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.

Add IRL privacy center page and location-privacy invariant tests

nirholas6d2182accd07
diff --git a/api/irl/pins.js b/api/irl/pins.js
index f96afaf8b..eba78b4c9 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -21,6 +21,9 @@ import { WORD_BLACKLIST } from '../../src/profanity.js';
import { guardianConfig, assess, decide } from '../_lib/granite-guardian.js';
import { encodeGeohash } from '../_lib/geohash.js';
import { validateAppearance } from '../_lib/accessories.js';
+import { cacheGet, cacheSet } from '../_lib/cache.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+import { sha256 } from '../_lib/crypto.js';
// ── Moderation, safety & density caps (D4) ──────────────────────────────────
// Everything below makes the public, shared IRL world safe to launch: content
@@ -262,6 +265,76 @@ 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
+// each individual cell stays under the per-minute rate limit (a slow, methodical
+// grid never trips a burst counter). We track the set of distinct geocells a caller
+// reads within SWEEP_WINDOW_S in the shared cache (short TTL, capped) and fire ONE
+// deduped, COORDINATE-FREE ops alert when the count crosses SWEEP_CELL_THRESHOLD.
+//
+// Privacy discipline (mirrors redactUrl): the cache key and the alert carry only a
+// SHA-256 hash of the caller IP and the distinct-cell COUNT — never a coordinate,
+// never a raw IP, never a geocell value. The whole path is best-effort and wrapped
+// so it can never delay or fail the read it observes.
+const SWEEP_WINDOW_S = 120; // rolling observation window
+const SWEEP_CELL_THRESHOLD = 12; // distinct cells in the window that looks like a grid sweep
+const SWEEP_CELLS_TRACKED_MAX = 64; // cap the stored set so one caller can't bloat a cache entry
+
+export async function recordCellRead(ip, cell) {
+ if (!ip || !cell) return;
+ try {
+ const ipHash = (await sha256(ip)).slice(0, 16);
+ const key = `irl:sweep:${ipHash}`;
+ const prev = (await cacheGet(key)) || { cells: [], alerted: false };
+ const cells = Array.isArray(prev.cells) ? prev.cells : [];
+ if (!cells.includes(cell)) {
+ if (cells.length < SWEEP_CELLS_TRACKED_MAX) cells.push(cell);
+ }
+ const distinct = cells.length;
+ let alerted = prev.alerted === true;
+ if (distinct >= SWEEP_CELL_THRESHOLD && !alerted) {
+ alerted = true; // latch so we alert once per window, not every cell after the threshold
+ // Coordinate-free, IP-hash only. Deduped by the hash so a sustained sweep
+ // from one caller is one alert per dedup window, not a flood.
+ sendOpsAlert(
+ 'IRL sweep suspected',
+ `A single caller read ${distinct}+ distinct geocells from the /irl nearby feed within ${SWEEP_WINDOW_S}s (ip_hash ${ipHash}). Possible bulk location-harvest attempt; no coordinates logged.`,
+ { signature: `irl-sweep:${ipHash}` },
+ ).catch(() => {});
+ }
+ // Refresh the rolling window on every read so an active sweep keeps the entry warm.
+ await cacheSet(key, { cells, alerted }, SWEEP_WINDOW_S);
+ } catch {
+ /* best-effort telemetry — never block or fail the read */
+ }
+}
+
let _tableReady = false;
async function ensureTable() {
if (_tableReady) return;
@@ -557,9 +630,12 @@ 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.
+ // 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.
if (req.method === 'GET') {
- const rl = await limitOrFailOpen('publicIp', limits.publicIp, clientIp(req));
+ const rl = await limitFailClosedRead('publicIp', limits.publicIp, clientIp(req));
if (!rl.success) return rateLimited(res, rl);
}
@@ -720,6 +796,13 @@ export default wrap(async (req, res) => {
.filter(r => r.distance_m <= radius)
.sort((a, b) => a.distance_m - b.distance_m);
+ // Sweep anomaly detection (H7): record which geocell this caller just read.
+ // Reading many DISTINCT cells in a short window is sweep-shaped even when each
+ // cell stays under the rate limit; this fires a deduped, coordinate-free ops
+ // alert past the threshold. Best-effort and fire-and-forget — never awaited
+ // into the response path, never carries a coordinate.
+ recordCellRead(clientIp(req), encodeGeohash(lat, lng, GEOCELL_PRECISION));
+
return json(res, 200, { pins });
}
diff --git a/docs/internal/AGENT-WALLET-CUSTODY.md b/docs/internal/AGENT-WALLET-CUSTODY.md
new file mode 100644
index 000000000..a23eeb2f9
--- /dev/null
+++ b/docs/internal/AGENT-WALLET-CUSTODY.md
@@ -0,0 +1,197 @@
+# Agent Wallet Custody Model
+
+How three.ws holds, protects, spends, and lets owners recover the funds in an
+agent's **custodial Solana wallet** — and the procedure to rotate the key that
+protects them.
+
+Audience: engineers and security reviewers. This is the doc to read before
+touching anything that decrypts an agent secret or moves agent funds.
+
+---
+
+## What is custodial here
+
+Every agent gets a real Solana keypair generated server-side
+(`generateSolanaAgentWallet`, `api/_lib/agent-wallet.js`). The platform keeps the
+secret so the agent can act autonomously (trade, snipe, pay via x402) without a
+human signing each transaction. Concretely:
+
+- The 64-byte ed25519 secret is base64-encoded, then encrypted at rest with
+ **AES-256-GCM** and stored as `agent_identities.meta.encrypted_solana_secret`.
+ The public address is `meta.solana_address`.
+- The AES key is **derived from `JWT_SECRET`** via HKDF-SHA256 with a fixed salt
+ (`'agent-wallet-v1'`) and an empty info — see `deriveKey()` in
+ `api/_lib/agent-wallet.js`. There is no per-wallet key; one server secret keys
+ every agent wallet's encryption.
+- Decryption happens **only** through `recoverSolanaAgentKeypair()`, and only
+ after the request has passed authentication + ownership checks at the calling
+ endpoint. Every recover call takes an `audit` argument carrying the **reason**.
+
+This is a deliberate custodial design: the value of autonomous agents requires
+the platform to be able to sign. The controls below make that trustworthy.
+
+## Where the secret may and may not appear
+
+| Place | Allowed? |
+| --- | --- |
+| `agent_identities.meta.encrypted_solana_secret` (encrypted at rest) | ✅ the only at-rest home |
+| In memory transiently, inside `recoverSolanaAgentKeypair`, to sign | ✅ |
+| Any API **response** body | ❌ never |
+| Any **log line** (`console.*`, `logger`, audit meta) | ❌ never |
+| Any **error message** or stack handed to a caller | ❌ never |
+| The custody audit trail `meta` jsonb | ❌ never — only the public address |
+
+The audit `git grep` that gates this (see "Verifying" below) must stay clean.
+The only endpoint that returns a raw secret key is `api/x402/vanity.js`, which
+returns the **user's own freshly-ground** keypair at provisioning time — that is
+not a custodial agent secret and is by design.
+
+## Decryption is gated + audited
+
+`recoverSolanaAgentKeypair(encryptedSecret, audit)` is the single decrypt path.
+Callers must:
+
+1. **Authenticate** the request (session cookie or bearer) and **verify
+ ownership** (`agent_identities.user_id === auth.userId`) before calling.
+2. Pass `audit = { agentId, userId, reason, meta }`. The reason is a short verb
+ such as `withdraw`, `x402_pay_tool_call`, `sniper_buy`, `pumpfun_action`.
+
+Each recover writes **two** audit records, fire-and-forget:
+
+- a `usage_events` row (`kind: 'solana_key_use'`, `tool: <reason>`), and
+- an `agent_custody_events` row (`event_type: 'key_recover'`, `reason: <reason>`)
+ — the owner-viewable custody trail.
+
+So every single decrypt of a custodial key is traceable to who, when, and why.
+
+## Spend governance — one policy, enforced everywhere
+
+`api/_lib/agent-trade-guards.js` is the **single** spend policy. Limits live on
+`agent_identities.meta.spend_limits`:
+
+```
+{ daily_usd, per_tx_usd, withdraw_allowlist: [base58…] }
+```
+
+- `daily_usd` — rolling-24h USD-equivalent outflow ceiling.
+- `per_tx_usd` — max USD-equivalent for any single outbound transaction.
+- `withdraw_allowlist` — if non-empty, withdrawals may only target these
+ addresses.
+
+Limits are **opt-in**: an unset ceiling (`null`) means "no global cap", so an
+agent keeps its own per-feature caps (e.g. the sniper's lamports budget) until an
+owner sets a ceiling. Once set, the ceiling is a **hard** limit applied uniformly
+across **every** outbound path via `enforceSpendLimit(...)`:
+
+| Path | Enforced in | Recorded as |
+| --- | --- | --- |
+| Withdraw | `api/agents/solana-wallet.js` `handleWithdraw` | `spend` / `withdraw` |
+| x402 pay | `api/x402-pay.js` `runFlow` | `spend` / `x402` |
+| Snipe | `workers/agent-sniper/executor.js` | `spend` / `snipe` |
+| Trade | the authenticated agent-wallet trade endpoint (calls the module) | `spend` / `trade` |
+
+Enforcement happens **before** any signing, so a breach moves no funds and
+returns a structured **4xx** (`SpendLimitError`, status 403) with the reason —
+never a 500. Every confirmed/pending outbound spend is written to
+`agent_custody_events` (`event_type: 'spend'`), which is also the ledger the
+daily ceiling sums over the trailing 24h.
+
+Denomination: SOL and USDC are always priceable (USDC is dollar-denominated; SOL
+is priced via `solUsdPrice()` — Jupiter Lite primary, CoinGecko fallback). An
+arbitrary SPL token that cannot be priced is governed by the withdraw allowlist
+(and the per-user withdraw rate limit), not the USD cap — documented so a price
+outage can never strand an owner's own recovery withdrawal.
+
+## Withdraw / sweep — the recovery path
+
+`POST /api/agents/:id/solana/withdraw` (also reachable as `…/wallet/withdraw`),
+owner-authenticated, server-signed:
+
+- Validates the destination is a real base58, **on-curve** address (rejects PDAs,
+ which could make funds unrecoverable) and not the wallet itself.
+- On a SOL **Max**, reserves the rent-exempt minimum + a fee headroom so a sweep
+ can never brick the account or fail on fees. SPL transfers ensure the wallet
+ holds enough SOL to pay the fee and (if needed) open the recipient's token
+ account.
+- **Idempotent**: a client `idempotency_key` claims a row under a unique index; a
+ retry with the same key never double-sends (returns the prior signature when
+ confirmed, `in_progress` while pending). An ambiguous confirmation leaves the
+ row `pending` and hands back the signature to verify rather than risking a
+ double-spend on retry.
+- Honors a `simulate` flag for tests; defaults to a live submit + confirm. No
+ fabricated confirmations.
+
+## The custody audit trail
+
+`agent_custody_events` (migration
+`api/_lib/migrations/20260617000000_agent_custody.sql`) is the per-agent,
+owner-viewable record of key recoveries, withdrawals, automated spends, and limit
+changes. Surfaced at `GET /api/agents/:id/solana/custody` and rendered in the
+Agent Wallet hub's Withdraw → Activity view. Withdrawals and limit changes are
+*also* mirrored into the platform-wide `audit_log` via `logAudit()`.
+
+---
+
+## Key rotation (`JWT_SECRET`)
+
+Because the AES key is derived from `JWT_SECRET`, **rotating `JWT_SECRET` without
+re-encryption invalidates every stored agent secret** — `recoverSolanaAgentKeypair`
+would fail to decrypt and no agent could sign or be swept. Rotation is therefore
+a **re-encryption migration**, not a config flip. It is documented here even
+though it is not being executed now.
+
+### Why rotation is coupled to the wallets
+
+`deriveKey()` reads `env.JWT_SECRET` at call time. There is no key version tag on
+the ciphertext today (the salt is the constant `'agent-wallet-v1'`). So the
+*current* `JWT_SECRET` must be able to decrypt *every* existing
+`encrypted_solana_secret`. Change the secret and every ciphertext becomes
+undecryptable.
+
+### Procedure (re-encrypt under a new secret)
+
+Run as a one-shot, reversible migration with **both** secrets available:
+
+1. **Stage both secrets.** Set `JWT_SECRET` (old, current) and a new
+ `JWT_SECRET_NEXT` in the environment. Do not remove the old one yet.
+2. **Snapshot.** Back up `agent_identities` (at least `id`, `meta`) so the
+ re-encryption is reversible.
+3. **Re-encrypt offline.** For each agent with a `meta.encrypted_solana_secret`:
+ decrypt with a key derived from the **old** `JWT_SECRET`, then re-encrypt with
+ a key derived from **`JWT_SECRET_NEXT`**, and write the new ciphertext back.
+ Do this in a script that imports the crypto helpers — the plaintext secret
+ must never be logged or persisted, only held in memory for the single
+ re-encrypt step. Process in batches; verify each new ciphertext decrypts under
+ the new key before writing.
+4. **Verify.** Spot-check that `recoverSolanaAgentKeypair` reproduces the same
+ `publicKey` (it must equal `meta.solana_address`) for a sample of agents using
+ the **new** key.
+5. **Cut over.** Promote `JWT_SECRET_NEXT` to `JWT_SECRET` and redeploy. Sessions
+ signed with the old `JWT_SECRET` will invalidate at cutover — expect users to
+ re-authenticate (acceptable; it is a security rotation).
+6. **Retire the old secret** once every wallet is confirmed re-encrypted and the
+ deploy is healthy. Destroy the snapshot per data-retention policy.
+
+### Hardening this further (future work)
+
+- **Version the ciphertext.** Prefix stored ciphertext with a key-version byte /
+ change the HKDF `info` per version so old and new ciphertexts can coexist
+ during a rolling rotation (decrypt-on-read, lazy re-encrypt-on-write) instead
+ of a big-bang migration.
+- **Separate the wallet KEK from `JWT_SECRET`.** A dedicated
+ `AGENT_WALLET_ENCRYPTION_KEY` would decouple session-secret rotation from
+ wallet re-encryption entirely. Migrating to it is itself a re-encryption pass
+ (same procedure as above, old key = `JWT_SECRET`, new key = the dedicated KEK).
+- **Move to a KMS / HSM.** Wrap the data key with a managed KMS key so the raw
+ KEK never lives in an env var; rotation becomes a KMS key rotation + re-wrap.
+
+---
+
+## Verifying
+
+- **No secret leaks:** `git grep -nE "encrypted_solana_secret|secretKey" api/`
+ must show only at-rest storage, the internal recover/generate helpers, and
+ validation-message strings — never a value in a response, log, or error.
+- **Tests:** withdraw (SOL + SPL, Max rent/fee reserve, idempotency), spend-limit
+ enforcement (per-tx, daily, allowlist), and address validation are covered in
+ `tests/agent-custody-guards.test.js` and `tests/agent-wallet-withdraw.test.js`.
diff --git a/pages/irl-privacy.html b/pages/irl-privacy.html
new file mode 100644
index 000000000..66910d2be
--- /dev/null
+++ b/pages/irl-privacy.html
@@ -0,0 +1,389 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <title>How location works on IRL — three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="description" content="On three.ws IRL, a placed agent is private by location: it appears only to people physically standing within a few dozen metres of it — never on a map, a list, or a public directory. Here's exactly what is shared, what is not, and how your camera, motion, and location are used." />
+ <meta name="robots" content="index, follow" />
+ <link rel="canonical" href="https://three.ws/irl-privacy" />
+ <meta property="og:type" content="article" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/irl-privacy" />
+ <meta property="og:title" content="How location works on IRL — three.ws" />
+ <meta property="og:description" content="Placed agents are private by location — discovered only in person, never listed or mapped. What's shared, what isn't, and how your sensors are used." />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="How location works on IRL — three.ws" />
+ <meta name="twitter:description" content="Placed agents are private by location — discovered only in person, never listed or mapped." />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+ <link rel="stylesheet" href="/tokens.css" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ .ip-wrap {
+ max-width: 760px;
+ margin: 0 auto;
+ padding: clamp(56px, 9vw, 96px) clamp(18px, 5vw, 24px) 96px;
+ }
+
+ /* ── Hero ── */
+ .ip-hero { display: flex; flex-direction: column; align-items: flex-start; gap: 20px; }
+ .ip-eyebrow {
+ display: inline-flex; align-items: center; gap: 9px;
+ font: var(--weight-semibold) var(--text-2xs)/1 var(--font-body);
+ letter-spacing: 0.11em; text-transform: uppercase;
+ color: #7ec8e3;
+ background: rgba(126, 200, 227, 0.10);
+ border: 1px solid rgba(126, 200, 227, 0.28);
+ border-radius: var(--radius-pill);
+ padding: 6px 12px 6px 8px;
+ }
+ .ip-eyebrow img { width: 18px; height: 18px; border-radius: 5px; display: block; }
+ .ip-hero h1 {
+ font-family: var(--font-display);
+ font-size: clamp(28px, 6.5vw, 44px);
+ line-height: 1.08;
+ letter-spacing: -0.025em;
+ font-weight: var(--weight-semibold);
+ color: var(--ink-bright, #fff);
+ margin: 0;
+ }
+ .ip-hero h1 .accent { color: #7ec8e3; }
+ .ip-lede {
+ font-size: clamp(15px, 2.6vw, 18px);
+ line-height: 1.62;
+ color: var(--ink-dim, #aeb6c8);
+ margin: 0;
+ max-width: 60ch;
+ }
+ .ip-lede strong { color: var(--ink, #e8e8e8); font-weight: var(--weight-semibold); }
+ .ip-updated {
+ font: var(--weight-regular) var(--text-sm)/1 var(--font-body);
+ color: var(--ink-faint, rgba(255,255,255,0.45));
+ }
+
+ /* ── Generic section ── */
+ .ip-sec { margin-top: clamp(40px, 7vw, 60px); }
+ .ip-sec > h2 {
+ font-family: var(--font-display);
+ font-size: clamp(19px, 3.6vw, 24px);
+ letter-spacing: -0.02em;
+ font-weight: var(--weight-semibold);
+ color: var(--ink-bright, #fff);
+ margin: 0 0 6px;
+ }
+ .ip-sec > .ip-sub {
+ font-size: var(--text-md);
+ line-height: 1.6;
+ color: var(--ink-dim, #aeb6c8);
+ margin: 0 0 20px;
+ max-width: 62ch;
+ }
+
+ /* ── Fact cards ── */
+ .ip-cards { display: grid; gap: 12px; }
+ .ip-card {
+ display: flex; gap: 14px; align-items: flex-start;
+ padding: 18px;
+ background: var(--surface-1, rgba(255,255,255,0.03));
+ border: 1px solid var(--stroke, rgba(255,255,255,0.08));
+ border-radius: var(--radius-lg, 14px);
+ transition: border-color 0.18s ease, transform 0.18s ease, background 0.18s ease;
+ }
+ .ip-card:hover { border-color: var(--stroke-strong, rgba(255,255,255,0.16)); transform: translateY(-1px); }
+ .ip-card .ip-ic {
+ flex-shrink: 0;
+ width: 40px; height: 40px;
+ display: flex; align-items: center; justify-content: center;
+ border-radius: 11px;
+ background: rgba(126, 200, 227, 0.10);
+ color: #7ec8e3;
+ }
+ .ip-card .ip-ic svg { width: 21px; height: 21px; }
+ .ip-card.is-deny .ip-ic { background: rgba(248, 113, 113, 0.10); color: #f87171; }
+ .ip-card.is-allow .ip-ic { background: rgba(74, 222, 128, 0.10); color: #4ade80; }
+ .ip-card h3 {
+ font-size: 15px; font-weight: var(--weight-semibold);
+ color: var(--ink, #eef1f7); margin: 1px 0 4px;
+ }
+ .ip-card p {
+ font-size: var(--text-md); line-height: 1.55;
+ color: var(--ink-dim, #aeb6c8); margin: 0;
+ }
+
+ /* ── Two-column compare (can / cannot) ── */
+ .ip-compare { display: grid; gap: 12px; grid-template-columns: 1fr 1fr; }
+ @media (max-width: 560px) { .ip-compare { grid-template-columns: 1fr; } }
+ .ip-col {
+ padding: 18px;
+ border-radius: var(--radius-lg, 14px);
+ border: 1px solid var(--stroke, rgba(255,255,255,0.08));
+ background: var(--surface-1, rgba(255,255,255,0.03));
+ }
+ .ip-col h3 {
+ display: flex; align-items: center; gap: 8px;
+ font-size: 13px; font-weight: var(--weight-semibold);
+ letter-spacing: 0.04em; text-transform: uppercase;
+ margin: 0 0 12px;
+ }
+ .ip-col.is-yes h3 { color: #4ade80; }
+ .ip-col.is-no h3 { color: #f87171; }
+ .ip-col ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
+ .ip-col li {
+ font-size: var(--text-md); line-height: 1.5;
+ color: var(--ink-dim, #aeb6c8);
+ padding-left: 22px; position: relative;
+ }
+ .ip-col li::before {
+ position: absolute; left: 0; top: 0;
+ font-weight: 700;
+ }
+ .ip-col.is-yes li::before { content: "✓"; color: #4ade80; }
+ .ip-col.is-no li::before { content: "✕"; color: #f87171; }
+
+ /* ── Sensor rows ── */
+ .ip-sensors { display: flex; flex-direction: column; gap: 12px; }
+ .ip-sensor {
+ display: flex; gap: 14px; align-items: flex-start;
+ padding: 16px 18px;
+ background: var(--surface-1, rgba(255,255,255,0.03));
+ border: 1px solid var(--stroke, rgba(255,255,255,0.08));
+ border-radius: var(--radius-lg, 14px);
+ }
+ .ip-sensor .ip-ic {
+ flex-shrink: 0; width: 38px; height: 38px;
+ display: flex; align-items: center; justify-content: center;
+ border-radius: 10px;
+ background: var(--surface-2, rgba(255,255,255,0.05));
+ color: var(--ink, #cdd6e4);
+ }
+ .ip-sensor .ip-ic svg { width: 20px; height: 20px; }
+ .ip-sensor h3 { font-size: 14.5px; font-weight: var(--weight-semibold); color: var(--ink, #eef1f7); margin: 1px 0 3px; }
+ .ip-sensor p { font-size: var(--text-md); line-height: 1.55; color: var(--ink-dim, #aeb6c8); margin: 0; }
+ .ip-sensor .ip-chip {
+ display: inline-block; margin-top: 8px;
+ font: var(--weight-medium) 11px/1 var(--font-body);
+ letter-spacing: 0.04em;
+ color: #4ade80;
+ background: rgba(74, 222, 128, 0.10);
+ border: 1px solid rgba(74, 222, 128, 0.22);
+ border-radius: var(--radius-pill);
+ padding: 5px 9px;
+ }
+
+ /* ── Controls callout ── */
+ .ip-controls {
+ margin-top: 14px;
+ padding: 18px;
+ border-radius: var(--radius-lg, 14px);
+ border: 1px solid var(--stroke, rgba(255,255,255,0.08));
+ background: var(--surface-1, rgba(255,255,255,0.03));
+ }
+ .ip-controls dl { margin: 0; display: flex; flex-direction: column; gap: 14px; }
+ .ip-controls dt { font-size: 14px; font-weight: var(--weight-semibold); color: var(--ink, #eef1f7); margin-bottom: 3px; }
+ .ip-controls dd { margin: 0; font-size: var(--text-md); line-height: 1.55; color: var(--ink-dim, #aeb6c8); }
+
+ /* ── Closing CTA ── */
+ .ip-cta {
+ margin-top: clamp(44px, 8vw, 64px);
+ padding: 28px;
+ border-radius: var(--radius-lg, 14px);
+ border: 1px solid var(--stroke-strong, rgba(255,255,255,0.14));
+ background: linear-gradient(180deg, rgba(126,200,227,0.07), rgba(126,200,227,0.02));
+ text-align: center;
+ }
+ .ip-cta h2 { font-family: var(--font-display); font-size: 21px; font-weight: var(--weight-semibold); color: var(--ink-bright, #fff); margin: 0 0 8px; }
+ .ip-cta p { font-size: var(--text-md); line-height: 1.55; color: var(--ink-dim, #aeb6c8); margin: 0 0 18px; }
+ .ip-actions { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; }
+ .ip-btn {
+ display: inline-flex; align-items: center; gap: 7px;
+ font: var(--weight-semibold) 14px/1 var(--font-body);
+ padding: 12px 18px;
+ border-radius: var(--radius-md, 10px);
+ text-decoration: none;
+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.12s ease, color 0.15s ease;
+ }
+ .ip-btn--primary { background: #fff; color: #0a0a0a; border: 1px solid #fff; }
+ .ip-btn--primary:hover { background: rgba(255,255,255,0.88); }
+ .ip-btn--ghost { background: transparent; color: var(--ink, #e8e8e8); border: 1px solid var(--stroke-strong, rgba(255,255,255,0.16)); }
+ .ip-btn--ghost:hover { background: var(--surface-2, rgba(255,255,255,0.06)); border-color: var(--stroke-strong, rgba(255,255,255,0.22)); }
+ .ip-btn:active { transform: translateY(1px); }
+ .ip-btn:focus-visible { outline: 2px solid #7ec8e3; outline-offset: 2px; }
+
+ /* ── Inline links ── */
+ .ip-link { color: #7ec8e3; text-decoration: none; border-bottom: 1px solid rgba(126,200,227,0.4); transition: border-color 0.15s ease, color 0.15s ease; }
+ .ip-link:hover { border-bottom-color: #7ec8e3; }
+ .ip-link:focus-visible { outline: 2px solid #7ec8e3; outline-offset: 2px; border-radius: 2px; }
+
+ .ip-foot-note {
+ margin-top: 32px;
+ font-size: var(--text-sm);
+ line-height: 1.6;
+ color: var(--ink-faint, rgba(255,255,255,0.45));
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .ip-card, .ip-card:hover, .ip-btn, .ip-btn:active { transition: none; transform: none; }
+ }
+ </style>
+</head>
+<body>
+ <div id="nav-container"></div>
+
+ <main class="ip-wrap">
+ <header class="ip-hero">
+ <span class="ip-eyebrow"><img src="/irl-logo.svg" alt="" aria-hidden="true" /> IRL · Location privacy</span>
+ <h1>Your agents are <span class="accent">private by location</span>.</h1>
+ <p class="ip-lede">
+ When you place a 3D agent at a real spot on <strong>IRL</strong>, it isn't broadcast to a feed
+ or dropped on a public map. It becomes visible to someone <strong>only when they're physically
+ standing next to it</strong> and point their camera. You discover agents by walking up to
+ them — never by browsing where they are.
+ </p>
+ <p class="ip-updated">Last updated 2026-06-17</p>
+ </header>
+
+ <section class="ip-sec" aria-labelledby="ip-how-h">
+ <h2 id="ip-how-h">How it works, in one line</h2>
+ <p class="ip-sub">
+ There is no list, no map, and no directory of where agents are — not for other users, and not
+ public. Your own placements are visible only to you, in your dashboard. Everyone else can find
+ an agent only by being near it in person.
+ </p>
+ <div class="ip-cards">
+ <article class="ip-card">
+ <span class="ip-ic" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0z"/><circle cx="12" cy="10" r="3"/></svg></span>
+ <div>
+ <h3>Only people right next to it</h3>
+ <p>A placed agent appears to someone only when they're physically within a few dozen metres of it. Walk away and it's out of reach — there's no way to view it from across town.</p>
+ </div>
+ </article>
+ <article class="ip-card">
+ <span class="ip-ic" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><line x1="3" y1="3" x2="21" y2="21"/></svg></span>
+ <div>
+ <h3>Never tied to your identity</h3>
+ <p>When others come across an agent nearby, they see an avatar at a spot — never your account, your device, or who placed it. Owner identity is stripped before anything leaves our servers.</p>
+ </div>
+ </article>
+ <article class="ip-card">
+ <span class="ip-ic" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 14"/></svg></span>
+ <div>
+ <h3>Gone on your terms</h3>
+ <p>Agents you place without signing in expire on their own after 7 days. Anything you place is yours to remove instantly from your dashboard at any time.</p>
+ </div>
+ </article>
+ </div>
+ </section>
+
+ <section class="ip-sec" aria-labelledby="ip-cmp-h">
+ <h2 id="ip-cmp-h">What others can and can't see</h2>
+ <p class="ip-sub">
+ While you're using IRL, the only thing visible to nearby people is anonymous presence —
+ and a coarse ghost, if you choose to turn it on. Your exact position never leaves your device.
+ </p>
+ <div class="ip-compare">
+ <div class="ip-col is-yes">
+ <h3>What others can see</h3>
+ <ul>
+ <li>An anonymous "someone is viewing nearby" count when you're in the same area</li>
+ <li>A coarse ghost marker — but only if you opt in, and only snapped to a rough area, never your precise GPS</li>
+ <li>An agent placed at a spot, once they're standing near it themselves</li>
+ <li>An ambient reaction (a heart or a wave) when someone interacts with an agent you're both standing near</li>
+ </ul>
+ </div>
+ <div class="ip-col is-no">
+ <h3>What no one can see</h3>
+ <ul>
+ <li>A list, map, feed, or directory of where agents are placed</li>
+ <li>Your exact GPS coordinates — they stay on your device unless you place a pin there</li>
+ <li>Who placed any agent — no account or device id is ever attached</li>
+ <li>Where you are when you're not within reach of them in person</li>
+ </ul>
+ </div>
+ </div>
+ </section>
+
+ <section class="ip-sec" aria-labelledby="ip-sensors-h">
+ <h2 id="ip-sensors-h">How your camera, motion, and location are used</h2>
+ <p class="ip-sub">
+ IRL is a phone-camera experience built on three sensors. Each is used to render the scene
+ on your device — and each is something you grant, and can change, at any time.
+ </p>
+ <div class="ip-sensors">
+ <div class="ip-sensor">
+ <span class="ip-ic" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M23 7 16 12l7 5V7z"/><rect x="1" y="5" width="15" height="14" rx="2.5"/></svg></span>
+ <div>
+ <h3>Camera</h3>
+ <p>Renders the live AR passthrough so agents look anchored to the real world behind them. The video is drawn on your screen only — frames are never uploaded or stored.</p>
+ <span class="ip-chip">Processed on-device</span>
+ </div>
+ </div>
+ <div class="ip-sensor">
+ <span class="ip-ic" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><polygon points="16 8 13.5 13.5 8 16 10.5 10.5 16 8"/></svg></span>
+ <div>
+ <h3>Motion &amp; orientation</h3>
+ <p>Reads your phone's gyroscope so agents stay locked in place as you turn to look around. Used in real time to position the scene; nothing is sent off your device.</p>
+ <span class="ip-chip">Processed on-device</span>
+ </div>
+ </div>
+ <div class="ip-sensor">
+ <span class="ip-ic" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0z"/><circle cx="12" cy="10" r="3"/></svg></span>
+ <div>
+ <h3>Location</h3>
+ <p>Lets you place an agent at a real spot and discover the ones near you. We only ever check what's within a few dozen metres of where you are right now — never a wider area — and your position is never shared with other users.</p>
+ <span class="ip-chip">Used only for proximity</span>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="ip-sec" aria-labelledby="ip-ctrl-h">
+ <h2 id="ip-ctrl-h">The controls you hold</h2>
+ <p class="ip-sub">
+ Open <strong>Location &amp; privacy</strong> from the IRL top bar to adjust any of these. They're off
+ or private by default — you turn them on, never the other way around.
+ </p>
+ <div class="ip-controls">
+ <dl>
+ <dt>Discovery precision — Precise or Approximate</dt>
+ <dd>Approximate keeps your exact position off our servers while you browse: nearby agents resolve a little less precisely in exchange. Placement is always exactly where you choose.</dd>
+ <dt>Appear to others nearby — off by default</dt>
+ <dd>When on, people viewing the same area see you as a coarse ghost marker snapped to a rough area. The anonymous presence count is shared either way; your precise location never is.</dd>
+ <dt>Your placements — remove anytime</dt>
+ <dd>Every agent you've placed is listed in your dashboard, visible only to you. Remove any of them instantly, and anonymous pins expire on their own after 7 days.</dd>
+ </dl>
+ </div>
+ </section>
+
+ <section class="ip-cta" aria-labelledby="ip-cta-h">
+ <h2 id="ip-cta-h">That's the whole deal.</h2>
+ <p>Private by location, discovered in person, controlled by you. Ready to bring your agents into the real world?</p>
+ <div class="ip-actions">
+ <a class="ip-btn ip-btn--primary" href="/irl">Open IRL</a>
+ <a class="ip-btn ip-btn--ghost" href="/legal/privacy">Privacy policy</a>
+ </div>
+ </section>
+
+ <p class="ip-foot-note">
+ Questions about how your data is handled? Read our full
+ <a class="ip-link" href="/legal/privacy">privacy policy</a> or email
+ <a class="ip-link" href="mailto:[email protected]">[email protected]</a>.
+ </p>
+ </main>
+
+ <script type="module" src="/nav.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+</body>
+</html>
diff --git a/pages/irl.html b/pages/irl.html
index 16364b7bf..d5c262cb6 100644
--- a/pages/irl.html
+++ b/pages/irl.html
@@ -5,9 +5,12 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<meta name="theme-color" content="#000000" />
- <!-- Realtime pin sync (D1) — the IRL world runs as a room on the same Colyseus
- host as /walk. Lets nearby pins stream live; absent/unreachable it falls back
- to polling automatically (see src/irl-net.js). -->
+ <!-- Live presence + reactions room — the IRL world runs as a room on the same
+ Colyseus host as /walk. It carries an anonymous "viewing nearby" count and
+ opt-in ghost markers ONLY; placed agents are never synced here. Agents are
+ private by location and discovered solely through the per-viewer proximity
+ read in api/irl/pins.js. Absent/unreachable, presence is simply hidden and
+ discovery still works via the proximity poll (see src/irl-net.js). -->
<meta name="irl-server" content="wss://three-ws-multiplayer-93741856042.us-central1.run.app" />
<title>IRL · three.ws</title>
<meta name="description" content="Walk a 3D avatar in your real space. Camera AR passthrough, joystick movement, tap-to-place objects." />
@@ -214,6 +217,13 @@
.irl-share-btn[disabled] { opacity: 0.6; cursor: progress; }
/* L3 — icon-only "Location & privacy" control sits beside Share */
.irl-privacy-btn { padding: 6px; display: inline-flex; align-items: center; justify-content: center; margin-right: 8px; }
+ /* Task 03 — icon-only arrival-cue mute toggle (sound on/off icon swap) */
+ .irl-cue-mute { padding: 6px; display: inline-flex; align-items: center; justify-content: center; margin-right: 8px; }
+ .irl-cue-mute .irl-cue-off { display: none; }
+ .irl-cue-mute.is-muted .irl-cue-on { display: none; }
+ .irl-cue-mute.is-muted .irl-cue-off { display: inline; }
+ .irl-cue-mute.is-muted { color: var(--text-3); }
+ .irl-cue-mute[aria-pressed="false"] { color: var(--green); border-color: rgba(74,222,128,0.32); }
/* ── Joystick ────────────────────────────────────────────── */
#irl-joystick {
@@ -691,6 +701,101 @@
.irl-presence-chip::before { animation: none; }
}
+ /* ── Proximity-arrival cue (task 03) ─────────────────────── */
+ /* Transient "look around" banner — appears centred near the top, below the
+ topbar, when a new agent enters your bubble. Glassy, quiet, auto-dismisses. */
+ .irl-arrival-cue {
+ position: fixed;
+ top: calc(env(safe-area-inset-top, 0px) + 64px);
+ left: 50%;
+ z-index: 46;
+ max-width: min(92vw, 360px);
+ padding: 9px 16px;
+ border-radius: 999px;
+ font-size: 13px;
+ font-weight: 600;
+ letter-spacing: 0.01em;
+ text-align: center;
+ color: #eaf4ff;
+ background: rgba(18,26,40,0.82);
+ border: 1px solid rgba(120,170,255,0.42);
+ box-shadow: 0 6px 24px rgba(0,0,0,0.45), 0 0 18px rgba(120,170,255,0.18);
+ -webkit-backdrop-filter: blur(10px);
+ backdrop-filter: blur(10px);
+ pointer-events: none;
+ opacity: 0;
+ transform: translate(-50%, -10px);
+ transition: opacity 0.3s ease, transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
+ }
+ .irl-arrival-cue[hidden] { display: none; }
+ .irl-arrival-cue.is-visible {
+ opacity: 1;
+ transform: translate(-50%, 0);
+ }
+ .irl-arrival-cue::before {
+ content: '';
+ display: inline-block;
+ width: 7px;
+ height: 7px;
+ margin-right: 8px;
+ border-radius: 50%;
+ background: #8ec5ff;
+ box-shadow: 0 0 8px #8ec5ff;
+ vertical-align: middle;
+ animation: irl-cue-ping 1.4s ease-out infinite;
+ }
+ @keyframes irl-cue-ping {
+ 0% { transform: scale(0.7); opacity: 1; }
+ 70%, 100% { transform: scale(1.6); opacity: 0; }
+ }
+
+ /* Non-map directional hint — a soft glow + arrow riding the screen edge,
+ positioned via JS transform toward the nearest agent's bearing. The wrapper
+ is centred on the computed edge point (translate(-50%,-50%) + the JS offset);
+ the inner arrow rotates to aim along the bearing. */
+ .irl-dir-nudge {
+ position: fixed;
+ top: 0;
+ left: 0;
+ z-index: 12;
+ width: 64px;
+ height: 64px;
+ pointer-events: none;
+ opacity: 0;
+ transition: opacity 0.35s ease;
+ will-change: transform, opacity;
+ }
+ .irl-dir-nudge[hidden] { display: none; }
+ .irl-dir-nudge.is-visible { opacity: 1; }
+ .irl-dir-nudge-glow {
+ position: absolute;
+ inset: 0;
+ border-radius: 50%;
+ background: radial-gradient(circle, rgba(140,197,255,0.55) 0%, rgba(140,197,255,0.18) 45%, transparent 72%);
+ animation: irl-nudge-breathe 1.8s ease-in-out infinite;
+ }
+ .irl-dir-nudge-arrow {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: #d6ecff;
+ filter: drop-shadow(0 0 6px rgba(140,197,255,0.85));
+ transition: transform 0.18s ease-out;
+ }
+ @keyframes irl-nudge-breathe {
+ 0%, 100% { transform: scale(0.86); opacity: 0.7; }
+ 50% { transform: scale(1.08); opacity: 1; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .irl-arrival-cue { transition: opacity 0.001s; }
+ .irl-arrival-cue::before { animation: none; }
+ .irl-dir-nudge-glow { animation: none; opacity: 0.9; }
+ .irl-dir-nudge-arrow { transition: none; }
+ .irl-dir-nudge { transition: opacity 0.001s; }
+ }
+
/* Radar minimap */
#irl-radar {
position: fixed;
@@ -1613,12 +1718,33 @@
unless the live stream is up and more than just you are here. -->
<span id="irl-presence-chip" class="irl-presence-chip" hidden role="status" aria-live="polite"></span>
</div>
+ <button class="irl-share-btn irl-cue-mute" id="irl-cue-mute" type="button" aria-pressed="false" aria-label="Arrival sound on — tap to mute" title="Arrival sound on">
+ <svg class="irl-cue-on" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M11 5 6 9H2v6h4l5 4z"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M19 5a9 9 0 0 1 0 14"/></svg>
+ <svg class="irl-cue-off" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M11 5 6 9H2v6h4l5 4z"/><line x1="22" y1="9" x2="16" y2="15"/><line x1="16" y1="9" x2="22" y2="15"/></svg>
+ </button>
<button class="irl-share-btn irl-privacy-btn" id="irl-privacy-btn" type="button" aria-label="Location & privacy" title="Location & privacy">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9 12 2 2 4-4"/></svg>
</button>
<button class="irl-share-btn" id="irl-share-btn" type="button" aria-label="Share">Share</button>
</header>
+<!-- Proximity-arrival cue (task 03): a transient "look around" banner when a new
+ agent enters your ~40 m bubble. aria-live polite so a screen reader announces
+ the arrival without stealing focus. Filled + shown by src/irl.js. -->
+<div id="irl-arrival-cue" class="irl-arrival-cue" role="status" aria-live="polite" hidden></div>
+
+<!-- Non-map directional hint (task 03): a soft edge glow + arrow pointing toward
+ the nearest in-range agent's bearing, recomputed as the device rotates and
+ faded once that agent is on-screen. A *direction*, never a map or a distance.
+ aria-hidden — the banner above is the accessible announcement; this is purely
+ a visual nudge that tracks live camera motion. -->
+<div id="irl-dir-nudge" class="irl-dir-nudge" aria-hidden="true" hidden>
+ <span class="irl-dir-nudge-glow"></span>
+ <span class="irl-dir-nudge-arrow">
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5"/><path d="m6 11 6-6 6 6"/></svg>
+ </span>
+</div>
+
<!-- E1 permission re-request chips — a denied sensor leaves a one-tap recovery
chip here; src/irl/onboarding.js shows/hides this strip and renders into it. -->
<div id="irl-perm-chips" class="irl-perm-chips" hidden aria-label="Permissions needing attention"></div>
diff --git a/scripts/irl-d2-smoke.mjs b/scripts/irl-d2-smoke.mjs
index cb62c3d4f..3a84feda8 100644
--- a/scripts/irl-d2-smoke.mjs
+++ b/scripts/irl-d2-smoke.mjs
@@ -2,7 +2,8 @@
//
// node scripts/irl-d2-smoke.mjs
//
-// Where irl-d1-smoke proves pin liveness, this proves the PRESENCE contract end-
+// Pins are never carried over the realtime room — they're discovered only by the
+// per-viewer proximity read. This proves the PRESENCE contract end-
// to-end: it boots the REAL multiplayer server (the same multiplayer/src/index.js
// prod runs, with the irl_world room wired exactly as deployed), connects two
// colyseus.js clients to one geocell room, and asserts the spec's acceptance
diff --git a/src/irl.js b/src/irl.js
index 5d11a89e4..e7631b5e4 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -405,6 +405,9 @@ function disableAR() {
}
cameraBtn.addEventListener('click', () => {
+ // Unlock the arrival-cue chime inside this real gesture (same tap that grants
+ // camera + motion), so it can play later without an autoplay-policy warning.
+ unlockArrivalAudio();
if (arActive) disableAR();
else enableAR();
});
@@ -1996,6 +1999,191 @@ function emitPinStable(pin) {
}
}
+// ── Proximity-arrival cue + non-map directional hint (task 03) ──────────────
+// We deleted the list and the radar on purpose: a pin's location is private and
+// you find an agent only by physically walking into its ~40 m bubble. The cost is
+// that you can be 15 m away, facing the wrong way, and never know. This is the cue
+// that fixes it — the in-world equivalent of hearing a sound nearby. When the
+// hysteresis band promotes a genuinely new agent into range (emitPinStable, task
+// 04), we fire a quiet, rate-limited burst: an optional haptic, an optional soft
+// chime, and an aria-live "look around" banner — then a soft edge glow points
+// toward the nearest in-range agent and fades the moment you turn to face it. The
+// hint reveals a *direction*, never a list or a coordinate (proximity-cue.js).
+//
+// Sound is opt-out (a persisted mute toggle) and the WebAudio context is only ever
+// resumed on the camera-start tap (unlockArrivalAudio), so there is never an
+// autoplay-policy warning. The animated glow honours prefers-reduced-motion.
+
+const CUE_MUTE_KEY = 'irl_cue_muted_v1';
+let _cueMuted = (() => { try { return localStorage.getItem(CUE_MUTE_KEY) === '1'; } catch { return false; } })();
+let _lastCueAt = null; // ms of the last fired cue (global cooldown)
+let _audioCtx = null; // lazily created, resumed on the camera gesture
+let _audioUnlocked = false;
+
+// Resume / create the WebAudio context inside a real user gesture so the chime is
+// never an autoplay violation. Called from the camera-start tap (the same gesture
+// that grants camera + motion), and idempotent.
+function unlockArrivalAudio() {
+ if (_audioUnlocked) { _audioCtx?.resume?.().catch(() => {}); return; }
+ const Ctx = window.AudioContext || window.webkitAudioContext;
+ if (!Ctx) return; // no WebAudio — haptic + banner still fire
+ try {
+ _audioCtx = new Ctx();
+ _audioCtx.resume?.().catch(() => {});
+ _audioUnlocked = true;
+ } catch { _audioCtx = null; }
+}
+
+// A short, quiet two-note chime — a gentle "✨" rather than a notification ping.
+// Synthesised (no asset to load/decode), gated by the mute toggle and a live,
+// unlocked context. Two sine partials with a fast attack + soft exponential decay.
+function playArrivalChime() {
+ if (_cueMuted || !_audioCtx || _audioCtx.state === 'closed') return;
+ try {
+ const ctx = _audioCtx;
+ const now = ctx.currentTime;
+ const master = ctx.createGain();
+ master.gain.setValueAtTime(0.0001, now);
+ master.gain.exponentialRampToValueAtTime(0.16, now + 0.012);
+ master.gain.exponentialRampToValueAtTime(0.0001, now + 0.9);
+ master.connect(ctx.destination);
+ // Two ascending notes (a major sixth) for a friendly, non-alarming arrival.
+ [[659.25, 0], [987.77, 0.11]].forEach(([freq, at]) => {
+ const osc = ctx.createOscillator();
+ const g = ctx.createGain();
+ osc.type = 'sine';
+ osc.frequency.setValueAtTime(freq, now + at);
+ g.gain.setValueAtTime(0.0001, now + at);
+ g.gain.exponentialRampToValueAtTime(1, now + at + 0.02);
+ g.gain.exponentialRampToValueAtTime(0.0001, now + at + 0.5);
+ osc.connect(g); g.connect(master);
+ osc.start(now + at);
+ osc.stop(now + at + 0.55);
+ });
+ } catch { /* audio is a flourish — never let it break discovery */ }
+}
+
+// Persisted mute toggle (topbar button #irl-cue-mute). Reflects state into the
+// button's aria-pressed + icon so it's an honest, accessible control.
+function setCueMuted(muted) {
+ _cueMuted = !!muted;
+ try { localStorage.setItem(CUE_MUTE_KEY, _cueMuted ? '1' : '0'); } catch {}
+ syncCueMuteButton();
+}
+function syncCueMuteButton() {
+ const btn = document.getElementById('irl-cue-mute');
+ if (!btn) return;
+ btn.setAttribute('aria-pressed', _cueMuted ? 'true' : 'false');
+ btn.classList.toggle('is-muted', _cueMuted);
+ btn.setAttribute('aria-label', _cueMuted ? 'Arrival sound off — tap to unmute' : 'Arrival sound on — tap to mute');
+ btn.title = _cueMuted ? 'Arrival sound off' : 'Arrival sound on';
+}
+
+// The transient "look around" banner. aria-live polite so a screen reader announces
+// the arrival without stealing focus; auto-dismisses, and a fresh arrival restarts
+// the timer rather than stacking banners.
+let _cueBannerTimer = null;
+function showArrivalBanner() {
+ const el = document.getElementById('irl-arrival-cue');
+ if (!el) return;
+ el.textContent = 'An agent is near — look around';
+ el.classList.add('is-visible');
+ el.hidden = false;
+ clearTimeout(_cueBannerTimer);
+ _cueBannerTimer = setTimeout(() => {
+ el.classList.remove('is-visible');
+ // Keep it in the DOM (hidden) so the next arrival re-announces cleanly.
+ setTimeout(() => { if (!el.classList.contains('is-visible')) el.hidden = true; }, 320);
+ }, 4200);
+}
+
+// Fire the full arrival cue for a freshly-in-range agent: haptic (where supported),
+// chime (unless muted), and the banner. Rate-limited by shouldCueArrival so a busy
+// corner where several agents drift in at once buzzes once, not like a slot machine.
+function fireArrivalCue() {
+ const now = Date.now();
+ if (!shouldCueArrival(now, _lastCueAt)) return;
+ _lastCueAt = now;
+ // Haptic — guarded; iOS Safari and many desktops ignore vibrate() entirely, so
+ // it's a bonus, never the cue. A short double-tap reads as "notice me".
+ try { navigator.vibrate?.([18, 40, 18]); } catch {}
+ playArrivalChime();
+ showArrivalBanner();
+}
+
+onPinStable(() => fireArrivalCue());
+
+// ── Directional nudge (non-map "that way" hint) ─────────────────────────────
+// A soft glow + arrow pinned to the screen edge pointing toward the NEAREST
+// in-range agent's current screen-relative bearing (recomputed every frame from
+// cameraYaw + the agent's world offset, so it tracks live as the user rotates). It
+// fades the instant that agent is comfortably on-screen — the visible avatar is
+// then its own cue. Never a minimap, never a distance readout: just a direction,
+// the in-world equivalent of "look over there". Honours reduced motion (the glow's
+// pulse is CSS-gated; the arrow still points, it just doesn't breathe).
+let _nudgeEl = null;
+let _nudgeArrowEl = null;
+let _nudgeVisible = false;
+// Throttle the DOM writes to ~20 Hz — the bearing changes smoothly and a full
+// per-frame style write is wasted work; CSS transitions cover the gaps.
+let _nudgeAccum = 0;
+const NUDGE_INTERVAL = 0.05;
+
+function _ensureNudgeEls() {
+ if (_nudgeEl) return;
+ _nudgeEl = document.getElementById('irl-dir-nudge');
+ _nudgeArrowEl = _nudgeEl?.querySelector('.irl-dir-nudge-arrow') ?? null;
+}
+
+// Pick the agent to point at and the camera's half-FOV, then either place + show
+// the glow toward an off-screen agent or fade it once we're facing the nearest one.
+// Reads only world offsets the scene already renders — no coordinate ever touched.
+function updateDirectionalNudge(dt) {
+ _nudgeAccum += dt;
+ if (_nudgeAccum < NUDGE_INTERVAL) return;
+ _nudgeAccum = 0;
+ _ensureNudgeEls();
+ if (!_nudgeEl) return;
+
+ // Candidates: every rendered in-range agent, measured from where we stand. The
+ // band distance (not the live AR-head distance) is the honest "how near is this
+ // agent to me" — stable as the camera pans.
+ let candidates = null;
+ for (const pin of nearbyPins) {
+ if (!pin.group) continue;
+ (candidates ??= []).push({ pin, distance: bandDistance(pin) });
+ }
+ const target = candidates && nearestAgent(candidates);
+ if (!target) { _hideNudge(); return; }
+
+ const wp = target.pin.group.position;
+ const relBearing = relativeBearing(wp.x, wp.z, cameraYaw);
+ // Half the camera's horizontal FOV (camera.fov is vertical; convert via aspect).
+ const aspect = window.innerWidth / Math.max(1, window.innerHeight);
+ const halfVFov = (camera.fov * Math.PI) / 180 / 2;
+ const halfHFov = Math.atan(Math.tan(halfVFov) * aspect);
+
+ // Already looking at the nearest agent (and it's actually drawing on-screen)? The
+ // avatar is the cue now — fade the hint.
+ if (isFacingAgent(relBearing, halfHFov) && pinOnScreen(target.pin)) { _hideNudge(); return; }
+
+ const { x, y, rotateDeg } = edgeNudgePlacement(relBearing, window.innerWidth, window.innerHeight);
+ _nudgeEl.style.transform = `translate(-50%, -50%) translate(${x}px, ${y}px)`;
+ if (_nudgeArrowEl) _nudgeArrowEl.style.transform = `rotate(${rotateDeg}deg)`;
+ if (!_nudgeVisible) {
+ _nudgeVisible = true;
+ _nudgeEl.hidden = false;
+ // Next frame so the transition runs from the hidden state.
+ requestAnimationFrame(() => { if (_nudgeVisible) _nudgeEl.classList.add('is-visible'); });
+ }
+}
+
+function _hideNudge() {
+ if (!_nudgeVisible) return;
+ _nudgeVisible = false;
+ _nudgeEl?.classList.remove('is-visible');
+}
+
// Briefly tint a pin's floating label so a deep-linked target (?highlight= or
// ?agent=) is easy to spot among the nearby agents. No-op for a missing pin/label.
function flashPinLabel(pin) {
@@ -3213,6 +3401,10 @@ function applyGhost(on) {
document.getElementById('irl-ghost-toggle')?.addEventListener('click', () => applyGhost(!getShareGhost()));
syncGhostToggle();
+// Arrival-cue mute toggle (task 03) — persisted; reflects state into the button.
+document.getElementById('irl-cue-mute')?.addEventListener('click', () => setCueMuted(!_cueMuted));
+syncCueMuteButton();
+
// L3 — Location & privacy center: honest disclosure + discovery precision +
// presence opt-in + a jump into pin management, all in one designed surface.
document.getElementById('irl-privacy-btn')?.addEventListener('click', () => {
@@ -4671,6 +4863,9 @@ function tick() {
updateReactions(dt);
// Gentle pulse on live presence ghosts (D2) — early-outs when none are present.
updateGhosts(dt);
+ // Non-map directional hint (task 03): point the edge glow toward the nearest
+ // in-range agent and fade it once it's on-screen. ~20 Hz internally, no map.
+ updateDirectionalNudge(dt);
// Radar DOM is rebuilt at ~5 Hz, not every frame (it was a per-frame churn).
_radarAccum += dt;
if (_radarAccum >= RADAR_INTERVAL) { _radarAccum = 0; updateRadar(); }
@@ -4949,7 +5144,7 @@ async function saveCalibrate() {
pin.lat = _cal.lat; pin.lng = _cal.lng;
pin.anchor_yaw_deg = _cal.yaw; pin.heading = Math.round(_cal.yaw);
pin.anchor_height_m = _cal.height;
- setStatus('Position calibrated — everyone nearby now sees it here');
+ setStatus('Position calibrated — saved here; nearby viewers update within ~10s');
exitCalibrate(false);
loadNearbyPins();
} catch (err) {
diff --git a/tests/agent-custody-guards.test.js b/tests/agent-custody-guards.test.js
new file mode 100644
index 000000000..d36fac3dd
--- /dev/null
+++ b/tests/agent-custody-guards.test.js
@@ -0,0 +1,190 @@
+// Unit tests for api/_lib/agent-trade-guards.js — the shared per-agent spend
+// policy + custody ledger that governs withdraw / x402 / snipe / trade.
+//
+// Covers: Solana address validation (base58, on-curve, PDA rejection),
+// spend-limit normalization, and enforcement of the per-tx + daily USD ceilings
+// and the withdraw allowlist. The DB + SOL price feed are mocked so these are
+// deterministic and fast.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Keypair, PublicKey, SystemProgram } from '@solana/web3.js';
+
+// ── mocks ─────────────────────────────────────────────────────────────────────
+const sqlState = { queue: [], calls: [] };
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ return sqlState.queue.length ? sqlState.queue.shift() : [];
+ }),
+}));
+
+vi.mock('../api/_lib/avatar-wallet.js', () => ({
+ solUsdPrice: vi.fn(async () => 200), // $200 / SOL
+}));
+
+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+
+const guards = await import('../api/_lib/agent-trade-guards.js');
+const {
+ validateSolanaAddress, normalizeSpendLimits, enforceSpendLimit, SpendLimitError,
+ getDailySpendUsd, lamportsToUsd, getSpendLimits,
+} = guards;
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+// ── address validation ─────────────────────────────────────────────────────────
+describe('validateSolanaAddress', () => {
+ it('accepts a real on-curve wallet address', () => {
+ const addr = Keypair.generate().publicKey.toBase58();
+ const r = validateSolanaAddress(addr);
+ expect(r.valid).toBe(true);
+ expect(r.onCurve).toBe(true);
+ expect(r.base58).toBe(addr);
+ });
+
+ it('flags a program-derived (off-curve) address as not on-curve', () => {
+ const [pda] = PublicKey.findProgramAddressSync([Buffer.from('custody-test')], SystemProgram.programId);
+ const r = validateSolanaAddress(pda.toBase58());
+ expect(r.valid).toBe(true);
+ expect(r.onCurve).toBe(false);
+ });
+
+ it('rejects non-base58 input', () => {
+ expect(validateSolanaAddress('not an address!').valid).toBe(false);
+ expect(validateSolanaAddress('not an address!').reason).toBe('not_base58');
+ });
+
+ it('rejects empty / non-string input', () => {
+ expect(validateSolanaAddress('').valid).toBe(false);
+ expect(validateSolanaAddress(null).valid).toBe(false);
+ expect(validateSolanaAddress(undefined).valid).toBe(false);
+ });
+
+ it('rejects a base58 string that is the wrong byte length', () => {
+ // 5 base58 chars passes the length pre-filter's lower bound? No — min 32.
+ expect(validateSolanaAddress('abc').valid).toBe(false);
+ });
+});
+
+// ── limit normalization ─────────────────────────────────────────────────────────
+describe('normalizeSpendLimits', () => {
+ it('defaults to unset ceilings + empty allowlist', () => {
+ const n = normalizeSpendLimits(undefined);
+ expect(n.daily_usd).toBeNull();
+ expect(n.per_tx_usd).toBeNull();
+ expect(n.withdraw_allowlist).toEqual([]);
+ });
+
+ it('coerces numeric strings and rejects negatives', () => {
+ expect(normalizeSpendLimits({ daily_usd: '50', per_tx_usd: 25 }).daily_usd).toBe(50);
+ expect(normalizeSpendLimits({ daily_usd: -5 }).daily_usd).toBeNull();
+ expect(normalizeSpendLimits({ per_tx_usd: 'abc' }).per_tx_usd).toBeNull();
+ });
+
+ it('filters invalid + de-dupes allowlist addresses', () => {
+ const a = Keypair.generate().publicKey.toBase58();
+ const n = normalizeSpendLimits({ withdraw_allowlist: [a, 'garbage', a] });
+ expect(n.withdraw_allowlist).toEqual([a]);
+ });
+
+ it('getSpendLimits reads off meta.spend_limits', () => {
+ const a = Keypair.generate().publicKey.toBase58();
+ const lim = getSpendLimits({ spend_limits: { daily_usd: 100, withdraw_allowlist: [a] } });
+ expect(lim.daily_usd).toBe(100);
+ expect(lim.withdraw_allowlist).toEqual([a]);
+ });
+});
+
+// ── enforcement ─────────────────────────────────────────────────────────────────
+describe('enforceSpendLimit', () => {
+ const noLimits = { daily_usd: null, per_tx_usd: null, withdraw_allowlist: [] };
+
+ it('passes when no ceilings are set', async () => {
+ const r = await enforceSpendLimit({ agentId: 'a', limits: noLimits, category: 'x402', usdValue: 9999 });
+ expect(r.ok).toBe(true);
+ });
+
+ it('blocks an over-limit single transaction with a 403 SpendLimitError', async () => {
+ await expect(
+ enforceSpendLimit({ agentId: 'a', limits: { ...noLimits, per_tx_usd: 10 }, category: 'x402', usdValue: 25 }),
+ ).rejects.toMatchObject({ name: 'SpendLimitError', code: 'per_tx_exceeded', status: 403 });
+ });
+
+ it('allows a transaction at the per-tx ceiling', async () => {
+ const r = await enforceSpendLimit({ agentId: 'a', limits: { ...noLimits, per_tx_usd: 10 }, category: 'x402', usdValue: 10 });
+ expect(r.ok).toBe(true);
+ });
+
+ it('blocks a withdraw to a non-allowlisted destination', async () => {
+ const allowed = Keypair.generate().publicKey.toBase58();
+ const other = Keypair.generate().publicKey.toBase58();
+ await expect(
+ enforceSpendLimit({ agentId: 'a', limits: { ...noLimits, withdraw_allowlist: [allowed] }, category: 'withdraw', usdValue: 1, destination: other }),
+ ).rejects.toMatchObject({ code: 'destination_not_allowed' });
+ });
+
+ it('allows a withdraw to an allowlisted destination', async () => {
+ const allowed = Keypair.generate().publicKey.toBase58();
+ const r = await enforceSpendLimit({ agentId: 'a', limits: { ...noLimits, withdraw_allowlist: [allowed] }, category: 'withdraw', usdValue: 1, destination: allowed });
+ expect(r.ok).toBe(true);
+ });
+
+ it('does not gate non-withdraw paths on the withdraw allowlist', async () => {
+ const allowed = Keypair.generate().publicKey.toBase58();
+ const r = await enforceSpendLimit({ agentId: 'a', limits: { ...noLimits, withdraw_allowlist: [allowed] }, category: 'x402', usdValue: 1, destination: 'whatever' });
+ expect(r.ok).toBe(true);
+ });
+
+ it('blocks when the rolling daily total would exceed the cap', async () => {
+ sqlState.queue.push([{ usd: 30 }]); // already spent today
+ await expect(
+ enforceSpendLimit({ agentId: 'a', limits: { ...noLimits, daily_usd: 50 }, category: 'snipe', usdValue: 25, network: 'mainnet' }),
+ ).rejects.toMatchObject({ code: 'daily_exceeded' });
+ });
+
+ it('allows when the daily total stays within the cap', async () => {
+ sqlState.queue.push([{ usd: 10 }]);
+ const r = await enforceSpendLimit({ agentId: 'a', limits: { ...noLimits, daily_usd: 50 }, category: 'snipe', usdValue: 25 });
+ expect(r.ok).toBe(true);
+ expect(r.dailySpentUsd).toBe(10);
+ });
+
+ it('skips the USD ceilings for an unpriceable asset (allowlist still applies)', async () => {
+ // usdValue null → daily/per-tx can't be evaluated; must not query or throw.
+ const r = await enforceSpendLimit({ agentId: 'a', limits: { ...noLimits, daily_usd: 1, per_tx_usd: 1 }, category: 'withdraw', usdValue: null, destination: Keypair.generate().publicKey.toBase58() });
+ expect(r.ok).toBe(true);
+ expect(sqlState.calls.length).toBe(0); // never summed the ledger
+ });
+
+ it('SpendLimitError is the exported class with the breach detail', async () => {
+ try {
+ await enforceSpendLimit({ agentId: 'a', limits: { daily_usd: null, per_tx_usd: 5, withdraw_allowlist: [] }, category: 'trade', usdValue: 50 });
+ throw new Error('should have thrown');
+ } catch (e) {
+ expect(e).toBeInstanceOf(SpendLimitError);
+ expect(e.detail.per_tx_usd).toBe(5);
+ expect(e.detail.usd).toBe(50);
+ }
+ });
+});
+
+// ── ledger reads ────────────────────────────────────────────────────────────────
+describe('getDailySpendUsd / lamportsToUsd', () => {
+ it('returns the summed USD from the ledger', async () => {
+ sqlState.queue.push([{ usd: 123.45 }]);
+ expect(await getDailySpendUsd('a', 'mainnet')).toBe(123.45);
+ });
+
+ it('treats a null sum as zero', async () => {
+ sqlState.queue.push([{ usd: null }]);
+ expect(await getDailySpendUsd('a')).toBe(0);
+ });
+
+ it('converts lamports to USD at the live price', async () => {
+ // 1 SOL at the mocked $200
+ expect(await lamportsToUsd(1_000_000_000n)).toBeCloseTo(200, 6);
+ });
+});
diff --git a/tests/agent-wallet-withdraw.test.js b/tests/agent-wallet-withdraw.test.js
new file mode 100644
index 000000000..af99d2c05
--- /dev/null
+++ b/tests/agent-wallet-withdraw.test.js
@@ -0,0 +1,273 @@
+// Integration tests for the custodial withdraw endpoint
+// (api/agents/solana-wallet.js handleWithdraw, POST /api/agents/:id/solana/withdraw).
+//
+// Proves at the handler layer:
+// 1. invalid destination → 400, key never recovered
+// 2. off-curve (PDA) destination → 400, key never recovered
+// 3. idempotency replay → 200 replayed, never re-sends
+// 4. spend-limit breach → 403 with the reason, key never recovered
+// 5. simulate=true → simulated result, never signs, never sends
+// 6. live SOL "max" withdraw → 200 confirmed signature, rent+fee reserved
+//
+// All Solana RPC, the agent key recovery, and the spend policy are mocked so the
+// orchestration is deterministic. Real spend-policy enforcement + address
+// validation are covered by tests/agent-custody-guards.test.js.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Keypair, PublicKey } from '@solana/web3.js';
+
+process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-secret-for-custody-withdraw';
+
+// ── auth ────────────────────────────────────────────────────────────────────
+const authState = { session: { id: 'user-1' } };
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+// ── db ──────────────────────────────────────────────────────────────────────
+const sqlState = { queue: [], calls: [] };
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ return sqlState.queue.length ? sqlState.queue.shift() : [];
+ }),
+}));
+
+// ── rate limit ──────────────────────────────────────────────────────────────
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ withdrawalPerUser: vi.fn(async () => ({ success: true })),
+ authIp: vi.fn(async () => ({ success: true })),
+ walletRead: vi.fn(async () => ({ success: true })),
+ auditLogRead: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+// ── cache / audit / usage ────────────────────────────────────────────────────
+vi.mock('../api/_lib/cache.js', () => ({ cacheGet: vi.fn(async () => null), cacheSet: vi.fn(async () => {}) }));
+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
+vi.mock('../api/_lib/usage.js', () => ({ recordEvent: vi.fn() }));
+vi.mock('../src/solana/sns.js', () => ({ reverseLookupAddress: vi.fn(async () => null) }));
+
+// ── Solana RPC (fake connection) ──────────────────────────────────────────────
+const connState = {
+ balance: 2_000_000_000, // 2 SOL
+ rentExempt: 890_880,
+ blockhash: Keypair.generate().publicKey.toBase58(), // valid 32-byte base58
+ sendSig: 'LIVESIG1111111111111111111111111111111111111',
+ confirmErr: null,
+ sent: 0,
+ simulate: { value: { err: null, logs: ['Program log: ok'], unitsConsumed: 250 } },
+};
+const fakeConn = {
+ getBalance: vi.fn(async () => connState.balance),
+ getMinimumBalanceForRentExemption: vi.fn(async () => connState.rentExempt),
+ getLatestBlockhash: vi.fn(async () => ({ blockhash: connState.blockhash, lastValidBlockHeight: 1000 })),
+ simulateTransaction: vi.fn(async () => connState.simulate),
+ sendRawTransaction: vi.fn(async () => { connState.sent += 1; return connState.sendSig; }),
+ confirmTransaction: vi.fn(async () => ({ value: { err: connState.confirmErr } })),
+ getSignatureStatus: vi.fn(async () => ({ value: { err: null, confirmationStatus: 'confirmed' } })),
+ getAccountInfo: vi.fn(async () => null),
+ getTokenAccountBalance: vi.fn(async () => ({ value: { amount: '0', uiAmount: 0, decimals: 6 } })),
+ getParsedTokenAccountsByOwner: vi.fn(async () => ({ value: [] })),
+};
+vi.mock('../api/_lib/agent-pumpfun.js', () => ({
+ solanaConnection: vi.fn(() => fakeConn),
+ solanaPublicConnection: vi.fn(() => fakeConn),
+}));
+
+// ── agent key recovery (returns a REAL keypair so signing works) ──────────────
+const agentKp = Keypair.generate();
+const recoverState = { calls: 0 };
+vi.mock('../api/_lib/agent-wallet.js', () => ({
+ generateSolanaAgentWallet: vi.fn(),
+ recoverSolanaAgentKeypair: vi.fn(async () => { recoverState.calls += 1; return agentKp; }),
+}));
+
+// ── avatar-wallet (explorer + price) ──────────────────────────────────────────
+vi.mock('../api/_lib/avatar-wallet.js', () => ({
+ explorerTxUrl: vi.fn((sig, net) => `https://solscan.io/tx/${sig}${net === 'devnet' ? '?cluster=devnet' : ''}`),
+ solUsdPrice: vi.fn(async () => 200),
+}));
+
+// ── shared spend policy (controllable; real version unit-tested separately) ───
+class FakeSpendLimitError extends Error {
+ constructor(code, message, detail = {}) { super(message); this.name = 'SpendLimitError'; this.status = 403; this.code = code; this.detail = detail; }
+}
+const guardState = { addrOverride: null, enforceThrow: null };
+vi.mock('../api/_lib/agent-trade-guards.js', () => ({
+ SpendLimitError: FakeSpendLimitError,
+ validateSolanaAddress: vi.fn((addr) => {
+ if (guardState.addrOverride) return guardState.addrOverride;
+ try { const pk = new PublicKey(addr); return { valid: true, base58: pk.toBase58(), pubkey: pk, onCurve: true }; }
+ catch { return { valid: false, reason: 'not_pubkey' }; }
+ }),
+ enforceSpendLimit: vi.fn(async () => { if (guardState.enforceThrow) throw guardState.enforceThrow; return { ok: true }; }),
+ lamportsToUsd: vi.fn(async () => 100),
+ getSpendLimits: vi.fn(() => ({ daily_usd: null, per_tx_usd: null, withdraw_allowlist: [] })),
+ setSpendLimits: vi.fn(async () => ({ daily_usd: null, per_tx_usd: null, withdraw_allowlist: [] })),
+ listCustodyEvents: vi.fn(async () => []),
+ updateCustodyEvent: vi.fn(async () => {}),
+ getDailySpendUsd: vi.fn(async () => 0),
+}));
+
+const { handleWithdraw } = await import('../api/agents/solana-wallet.js');
+
+// ── request/response helpers ──────────────────────────────────────────────────
+function mockReq(body) {
+ const buf = Buffer.from(JSON.stringify(body || {}));
+ return {
+ method: 'POST',
+ url: '/api/agents/agent-1/solana/withdraw',
+ headers: { host: 'localhost', 'content-type': 'application/json' },
+ on(evt, cb) {
+ if (evt === 'data') queueMicrotask(() => cb(buf));
+ if (evt === 'end') queueMicrotask(() => cb());
+ },
+ destroy() {},
+ };
+}
+function mockRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, ended: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(b) { this.body = b; this.ended = true; },
+ };
+}
+function parse(res) { try { return JSON.parse(res.body); } catch { return null; } }
+
+const AGENT_META = { solana_address: agentKp.publicKey.toBase58(), encrypted_solana_secret: 'ENC' };
+function queueAgentRow() {
+ sqlState.queue.push([{ id: 'agent-1', user_id: 'user-1', meta: AGENT_META }]);
+}
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ connState.sent = 0;
+ connState.confirmErr = null;
+ recoverState.calls = 0;
+ guardState.addrOverride = null;
+ guardState.enforceThrow = null;
+ authState.session = { id: 'user-1' };
+});
+
+describe('handleWithdraw — validation + safety', () => {
+ it('rejects an invalid destination with 400 and never touches the key', async () => {
+ queueAgentRow();
+ guardState.addrOverride = { valid: false, reason: 'not_base58' };
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 0.1, destination: 'garbage' }), res, 'agent-1');
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_destination');
+ expect(recoverState.calls).toBe(0);
+ expect(connState.sent).toBe(0);
+ });
+
+ it('rejects an off-curve (PDA) destination with 400', async () => {
+ queueAgentRow();
+ const [pda] = PublicKey.findProgramAddressSync([Buffer.from('x')], PublicKey.default);
+ guardState.addrOverride = { valid: true, onCurve: false, base58: pda.toBase58(), pubkey: pda };
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 0.1, destination: pda.toBase58() }), res, 'agent-1');
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_destination');
+ expect(recoverState.calls).toBe(0);
+ });
+
+ it('returns 403 with the reason on a spend-limit breach, without sending', async () => {
+ queueAgentRow();
+ sqlState.queue.push([]); // idempotency lookup: none
+ guardState.enforceThrow = new FakeSpendLimitError('daily_exceeded', 'over the daily limit', { daily_usd: 5 });
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 0.1, destination: Keypair.generate().publicKey.toBase58() }), res, 'agent-1');
+ expect(res.statusCode).toBe(403);
+ const body = parse(res);
+ expect(body.error).toBe('daily_exceeded');
+ expect(body.detail.daily_usd).toBe(5);
+ expect(recoverState.calls).toBe(0);
+ expect(connState.sent).toBe(0);
+ });
+
+ it('forbids withdrawing from an agent the caller does not own', async () => {
+ sqlState.queue.push([{ id: 'agent-1', user_id: 'someone-else', meta: AGENT_META }]);
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 0.1, destination: Keypair.generate().publicKey.toBase58() }), res, 'agent-1');
+ expect(res.statusCode).toBe(403);
+ expect(parse(res).error).toBe('forbidden');
+ });
+});
+
+describe('handleWithdraw — idempotency', () => {
+ it('replays a confirmed withdrawal for the same idempotency key without re-sending', async () => {
+ queueAgentRow();
+ sqlState.queue.push([{ id: 9, status: 'confirmed', signature: 'OLDSIG' }]); // existing confirmed
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 0.1, destination: Keypair.generate().publicKey.toBase58(), idempotency_key: 'k-1' }), res, 'agent-1');
+ expect(res.statusCode).toBe(200);
+ const body = parse(res).data;
+ expect(body.replayed).toBe(true);
+ expect(body.signature).toBe('OLDSIG');
+ expect(connState.sent).toBe(0);
+ expect(recoverState.calls).toBe(0);
+ });
+
+ it('reports an in-flight withdrawal (pending row) as 409', async () => {
+ queueAgentRow();
+ sqlState.queue.push([{ id: 9, status: 'pending', signature: null }]);
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 0.1, destination: Keypair.generate().publicKey.toBase58(), idempotency_key: 'k-2' }), res, 'agent-1');
+ expect(res.statusCode).toBe(409);
+ expect(parse(res).error).toBe('withdrawal_in_progress');
+ expect(connState.sent).toBe(0);
+ });
+});
+
+describe('handleWithdraw — simulate', () => {
+ it('returns a simulation without signing or sending', async () => {
+ queueAgentRow();
+ sqlState.queue.push([]); // idempotency lookup: none
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 'max', destination: Keypair.generate().publicKey.toBase58(), simulate: true }), res, 'agent-1');
+ expect(res.statusCode).toBe(200);
+ const body = parse(res).data;
+ expect(body.simulated).toBe(true);
+ expect(body.err).toBeNull();
+ expect(recoverState.calls).toBe(0);
+ expect(connState.sent).toBe(0);
+ });
+});
+
+describe('handleWithdraw — live SOL max sweep', () => {
+ it('reserves rent + fees, signs, sends, confirms, and returns the signature', async () => {
+ queueAgentRow();
+ sqlState.queue.push([]); // idempotency lookup: none
+ sqlState.queue.push([{ id: 77 }]); // claim INSERT … RETURNING id
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 'max', destination: Keypair.generate().publicKey.toBase58() }), res, 'agent-1');
+ expect(res.statusCode).toBe(200);
+ const body = parse(res).data;
+ expect(body.replayed).toBe(false);
+ expect(body.signature).toBe(connState.sendSig);
+ expect(body.asset).toBe('SOL');
+ // Max sweep leaves balance - rentExempt - feeReserve (15000) lamports.
+ const expectedLamports = BigInt(connState.balance) - BigInt(connState.rentExempt) - 15_000n;
+ expect(body.lamports).toBe(expectedLamports.toString());
+ expect(recoverState.calls).toBe(1);
+ expect(connState.sent).toBe(1);
+ });
+
+ it('does not double-send; one confirmed send produces one signature', async () => {
+ queueAgentRow();
+ sqlState.queue.push([]);
+ sqlState.queue.push([{ id: 78 }]);
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 0.5, destination: Keypair.generate().publicKey.toBase58() }), res, 'agent-1');
+ expect(res.statusCode).toBe(200);
+ expect(connState.sent).toBe(1);
+ });
+});
diff --git a/tests/api/irl-interactions-privacy.test.js b/tests/api/irl-interactions-privacy.test.js
new file mode 100644
index 000000000..67f2488c4
--- /dev/null
+++ b/tests/api/irl-interactions-privacy.test.js
@@ -0,0 +1,162 @@
+// IRL interactions privacy invariants (H1 — IRL-Hardening regression fence).
+//
+// /api/irl/interactions is the IRL feedback loop, and it touches money + location:
+// • a `pay` is the one caller-asserted type that names money, so it is recorded
+// ONLY with a real settlement signature + a $THREE/USDC mint;
+// • the stored lat/lng are the PIN's location (snapshotted server-side), never a
+// caller-supplied coordinate — a tap must not be able to assert "I was at X";
+// • the owner inbox (?mine=1) is null-guarded so an empty device token matches
+// nothing (a bare '' must not surface every legacy NULL-token row).
+// This file pins those three so a regression goes red. DB / auth / limiter /
+// notify / alerts mocked → fully offline.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+let pinRow = null;
+let viewDupeRow = null;
+let paySigDupeRow = null;
+let lastInsert = null; // bound values of the most recent INSERT
+let mineQueries = []; // bound values of every owner-feed (?mine=1) SELECT
+
+const sqlMock = vi.fn((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/FROM irl_pins[\s\S]*WHERE id =/i.test(q)) {
+ return Promise.resolve(pinRow ? [pinRow] : []);
+ }
+ if (/SELECT id FROM irl_interactions[\s\S]*type = 'view'/i.test(q)) {
+ return Promise.resolve(viewDupeRow ? [viewDupeRow] : []);
+ }
+ if (/type = 'pay' AND payload->>'signature'/i.test(q)) {
+ return Promise.resolve(paySigDupeRow ? [paySigDupeRow] : []);
+ }
+ if (/INSERT INTO irl_interactions/i.test(q)) {
+ lastInsert = { values };
+ return Promise.resolve([{ id: 'ix-new', type: values[2], created_at: '2026-06-17T00:00:00Z' }]);
+ }
+ // Owner feed (?mine=1): the JOINed SELECT and the unread aggregate. Capture the
+ // bound owner id + device token so the null-guard can be asserted.
+ if (/FROM irl_interactions ix[\s\S]*JOIN irl_pins p/i.test(q)) {
+ mineQueries.push(values);
+ return Promise.resolve([]);
+ }
+ return Promise.resolve([]); // DDL, view_count UPDATE, etc.
+});
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+let sessionUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => sessionUser) }));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { irlInteractIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+vi.mock('../../api/_lib/notify.js', () => ({ insertNotification: vi.fn() }));
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));
+
+const { default: handler } = await import('../../api/irl/interactions.js');
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const SOL_SIG = '5'.repeat(64);
+const PIN_ID = '33333333-3333-4333-8333-333333333333';
+
+function makeRes() {
+ return {
+ statusCode: 200, _h: {}, headersSent: false, writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+async function call(method, { query = {}, body } = {}) {
+ const res = makeRes();
+ await handler({ method, url: '/api/irl/interactions', headers: { host: 'x' }, query, body }, res);
+ let parsed = null; try { parsed = JSON.parse(res._body); } catch {}
+ return { res, body: parsed };
+}
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ sessionUser = null;
+ pinRow = null;
+ viewDupeRow = null;
+ paySigDupeRow = null;
+ lastInsert = null;
+ mineQueries = [];
+});
+
+describe('POST pay — rejected without a valid signature + an allowed mint', () => {
+ beforeEach(() => {
+ pinRow = { id: PIN_ID, agent_id: 'a1', lat: 40.7128, lng: -74.006, user_id: 'owner', device_token: null };
+ });
+
+ it('400s a pay with no settlement signature, and inserts nothing', async () => {
+ const { res, body } = await call('POST', {
+ body: { pinId: PIN_ID, type: 'pay', currencyMint: THREE_MINT, amount: 1 },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/signature/i);
+ expect(lastInsert).toBeNull();
+ });
+
+ it('400s a pay whose mint is neither $THREE nor USDC, and inserts nothing', async () => {
+ const { res, body } = await call('POST', {
+ body: { pinId: PIN_ID, type: 'pay', signature: SOL_SIG, currencyMint: 'SomeOtherMint1111111111111111111111111111111', amount: 1 },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/\$THREE or USDC/i);
+ expect(lastInsert).toBeNull();
+ });
+
+ it('accepts a pay with a valid signature + the $THREE mint', async () => {
+ const { res } = await call('POST', {
+ body: { pinId: PIN_ID, type: 'pay', signature: SOL_SIG, currencyMint: THREE_MINT, amount: 1 },
+ });
+ expect(res.statusCode).toBe(201);
+ expect(lastInsert).not.toBeNull();
+ });
+});
+
+describe('POST — the stored coordinate is the PIN’s, never the caller’s', () => {
+ it('snapshots lat/lng from the pin and ignores any caller-supplied position', async () => {
+ pinRow = { id: PIN_ID, agent_id: 'a1', lat: 51.5074, lng: -0.1278, user_id: 'owner', device_token: null };
+ await call('POST', {
+ // A malicious caller tries to assert they were somewhere else entirely.
+ body: { pinId: PIN_ID, type: 'tap', lat: 0, lng: 0, deviceToken: 'visitor-dev' },
+ });
+ expect(lastInsert).not.toBeNull();
+ // INSERT columns: (pin_id, agent_id, type, message, viewer_user_id,
+ // viewer_device, lat, lng, amount, currency_mint, payload, seen_at)
+ const v = lastInsert.values;
+ expect(v[6]).toBe(51.5074); // lat = pin's
+ expect(v[7]).toBe(-0.1278); // lng = pin's
+ // The caller's spoofed (0,0) was never persisted.
+ expect(v[6]).not.toBe(0);
+ expect(v[7]).not.toBe(0);
+ });
+});
+
+describe('GET ?mine=1 — owner feed is null-guarded against an empty device token', () => {
+ it('400s a caller with neither a session nor a device token; runs no feed query', async () => {
+ const { res } = await call('GET', { query: { mine: '1' } });
+ expect(res.statusCode).toBe(400);
+ expect(mineQueries.length).toBe(0);
+ });
+
+ it('passes a NULL (not "") device token when the caller’s token is empty', async () => {
+ // An empty-string token must collapse to NULL so the IS NOT NULL guard makes
+ // it match nothing — never every legacy NULL-token row.
+ const { res } = await call('GET', { query: { mine: '1', deviceToken: '' } });
+ // No usable identifier → 400, and the feed query never ran with a '' clause.
+ expect(res.statusCode).toBe(400);
+ expect(mineQueries.length).toBe(0);
+ });
+
+ it('a real device token is passed through, the NULL session id stays NULL', async () => {
+ await call('GET', { query: { mine: '1', deviceToken: 'real-device' } });
+ expect(mineQueries.length).toBeGreaterThan(0);
+ // Each captured query binds (ownerId, ownerDev) repeatedly; the owner id is
+ // NULL for an anonymous caller and the device token is the literal one given.
+ const flat = mineQueries.flat();
+ expect(flat).toContain('real-device');
+ expect(flat).toContain(null); // ownerId NULL, never '' (a guessable match)
+ expect(flat).not.toContain(''); // an empty string would widen the match
+ });
+});
diff --git a/tests/api/irl-privacy.test.js b/tests/api/irl-privacy.test.js
new file mode 100644
index 000000000..3d65c13ee
--- /dev/null
+++ b/tests/api/irl-privacy.test.js
@@ -0,0 +1,262 @@
+// IRL location-privacy invariants (H1 — IRL-Hardening regression fence).
+//
+// The founder's bar is "nobody's real-world location ever leaks." Those
+// guarantees live in api/irl/pins.js but were only partially pinned by tests —
+// so a future edit could silently re-leak a coordinate, an owner id, or a device
+// token and still ship green. This file is the contract: it drives the REAL
+// pins.js handler with a content-addressed SQL mock (the irl-pins-room.test.js
+// harness, reused verbatim) and asserts every outbound-feed invariant:
+//
+// 1. the public nearby feed NEVER returns user_id or device_token — only an
+// is_mine boolean leaves;
+// 2. every outbound coordinate (lat/lng/origin_lat/origin_lng) is coarsened to
+// ≤ PUBLIC_COORD_DP (5) decimals — false precision is stripped;
+// 3. the read requires a genuine fix (missing lat/lng → 400) and clamps the
+// radius to the 60 m ceiling so one read can't widen into a window scan;
+// 4. every owner-gated mutation (calibrate / outfit / field PATCH / DELETE)
+// rejects a non-owner (403/404) and mutates NOTHING.
+//
+// Fully offline: DB / auth / limiter / guardian / accessories all mocked.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// ── Content-addressed SQL mock ──────────────────────────────────────────────
+// The nearby SELECT returns one seeded row (with user_id + device_token SET, to
+// prove the projection strips them). Mutation SELECTs return a configurable pin
+// so the ownership gates can be exercised. UPDATE/DELETE are tracked so we can
+// assert a rejected mutation never reached a write.
+let nearbyRow = null; // the row the nearby SELECT yields
+let lookupPin = null; // the row a mutation's ownership SELECT yields
+const writes = []; // every UPDATE/DELETE SQL the handler attempted
+let updateResult = []; // what an UPDATE RETURNING yields (default: no row)
+let deleteResult = []; // what a DELETE RETURNING yields (default: no row)
+
+const sqlMock = vi.fn((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ // Density / per-owner count probes on the POST path.
+ if (/count\(\*\)::int/i.test(q)) return Promise.resolve([{ n: 0 }]);
+ // Nearby SELECT (room columns + a BETWEEN range) → the seeded row.
+ if (/rel_east_m/i.test(q) && /BETWEEN/i.test(q) && /SELECT/i.test(q)) {
+ return Promise.resolve(nearbyRow ? [nearbyRow] : []);
+ }
+ // Ownership-lookup SELECT inside calibrate / outfit (SELECT … FROM irl_pins WHERE id = …).
+ if (/^\s*SELECT/i.test(q) && /FROM irl_pins/i.test(q) && /WHERE id =/i.test(q)) {
+ return Promise.resolve(lookupPin ? [lookupPin] : []);
+ }
+ if (/UPDATE irl_pins/i.test(q)) {
+ writes.push(q.replace(/\s+/g, ' ').trim().slice(0, 40));
+ return Promise.resolve(updateResult);
+ }
+ if (/DELETE FROM irl_pins/i.test(q)) {
+ writes.push(q.replace(/\s+/g, ' ').trim().slice(0, 40));
+ return Promise.resolve(deleteResult);
+ }
+ return Promise.resolve([]); // DDL + anything else
+});
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+let sessionUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => sessionUser) }));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ irlPinIp: vi.fn(async () => ({ success: true })),
+ irlPinBurst: vi.fn(async () => ({ success: true })),
+ irlPinHourly: vi.fn(async () => ({ success: true })),
+ publicIp: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+vi.mock('../../api/_lib/granite-guardian.js', () => ({
+ guardianConfig: () => ({ configured: false }), assess: vi.fn(), decide: vi.fn(),
+}));
+
+let handler;
+
+function makeRes() {
+ return {
+ statusCode: 200, _h: {}, headersSent: false, writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+async function call(method, { url = '/api/irl/pins', query = {}, body } = {}) {
+ const res = makeRes();
+ await handler({ url, method, headers: { host: 'x' }, query, body }, res);
+ let parsed = null; try { parsed = JSON.parse(res._body); } catch {}
+ return { res, body: parsed };
+}
+const getNearby = (query) => call('GET', { query });
+
+// Count fractional digits of a number after rounding away float noise at 1e-9.
+function fractionalDigits(n) {
+ if (typeof n !== 'number' || !Number.isFinite(n)) return 0;
+ const s = String(Math.round(n * 1e9) / 1e9);
+ const dot = s.indexOf('.');
+ return dot < 0 ? 0 : s.length - dot - 1;
+}
+
+beforeEach(async () => {
+ sqlMock.mockClear();
+ sessionUser = null;
+ nearbyRow = null;
+ lookupPin = null;
+ writes.length = 0;
+ updateResult = [];
+ deleteResult = [];
+ vi.resetModules(); // drop any pins.js a prior file cached under its own db.js mock
+ ({ default: handler } = await import('../../api/irl/pins.js'));
+});
+
+const ORIGIN = { lat: 40.7128, lng: -74.006 };
+
+function seedNearby(over = {}) {
+ nearbyRow = {
+ id: 'pin-1', user_id: 'owner-uuid-secret', device_token: 'device-token-secret',
+ agent_id: 'agent-9', lat: ORIGIN.lat, lng: ORIGIN.lng, heading: 90,
+ avatar_url: '/a.glb', avatar_name: 'Scout', caption: 'hi', x402_endpoint: null,
+ placed_at: '2026-06-17T00:00:00Z', view_count: 3,
+ anchor_height_m: null, anchor_yaw_deg: 90, anchor_quat: null,
+ gps_accuracy_m: 10, altitude_m: null, anchor_source: 'gyro-gps', avatar_version: 0,
+ room_id: null, rel_east_m: null, rel_north_m: null,
+ origin_lat: null, origin_lng: null, origin_yaw_deg: null,
+ ...over,
+ };
+}
+
+describe('GET /api/irl/pins — the nearby feed never leaks an owner identifier', () => {
+ it('strips user_id and device_token; only is_mine leaves', async () => {
+ seedNearby();
+ const { res, body } = await getNearby({ lat: String(ORIGIN.lat), lng: String(ORIGIN.lng) });
+ expect(res.statusCode).toBe(200);
+ expect(body.pins.length).toBe(1);
+ for (const p of body.pins) {
+ expect(p).not.toHaveProperty('user_id');
+ expect(p).not.toHaveProperty('device_token');
+ expect(p).toHaveProperty('is_mine');
+ expect(typeof p.is_mine).toBe('boolean');
+ }
+ });
+
+ it('the leaked-row values themselves never appear anywhere in the serialized body', async () => {
+ seedNearby();
+ const { res } = await getNearby({ lat: String(ORIGIN.lat), lng: String(ORIGIN.lng) });
+ // The strongest form: the secret strings must not survive serialization at all.
+ expect(res._body).not.toContain('owner-uuid-secret');
+ expect(res._body).not.toContain('device-token-secret');
+ });
+
+ it('is_mine is true only when the caller proves ownership (session or device token)', async () => {
+ seedNearby({ user_id: 'me-uuid' });
+ sessionUser = { id: 'me-uuid' };
+ const mine = await getNearby({ lat: String(ORIGIN.lat), lng: String(ORIGIN.lng) });
+ expect(mine.body.pins[0].is_mine).toBe(true);
+
+ sessionUser = { id: 'someone-else' };
+ const notMine = await getNearby({ lat: String(ORIGIN.lat), lng: String(ORIGIN.lng) });
+ expect(notMine.body.pins[0].is_mine).toBe(false);
+ });
+});
+
+describe('GET /api/irl/pins — every outbound coordinate is coarsened to ≤ 5 decimals', () => {
+ it('rounds lat/lng/origin_lat/origin_lng below the false-precision threshold', async () => {
+ const preciseLat = 40.71280123456;
+ const preciseLng = -74.00609987654;
+ seedNearby({
+ lat: preciseLat, lng: preciseLng,
+ room_id: 'living-room-7', rel_east_m: 2, rel_north_m: 1,
+ origin_lat: preciseLat, origin_lng: preciseLng, origin_yaw_deg: 0,
+ });
+ const { body } = await getNearby({ lat: String(preciseLat), lng: String(preciseLng), radius: '60' });
+ const p = body.pins[0];
+ for (const key of ['lat', 'lng', 'origin_lat', 'origin_lng']) {
+ expect(fractionalDigits(p[key])).toBeLessThanOrEqual(5);
+ }
+ // The exact stored sub-mm values must NOT leave the server.
+ expect(p.lat).not.toBe(preciseLat);
+ expect(p.lng).not.toBe(preciseLng);
+ // The exact intra-room layout (relative metres) is untouched — only the GPS index is coarsened.
+ expect(p.rel_east_m).toBe(2);
+ expect(p.rel_north_m).toBe(1);
+ });
+});
+
+describe('GET /api/irl/pins — the read is bound to a real fix and a tight radius', () => {
+ it('400s a missing lat/lng (no couch-browsing without a position)', async () => {
+ const { res, body } = await getNearby({ radius: '40' });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/lat and lng/i);
+ });
+
+ it('clamps a huge requested radius to the 60 m ceiling (no window widening)', async () => {
+ seedNearby();
+ // A pin ~58 m north is within the 60 m cap but would be excluded by a 40 m
+ // default — so if it comes back, the radius was honored up to but not beyond 60.
+ const farLat = ORIGIN.lat + 58 / 110540; // ~58 m north
+ seedNearby({ lat: farLat, lng: ORIGIN.lng });
+ const { body } = await getNearby({ lat: String(ORIGIN.lat), lng: String(ORIGIN.lng), radius: '100000' });
+ // 58 m is inside the 60 m clamp, so it survives; the row is the only seeded one.
+ expect(body.pins.length).toBe(1);
+ expect(body.pins[0].distance_m).toBeLessThanOrEqual(60);
+ });
+});
+
+describe('PATCH calibrate / outfit — a non-owner is rejected and nothing is written', () => {
+ const PIN_ID = '11111111-1111-4111-8111-111111111111';
+
+ it('calibrate from a wrong device token → 403, no UPDATE', async () => {
+ lookupPin = {
+ id: PIN_ID, user_id: null, device_token: 'real-owner-device',
+ lat: ORIGIN.lat, lng: ORIGIN.lng, heading: 0,
+ anchor_yaw_deg: 0, anchor_height_m: 0, expires_at: null, hidden_at: null,
+ };
+ const { res } = await call('PATCH', {
+ body: { id: PIN_ID, deviceToken: 'attacker-device', calibrate: { lat: ORIGIN.lat, lng: ORIGIN.lng } },
+ });
+ expect(res.statusCode).toBe(403);
+ expect(writes.length).toBe(0); // never reached the UPDATE
+ });
+
+ it('outfit change from a non-owner session → 403, no bake/UPDATE', async () => {
+ lookupPin = {
+ id: PIN_ID, user_id: 'real-owner-uuid', avatar_url: '/a.glb',
+ avatar_base_url: '/a.glb', avatar_version: 0, expires_at: null, hidden_at: null,
+ };
+ sessionUser = { id: 'attacker-uuid' };
+ const { res } = await call('PATCH', {
+ body: { id: PIN_ID, avatar_manifest: { colors: {} } },
+ });
+ expect(res.statusCode).toBe(403);
+ expect(writes.length).toBe(0);
+ });
+});
+
+describe('PATCH field-edit / DELETE — a non-owner mutates nothing', () => {
+ const PIN_ID = '22222222-2222-4222-8222-222222222222';
+
+ it('a field PATCH from a different session updates no row (owner-scoped WHERE → 404)', async () => {
+ sessionUser = { id: 'attacker-uuid' };
+ updateResult = []; // the owner-scoped WHERE matches nothing for an attacker
+ const { res, body } = await call('PATCH', {
+ body: { id: PIN_ID, caption: 'defaced' },
+ });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toMatch(/not found/i);
+ });
+
+ it('a DELETE with neither a session nor a device token → 401, never deletes', async () => {
+ const { res } = await call('DELETE', { url: `/api/irl/pins?id=${PIN_ID}`, query: { id: PIN_ID } });
+ expect(res.statusCode).toBe(401);
+ expect(writes.length).toBe(0);
+ });
+
+ it('a DELETE with a wrong device token matches no row (owner-scoped WHERE → 404)', async () => {
+ deleteResult = []; // strict owner-scoped WHERE returns nothing for a stranger
+ const { res, body } = await call('DELETE', {
+ url: `/api/irl/pins?id=${PIN_ID}`,
+ query: { id: PIN_ID, deviceToken: 'attacker-device' },
+ });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toMatch(/not found|not yours/i);
+ });
+});
diff --git a/vite.config.js b/vite.config.js
index 39e119065..0b2b9be42 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -384,6 +384,7 @@ const appConfig = {
xr: resolve(__dirname, 'pages/xr.html'),
walk: resolve(__dirname, 'pages/walk.html'),
irl: resolve(__dirname, 'pages/irl.html'),
+ 'irl-privacy': resolve(__dirname, 'pages/irl-privacy.html'),
communities: resolve(__dirname, 'pages/communities.html'),
'walk-embed': resolve(__dirname, 'pages/walk-embed.html'),
city: resolve(__dirname, 'pages/city.html'),
@@ -734,6 +735,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/walk/': resolve(root, 'pages/walk.html'),
'/irl': resolve(root, 'pages/irl.html'),
'/irl/': resolve(root, 'pages/irl.html'),
+ '/irl-privacy': resolve(root, 'pages/irl-privacy.html'),
+ '/irl-privacy/': resolve(root, 'pages/irl-privacy.html'),
'/play': resolve(root, 'pages/play.html'),
'/play/': resolve(root, 'pages/play.html'),
'/play/agent-wallet': resolve(root, 'pages/play/agent-wallet.html'),