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.

Pending changes exported from your codespace

oversteppinga6b875664a83
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc4c368b5..15c26f9da 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-17
+- **How location works on IRL** (`/irl-privacy`) — Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.
- **x402 Live Demo (IBM × three.ws)** (`/ibm/x402-demo`) — A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.
- **Agent profiles now show the agent's real avatar — no more stray model over the name** — On an agent's profile page, agents that ship their own 3D avatar were briefly showing the plain mannequin in the headshot while a second copy of their real avatar rendered loose over the agent's name. Both are fixed: the headshot now loads the agent's own model directly in place, and opening it full-screen shows that same model. Agents using the default body are unchanged. `[fix]`
- **Agents placed from an iPhone now land in the right real-world spot for everyone** — iPhone Safari can't use WebXR, so placing an agent in the real world relies on the phone's motion sensors and GPS. Until now it leaned on a relative gyro reading with no fixed sense of north, which meant an agent you pinned could show up rotated — or facing the wrong way — for other people standing at the same spot. IRL now reads the iPhone's true compass heading when you pin, so your agent is anchored to a real-world direction: pan your phone and it stays planted on its actual bearing instead of sliding with the camera, and walk toward it and it holds its place and grows as you approach. Everyone nearby sees it in the same orientation you intended. If your compass needs calibrating we still place the agent and tell you it may look rotated to others, rather than failing silently — and Android, which already had richer world-anchoring, is unchanged. (`/irl`) `[improvement, fix]`
@@ -16,6 +17,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Connect your Solana wallet right from the marketplace** — The marketplace now carries a persistent Connect Wallet control — in the sidebar on desktop, in the search bar on mobile — so you can link Phantom, Solflare, or Backpack once and arrive at any purchase already connected, instead of waiting until checkout. If you have more than one wallet installed you get a quick picker; if you have none, it points you to install one. Once connected it shows your address as a tidy pill with a menu to copy it, view the account on Solscan, or disconnect, and it quietly reconnects a previously approved wallet when you return — no extra pop-up. Connect from the header and the Buy dialog is ready to go; connect at checkout and the header updates too. It rides the same on-chain USDC purchase flow already in place, so there's nothing new to trust. (`/marketplace`) `[feature]`
- **Drop in <agent-3d> and you get just the avatar — chat is now opt-in** — The one-line embed is cleaner by default. A plain <agent-3d> tag now ships only the 3D avatar on a transparent background — no chat box, no input bar, no debug color picker, no name-plate. That makes it perfect for dropping a living avatar onto a landing page, hero section, or card without any extra UI to hide. When you want the full talking agent, add the new chat attribute: <agent-3d chat body="...">. Published agents you embed by agent-id, manifest, or an agent:// link still chat automatically — they carry their own brain and persona — so existing agent embeds are unchanged. The reference docs and examples were updated to match. (`/docs/web-component`) `[feature, sdk]`
- **Embedded avatars: polished loading, seamless looping, and smarter framing** — The live 3D avatars dotted around the site — the ones in the home-page feature cards and anywhere an <agent-3d> embed appears — now feel intentional from the first frame. Each one fades in behind a soft skeleton placeholder while its model streams, instead of popping in cold. Animations no longer hard-snap: a one-shot gesture like a wave plays once and settles smoothly back into an idle stance rather than jumping at the loop boundary. A new framing option crops the avatar to head-to-mid-thigh so it fills its card instead of standing tiny and low. If a body ever fails to load, you get a tasteful silhouette rather than a blank or broken box. Avatars pause themselves when scrolled off-screen to save battery, and anyone who's asked their device to reduce motion gets a calm, held pose instead of looping animation. (`/embed`) `[improvement]`
+- **Every agent now has a dedicated wallet hub** — Each 3D agent's self-custodied Solana wallet now has one home: a tabbed Agent Wallet hub — Balance, Deposit, Trade, Snipe, Pay, and Withdraw — reachable from the agent's profile and right after you create one. The Balance tab is live now, showing the real on-chain SOL balance with a USD estimate and recent activity, refreshing on its own and degrading gracefully if the network is briefly unreachable. Behind the scenes every agent is guaranteed a wallet: older agents that predated automatic wallets are backfilled, and the agent API now reports whether each agent's wallet is ready. The remaining tabs are wired up across the next releases. `[feature]`
- **Everyone at a location now sees your IRL agent in the same real spot** — three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry. (`/irl`) `[feature, improvement]`
- **iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk** — iPhone Safari has no AR mode, so a placed agent used to drift with the camera. On three.ws/irl it now stays anchored to its real-world spot using the compass and GPS: pan your phone and the agent holds its real bearing instead of following the view, and walk toward it and it grows and keeps its place. Tapping Pin here saves the full placement — facing, ground height, and how good your GPS fix was — so iPhone placements match the AR-anchored version other phones see. If you pin before your location is ready, it waits for the first fix and pins precisely instead of dropping at a default spot. Permission states are designed and recoverable too: if motion or location access is off you get a clear card with the exact iOS Settings path and a Try again button, and if your phone can't read an absolute compass heading you're warned that others may see the agent rotated. (`/irl`) `[improvement]`
- **IRL agents now materialize as you walk up to them** — On three.ws/irl, a 3D agent placed further away first appears as a glowing beacon to keep things light. Previously it stayed a beacon even after you walked right up to it; now it upgrades to the full 3D avatar the moment you come within range, so approaching an agent in real life actually reveals it. Distance to each nearby agent is also recalculated live as you move instead of being frozen at the moment you arrived. Long AR sessions are smoother too: agents that leave the area now fully release their 3D model from memory instead of quietly accumulating, which keeps the camera view fast when you're somewhere busy with lots of agents coming and going. (`/irl`) `[fix, improvement]`
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 5b8011580..0ed281177 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -465,11 +465,11 @@ async function handleWallet(req, res, id) {
// Returns { error } (already-shaped) on any failure so callers can early-return.
async function loadOwnedWallet(req, res, id) {
const auth = await resolveAuth(req);
- if (!auth) return { error: error(res, 401, 'unauthorized', 'sign in required') };
+ if (!auth) { error(res, 401, 'unauthorized', 'sign in required'); return { error: true }; }
const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
- if (!row) return { error: error(res, 404, 'not_found', 'agent not found') };
- if (row.user_id !== auth.userId) return { error: error(res, 403, 'forbidden', 'not your agent') };
+ if (!row) { error(res, 404, 'not_found', 'agent not found'); return { error: true }; }
+ if (row.user_id !== auth.userId) { error(res, 403, 'forbidden', 'not your agent'); return { error: true }; }
const meta = { ...(row.meta || {}) };
return { auth, meta, address: meta.solana_address || null, encryptedSecret: meta.encrypted_solana_secret || null };
diff --git a/api/irl/interactions.js b/api/irl/interactions.js
index 12aaf0fc4..834acc463 100644
--- a/api/irl/interactions.js
+++ b/api/irl/interactions.js
@@ -91,6 +91,8 @@ function explorerTxUrl(sig, network) {
}
// Bound an untrusted payload object so a caller can't store an arbitrarily large
// blob in the JSONB column. Non-objects and oversized payloads collapse to {}.
+// A circular / unserializable blob throws inside JSON.stringify and collapses to
+// {} too — the first line of defense against a 500 on the INSERT below.
function clampPayload(obj) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return {};
try {
@@ -100,6 +102,25 @@ function clampPayload(obj) {
}
}
+// Serialize the payload destined for the JSONB column, treating any failure as a
+// caller fault (400) rather than letting it bubble into an uncaught 500. The base
+// object has already survived clampPayload's serialize check, but it is mutated
+// afterward (from/replyTo/signature/network) and `pay` spreads in caller-derived
+// values — so a BigInt amount, a circular self-reference, or a toJSON() that
+// throws would otherwise reach this point and crash the request. Returning the
+// JSON text (or null on failure) keeps the failure at the boundary, with context.
+function serializePayload(payload) {
+ try {
+ return JSON.stringify(payload);
+ } catch (err) {
+ console.warn('[irl/interactions] payload not serializable, rejecting', {
+ endpoint: 'POST /api/irl/interactions',
+ reason: err?.message || String(err),
+ });
+ return null;
+ }
+}
+
let _tableReady = false;
async function ensureTable() {
if (_tableReady) return;
@@ -237,6 +258,12 @@ export default wrap(async (req, res) => {
// An owner reply is authored by the owner, so it lands already-seen — it must
// never light up the owner's own unread badge. Every other row is unread.
const seenAt = isOwnerReply ? new Date().toISOString() : null;
+ // Serialize at the boundary so an unserializable payload is a clean 400, never
+ // an uncaught 500 inside the INSERT's `::jsonb` cast.
+ const payloadJson = serializePayload(payload);
+ if (payloadJson === null) {
+ return json(res, 400, { error: 'payload is not serializable' });
+ }
const [row] = await sql`
INSERT INTO irl_interactions
(pin_id, agent_id, type, message, viewer_user_id, viewer_device, lat, lng,
@@ -252,7 +279,7 @@ export default wrap(async (req, res) => {
${pin.lng},
${amount},
${currencyMint},
- ${JSON.stringify(payload)}::jsonb,
+ ${payloadJson}::jsonb,
${seenAt}
)
RETURNING id, type, created_at
@@ -261,7 +288,16 @@ export default wrap(async (req, res) => {
// (or any non-view) must not inflate it (the owner already sees those as feed
// rows). Owner-self views and same-device repeats already returned above.
if (type === 'view') {
- sql`UPDATE irl_pins SET view_count = view_count + 1 WHERE id = ${pinId}`.catch(() => {});
+ // Best-effort: the row is already written, so a failed counter bump must not
+ // fail the request — but it must not vanish either. Log it with context so a
+ // systematically-stuck "Visitors" metric is diagnosable from the ops logs.
+ sql`UPDATE irl_pins SET view_count = view_count + 1 WHERE id = ${pinId}`.catch((err) => {
+ console.warn('[irl/interactions] view_count increment failed', {
+ endpoint: 'POST /api/irl/interactions',
+ pinId,
+ reason: err?.message || String(err),
+ });
+ });
}
// Fan-out. Both arms are fire-and-forget and no-op when there's no one to
// reach (anonymous actor) or creds are absent.
diff --git a/api/irl/pins.js b/api/irl/pins.js
index eba78b4c9..3e8d0579a 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -522,17 +522,25 @@ async function handleCalibrate(res, { id, session, body }) {
// Persist. heading stays in sync with anchor_yaw_deg so legacy clients (which
// only read `heading`) still render the corrected bearing.
const headingToStore = newYaw != null ? Math.round(newYaw) : null;
+ // A manual yaw recalibration SUPERSEDES the captured surface orientation. The
+ // render-back path (pinYawRad, irl-floor-anchor task 02) prefers anchor_quat over
+ // anchor_yaw_deg for exact facing, so a stale quat would silently override the
+ // owner's nudge — the correction would never show. Clear anchor_quat whenever the
+ // owner sets a new yaw, retiring the now-wrong capture so anchor_yaw_deg is the
+ // authoritative source again. A height-only / move-only calibrate keeps the quat.
+ const clearQuat = newYaw != null;
const [row] = await sql`
UPDATE irl_pins SET
lat = ${newLat},
lng = ${newLng},
anchor_yaw_deg = COALESCE(${newYaw}, anchor_yaw_deg),
heading = COALESCE(${headingToStore}, heading),
- anchor_height_m = COALESCE(${newHeight}, anchor_height_m)
+ anchor_height_m = COALESCE(${newHeight}, anchor_height_m),
+ anchor_quat = CASE WHEN ${clearQuat} THEN NULL ELSE anchor_quat END
WHERE id = ${id}
AND hidden_at IS NULL
AND (expires_at IS NULL OR expires_at > NOW())
- RETURNING id, lat, lng, heading, anchor_yaw_deg, anchor_height_m, gps_accuracy_m
+ RETURNING id, lat, lng, heading, anchor_yaw_deg, anchor_height_m, anchor_quat, gps_accuracy_m
`;
// A lapse between the SELECT above and this write (e.g. expiry / a reaping cron)
// leaves no row — surface that as not-found instead of returning { pin: null }.
diff --git a/data/changelog.json b/data/changelog.json
index 9d525577c..467e23aa7 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,18 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-17",
+ "title": "Withdraw your agent's funds any time — plus spend limits and a full custody audit trail",
+ "summary": "Your agent's Solana wallet is custodial, so we've made getting funds out and keeping them safe first-class. The Agent Wallet hub now has a working Withdraw tab: sweep all your SOL or any token the wallet holds to any address or .sol name (paste or scan a QR), with a clear review step, a confirmed explorer link, and every state designed. A small amount of SOL is always kept back on a \"Max\" sweep so the wallet can never get stuck. Withdrawals are signed on the server and are safe to retry — the same request never sends twice. A new Limits & Safety section lets you set a daily spend cap, a per-transaction cap, and an allowlist of addresses funds may be withdrawn to; those limits apply to everything the agent does — trades, snipes, and payments — not just withdrawals. And an Activity log shows exactly what your custodial wallet has done: every withdrawal, automated spend, limit change, and each time the key was used to sign, with the reason. The wallet's secret key never leaves our servers, is never shown or logged, and is only ever used after we confirm you own the agent.",
+ "tags": ["feature", "security"]
+ },
+ {
+ "date": "2026-06-17",
+ "title": "Every agent now has a dedicated wallet hub",
+ "summary": "Each 3D agent's self-custodied Solana wallet now has one home: a tabbed Agent Wallet hub — Balance, Deposit, Trade, Snipe, Pay, and Withdraw — reachable from the agent's profile and right after you create one. The Balance tab is live now, showing the real on-chain SOL balance with a USD estimate and recent activity, refreshing on its own and degrading gracefully if the network is briefly unreachable. Behind the scenes every agent is guaranteed a wallet: older agents that predated automatic wallets are backfilled, and the agent API now reports whether each agent's wallet is ready. The remaining tabs are wired up across the next releases.",
+ "tags": ["feature"]
+ },
{
"date": "2026-06-17",
"title": "Sniper now auto-sells coins that graduate off the bonding curve",
diff --git a/data/pages.json b/data/pages.json
index 2aba8a734..fccf3581d 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -54,6 +54,14 @@
"changefreq": "monthly",
"added": "2026-06-13"
},
+ {
+ "path": "/irl-privacy",
+ "title": "How location works on IRL",
+ "description": "Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.",
+ "priority": 0.4,
+ "changefreq": "yearly",
+ "added": "2026-06-17"
+ },
{
"path": "/marketplace",
"title": "Marketplace",
diff --git a/docs/irl/THREAT-MODEL.md b/docs/irl/THREAT-MODEL.md
new file mode 100644
index 000000000..e76a3b799
--- /dev/null
+++ b/docs/irl/THREAT-MODEL.md
@@ -0,0 +1,68 @@
+# IRL nearby-read — threat model (H7)
+
+The `/irl` world lets anyone place a 3D agent at a real GPS spot and lets a passer-by
+discover it in AR. The single most sensitive thing the platform does here is reveal
+**where an agent is**. This document states, honestly, what the public nearby read
+protects against, how it degrades, and the residual exposure we accept by design.
+
+The one read in scope: `GET /api/irl/pins?lat&lng&radius` — the per-viewer proximity
+feed. It is the **only** surface that ever returns another user's agent location.
+(`/api/irl/pins/mine`, `agent-card`, `agent-summary`, `interactions*`, `report`,
+`share-frame` do not — see `reports/irl-location-leak-audit.md`.)
+
+## What the read protects against
+
+| Threat | Control | Where |
+|---|---|---|
+| **Remote browsing** ("show me agents in Tokyo from my couch") | The caller must send their **own** `lat`/`lng`; results are filtered to `distance_m <= radius`. There is no bbox/window/roster feed and no realtime pin broadcast. | `api/irl/pins.js` nearby branch; `multiplayer/src/rooms/IrlRoom.js` (syncs no pins) |
+| **Wide-radius scrape** | `radius` is clamped to `[10, 60]` m server-side; a present-but-non-finite radius is rejected (no NaN box). | `api/irl/pins.js` `Math.min(60, Math.max(10, …))` |
+| **Bulk grid harvest** | Per-IP rate limit on every read; **fail-closed** if the limiter can't decide (deny, never an unmetered window). Distinct-cell **sweep detection** fires a deduped, coordinate-free ops alert when one caller reads many geocells in a short window. | `limitFailClosedRead`, `recordCellRead` in `api/irl/pins.js`; `limits.publicIp` in `api/_lib/rate-limit.js` |
+| **De-anonymization** (who placed this agent?) | The public projection is an explicit allow-list: `user_id` / `device_token` are never returned; only an `is_mine` boolean computed server-side. | `api/irl/pins.js` nearby projection |
+| **Coordinate fingerprinting** | Returned coordinates are coarsened to 5 decimals (~1.1 m, finer than GPS error but stripped of the false-precision tail). The room origin is coarsened too; exact intra-room layout rides relative offsets, not absolute coords. | `roundCoord`, `PUBLIC_COORD_DP` in `api/irl/pins.js` |
+| **Credential / position leak via logs** | `req.url` (which carries `lat`/`lng`/`deviceToken`) is redacted before any log/Sentry/Telegram sink. The sweep alert carries only a SHA-256 IP hash + a count — never a coordinate, IP, or geocell. | `redactUrl` in `api/_lib/http.js`; `recordCellRead` alert payload |
+| **Stale / abusive pins surfacing** | `hidden_at IS NULL` (community-moderation hide at 3 distinct reporters) and `expires_at` (anon pins 7-day) filter every read path. | `api/irl/pins.js`, `api/irl/report.js` |
+
+## Degradation behaviour (no silent fail-open)
+
+- **Limiter degraded / throws on the read** → **fail closed**: the read returns a
+ retryable `rate_limiter_unavailable` (HTTP 429), surfaced to the client as
+ "temporarily unavailable, retrying." It never serves an unmetered read. The
+ backing bucket (`limits.publicIp`) is an in-memory `local` limiter that never
+ touches Redis, so it does not throw in practice; `limitFailClosedRead` makes the
+ guarantee explicit and asserted (`tests/api/irl-pins-hardening.test.js`).
+- **Write limiter degraded** (place/edit/delete) → **fail open**: the DB density,
+ per-owner, and report-dedup caps still bound writes, so an infra hiccup never
+ blocks a legitimate placement. This asymmetry is deliberate: a blind limiter on a
+ *write* is bounded downstream; a blind limiter on the *location read* is not.
+- **Sweep detection / ops alert** is best-effort: it is fire-and-forget, wrapped so
+ it can never delay or fail the read, and degrades to "no alert" if the cache or
+ Telegram is unavailable. It never widens or narrows what the read returns.
+
+## Accepted residual exposure (by design — this is the product)
+
+- **A person physically standing at a spot can see the handful of pins right where
+ they stand.** That is the entire feature: you discover an agent in AR by being
+ next to it. Within the ≤60 m radius, a co-located caller learns those pins'
+ coarsened coordinates. We do not consider this a leak — it is the product working.
+- **A determined attacker who physically walks a grid** can, cell by cell, see each
+ cell's pins as they enter it (a real fix per cell, slowly, tripping neither the
+ per-minute limit at low rate nor — if patient enough — necessarily the sweep
+ threshold). The sweep detector raises the cost and surfaces the pattern to ops, but
+ physical presence is, by definition, allowed to see what is physically present.
+ We accept this; the data exposed is still coarsened, owner-stripped, and bounded to
+ cells the attacker actually visited.
+- **Coordinate precision is ~1.1 m, not exact.** This is a deliberate coverage cap:
+ the public read intentionally returns less precision than the placement stored.
+ Room-anchored agents keep exact intra-room layout via relative offsets, so the cap
+ costs render quality nothing while removing the false-precision fingerprint.
+
+## Out of scope here
+
+- Proof-of-presence (H3) — a cell-bound fix token would further bind a read to a
+ real, recent fix in that cell, denying a token-per-cell sweep. If/when it lands,
+ the cross-cell denial assertion belongs in `tests/api/irl-pins-hardening.test.js`.
+- Per-account reputation / banning of repeat sweepers (future).
+
+No limit in this document silently reduces coverage: every cap above is written down.
+If a future change tightens the radius, the rate limit, or the coordinate precision
+in a way that drops legitimate discovery, update this file in the same change.
diff --git a/public/changelog.json b/public/changelog.json
index 2fcc82d8d..05048683d 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-17T12:49:06.978Z",
+ "generated_at": "2026-06-17T12:53:57.807Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-17",
+ "type": "launch",
+ "title": "How location works on IRL",
+ "summary": "Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.",
+ "link": "/irl-privacy",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-17",
"type": "launch",
@@ -108,6 +118,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "Every agent now has a dedicated wallet hub",
+ "summary": "Each 3D agent's self-custodied Solana wallet now has one home: a tabbed Agent Wallet hub — Balance, Deposit, Trade, Snipe, Pay, and Withdraw — reachable from the agent's profile and right after you create one. The Balance tab is live now, showing the real on-chain SOL balance with a USD estimate and recent activity, refreshing on its own and degrading gracefully if the network is briefly unreachable. Behind the scenes every agent is guaranteed a wallet: older agents that predated automatic wallets are backfilled, and the agent API now reports whether each agent's wallet is ready. The remaining tabs are wired up across the next releases.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index d0deccd31..3b50b5fde 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>How location works on IRL</title>
+ <link>https://three.ws/irl-privacy</link>
+ <guid isPermaLink="false">2026-06-17:How location works on IRL</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.</description>
+ </item>
<item>
<title>x402 Live Demo (IBM × three.ws)</title>
<link>https://three.ws/ibm/x402-demo</link>
@@ -86,6 +94,14 @@
<category>improvement</category>
<description>The live 3D avatars dotted around the site — the ones in the home-page feature cards and anywhere an &lt;agent-3d&gt; embed appears — now feel intentional from the first frame. Each one fades in behind a soft skeleton placeholder while its model streams, instead of popping in cold. Animations no longer hard-snap: a one-shot gesture like a wave plays once and settles smoothly back into an idle stance rather than jumping at the loop boundary. A new framing option crops the avatar to head-to-mid-thigh so it fills its card instead of standing tiny and low. If a body ever fails to load, you get a tasteful silhouette rather than a blank or broken box. Avatars pause themselves when scrolled off-screen to save battery, and anyone who's asked their device to reduce motion gets a calm, held pose instead of looping animation.</description>
</item>
+ <item>
+ <title>Every agent now has a dedicated wallet hub</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-17:Every agent now has a dedicated wallet hub</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Each 3D agent's self-custodied Solana wallet now has one home: a tabbed Agent Wallet hub — Balance, Deposit, Trade, Snipe, Pay, and Withdraw — reachable from the agent's profile and right after you create one. The Balance tab is live now, showing the real on-chain SOL balance with a USD estimate and recent activity, refreshing on its own and degrading gracefully if the network is briefly unreachable. Behind the scenes every agent is guaranteed a wallet: older agents that predated automatic wallets are backfilled, and the agent API now reports whether each agent's wallet is ready. The remaining tabs are wired up across the next releases.</description>
+ </item>
<item>
<title>Everyone at a location now sees your IRL agent in the same real spot</title>
<link>https://three.ws/irl</link>
diff --git a/public/features.json b/public/features.json
index f14f8a9fe..7b5d2b6d1 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T12:37:32.782Z",
+ "generated_at": "2026-06-17T12:53:57.342Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -65,6 +65,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/irl-privacy",
+ "title": "How location works on IRL",
+ "description": "Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.",
+ "added": "2026-06-17",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/marketplace",
"title": "Marketplace",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index becc9f543..296e185ba 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -43,6 +43,12 @@ URL: https://three.ws/irl
Place a 3D avatar in your real environment. Camera AR passthrough, joystick movement, and tap-to-place 3D objects on your floor.
+### How location works on IRL
+
+URL: https://three.ws/irl-privacy
+
+Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.
+
### Marketplace
URL: https://three.ws/marketplace
diff --git a/public/llms.txt b/public/llms.txt
index accd2f4c9..e750482a2 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -16,6 +16,7 @@ Entry points into the product.
- [Avatar Gallery](https://three.ws/gallery): Every public 3D avatar in the system, browsable as a grid.
- [Walk](https://three.ws/walk): Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.
- [IRL](https://three.ws/irl): Place a 3D avatar in your real environment. Camera AR passthrough, joystick movement, and tap-to-place 3D objects on your floor.
+- [How location works on IRL](https://three.ws/irl-privacy): Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.
- [Marketplace](https://three.ws/marketplace): Buy access to agents, skills, and avatars from other creators.
- [Skills Marketplace](https://three.ws/skills): Browse, search, and install agent skills — tool packs, knowledge bases, and capabilities that make AI agents smarter.
- [Community](https://three.ws/community): Featured creators, builds, and conversations from the three.ws community.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 316cb651c..cfb27fef8 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 276 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 277 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 276 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 277 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -96,7 +96,7 @@
</nav>
<section class="sm-section" id="main">
<header>
- <h2>Main<span class="sm-count" data-count>11</span></h2>
+ <h2>Main<span class="sm-count" data-count>12</span></h2>
<p class="sm-section-desc">Entry points into the product.</p>
</header>
<ul class="sm-list">
@@ -135,6 +135,13 @@
<span class="sm-desc">Place a 3D avatar in your real environment. Camera AR passthrough, joystick movement, and tap-to-place 3D objects on your floor.</span>
</a>
</li>
+ <li>
+ <a href="/irl-privacy">
+ <span class="sm-title">How location works on IRL</span>
+ <span class="sm-path">/irl-privacy</span>
+ <span class="sm-desc">Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.</span>
+ </a>
+ </li>
<li>
<a href="/marketplace">
<span class="sm-title">Marketplace</span>
diff --git a/scripts/verify-embed-avatar-ux.mjs b/scripts/verify-embed-avatar-ux.mjs
index 062cda15e..a04b76282 100644
--- a/scripts/verify-embed-avatar-ux.mjs
+++ b/scripts/verify-embed-avatar-ux.mjs
@@ -57,8 +57,6 @@ const assert = (cond, label, extra = '') => {
if (!cond) failures++;
};
-const browser = await chromium.launch();
-
async function inspect(page, id) {
return page.evaluate((id) => {
const el = document.getElementById(id);
@@ -80,6 +78,8 @@ async function inspect(page, id) {
}, id);
}
+const browser = await chromium.launch();
+try {
// ── 1. Normal motion context: framing, loading, error, loop-honoring ──────────
{
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
@@ -152,9 +152,12 @@ async function inspect(page, id) {
assert(loop?.currentActionNull === true, 'reduced-motion: avatar holds a static pose (no active looping action)', `currentActionNull=${loop?.currentActionNull}`);
await ctx.close();
}
-
-await browser.close();
-rmSync(TMP, { force: true });
+} finally {
+ // Always clean up the throwaway page + browser, even if an assertion threw,
+ // so a non-gitignored scratch file is never left behind in public/.
+ await browser.close().catch(() => {});
+ rmSync(TMP, { force: true });
+}
log(`\n${failures === 0 ? '✅ ALL CHECKS PASSED' : `❌ ${failures} CHECK(S) FAILED`}`);
process.exit(failures === 0 ? 0 : 1);
diff --git a/src/element.js b/src/element.js
index e83812098..fd491033b 100644
--- a/src/element.js
+++ b/src/element.js
@@ -556,6 +556,9 @@ const BASE_STYLE = `
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: none; }
}
+ @media (prefers-reduced-motion: reduce) {
+ .error-card { animation: none; }
+ }
.error-icon {
width: 36px;
height: 36px;
diff --git a/src/irl.js b/src/irl.js
index e7631b5e4..4388ffb67 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -54,7 +54,7 @@ import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';
import { detectTier, BUDGETS, TIER_ORDER, shiftTier } from './irl/perf-budget.js';
import { sharedGLTFLoader, createLoadQueue } from './irl/load-queue.js';
import { roomOriginWorld, agentWorldPosition } from './irl/room-anchor.js';
-import { anchorPoseToPin } from './irl/floor-anchor.js';
+import { anchorPoseToPin, yawDegFromQuat } from './irl/floor-anchor.js';
import { initRoomMode } from './irl/room-mode.js';
import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw, clampPitch } from './irl/sensor-fusion.js';
import { pinBandAction } from './irl/proximity-band.js';
@@ -1204,8 +1204,31 @@ function gpsToWorld(agentLat, agentLng) {
// geodetic (lat/lng) frame, the agent lands in the same bearing and floor spot
// for everyone. anchor_yaw_deg / anchor_height_m fall back to the legacy
// `heading` / ground plane when a pin predates the A2 pose columns.
+//
+// Yaw source priority (irl-floor-anchor task 02): when a WebXR placement stored
+// the full tap-moment surface quaternion (anchor_quat = [x,y,z,w], float), derive
+// yaw from it for exact facing — anchor_yaw_deg is that same angle rounded to a
+// whole degree by the persist path, so a 47.6° placement reloads as 47.6° instead
+// of snapping to 48°. Gyro/legacy pins carry no quat, so they keep falling back to
+// the rounded anchor_yaw_deg, then to the legacy `heading` — fallback intact.
+//
+// Pitch/roll from the quat are DELIBERATELY DROPPED here: a standing humanoid is
+// kept upright (yaw-only). Tilting an avatar to match a sloped surface looks broken,
+// not realistic; true surface tilt is reserved for a future non-humanoid prop mode
+// behind an explicit flag (see task 02, "Out of scope"). So we read only the yaw
+// component of anchor_quat and apply it about world-Y via setFromAxisAngle(upY, …).
+function pinQuatYawDeg(pin) {
+ const q = pin.anchor_quat;
+ // Guard the JSONB shape the API returns ([x,y,z,w] of finite numbers); a
+ // malformed/partial value falls through to the rounded yaw rather than NaN.
+ if (!Array.isArray(q) || q.length !== 4) return null;
+ if (!q.every(n => Number.isFinite(n))) return null;
+ return yawDegFromQuat(q[0], q[1], q[2], q[3]);
+}
function pinYawRad(pin) {
- const deg = Number.isFinite(pin.anchor_yaw_deg) ? pin.anchor_yaw_deg
+ const quatYaw = pinQuatYawDeg(pin);
+ const deg = quatYaw != null ? quatYaw
+ : Number.isFinite(pin.anchor_yaw_deg) ? pin.anchor_yaw_deg
: (pin.heading != null ? pin.heading : 0);
return -(deg * Math.PI / 180);
}
@@ -5144,6 +5167,11 @@ 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;
+ // The manual yaw nudge supersedes the captured surface quaternion; drop it so
+ // pinYawRad (task 02) reads the corrected anchor_yaw_deg, matching the server
+ // (handleCalibrate clears anchor_quat on a yaw change). Without this the live
+ // pin would keep rendering the pre-nudge facing until the next re-fetch.
+ pin.anchor_quat = null;
setStatus('Position calibrated — saved here; nearby viewers update within ~10s');
exitCalibrate(false);
loadNearbyPins();
diff --git a/src/irl/onboarding.js b/src/irl/onboarding.js
index a6a500cc7..f11f32f97 100644
--- a/src/irl/onboarding.js
+++ b/src/irl/onboarding.js
@@ -240,6 +240,7 @@ function buildShell(opts) {
<span class="irl-ob-badge"><svg class="irl-ob-badge-mark" viewBox="0 0 26 28" fill="none" aria-hidden="true"><path class="irl-mark-cube" d="M13 2.5 4 7v9l9 4.5 9-4.5V7Z"/><path class="irl-mark-cube" d="M13 2.5v9M4 7l9 4.5M22 7l-9 4.5"/><path class="irl-mark-beam" d="M13 20.5v1.9"/><ellipse class="irl-mark-anchor" cx="13" cy="24.3" rx="7.4" ry="1.9"/><circle class="irl-mark-dot" cx="13" cy="24.3" r="1" stroke="none"/></svg> IRL</span>
<h2 class="irl-ob-title">${multi ? 'Bring your agents into the real world' : 'Permission needed'}</h2>
<p class="irl-ob-sub">${multi ? 'Three quick permissions power the camera, look-around, and real-world pins. You stay in control.' : 'Grant access to continue — you can change this anytime.'}</p>
+ <a class="irl-ob-learn" href="/irl-privacy" target="_blank" rel="noopener">How location works <span aria-hidden="true">↗</span></a>
</div>
<div class="irl-ob-card" aria-live="polite"></div>
<div class="irl-ob-progress"${multi ? '' : ' hidden'} aria-hidden="true"></div>
@@ -552,6 +553,15 @@ const ONBOARD_CSS = `
.irl-ob-badge-mark .irl-mark-dot { fill: currentColor; opacity: .8; }
.irl-ob-title { margin: 0 0 6px; font-size: 18px; font-weight: 700; letter-spacing: -.015em; color: #f1f4fa; line-height: 1.25; }
.irl-ob-sub { margin: 0; font-size: 13px; line-height: 1.5; color: #93a1b5; }
+.irl-ob-learn {
+ display: inline-flex; align-items: center; gap: 5px;
+ margin-top: 9px;
+ font: 500 12px/1 var(--font-body, system-ui, sans-serif);
+ color: #7dd3fc; text-decoration: none;
+ transition: color .15s;
+}
+.irl-ob-learn:hover { color: #a6dcee; }
+.irl-ob-learn:focus-visible { outline: 2px solid #7dd3fc; outline-offset: 3px; border-radius: 6px; }
.irl-ob-card .tws-es { padding: 22px 8px 6px; }
.irl-ob-card .tws-es-icon { color: #cdd6e4; opacity: .92; }
.irl-ob-card .tws-es-icon--err { color: #f87171; }
diff --git a/src/irl/privacy-center.js b/src/irl/privacy-center.js
index 2b1cdab98..5fdf13537 100644
--- a/src/irl/privacy-center.js
+++ b/src/irl/privacy-center.js
@@ -80,6 +80,11 @@ function ensureStyles() {
.irlpc-done{width:100%;appearance:none;background:#4f7cff;color:#fff;border:none;border-radius:11px;
font:600 14px system-ui,sans-serif;padding:13px;cursor:pointer;transition:background .15s}
.irlpc-done:hover{background:#3d6af0}
+.irlpc-learn{display:flex;align-items:center;justify-content:center;gap:6px;margin-top:11px;
+ font:500 12.5px/1 system-ui,sans-serif;color:#7ec8e3;text-decoration:none;transition:color .15s}
+.irlpc-learn:hover{color:#a6dcee}
+.irlpc-learn:focus-visible{outline:2px solid #4f7cff;outline-offset:3px;border-radius:6px}
+.irlpc-learn .ar{font-size:14px}
/* First-run disclosure reuses the sheet shell with a tighter body */
.irlpc-discl .irlpc-sec{border-top:none}
`;
@@ -166,7 +171,10 @@ export function openPrivacyCenter({ getGhost, setGhost, onManagePins } = {}) {
<span>Manage &amp; remove agents you’ve placed</span><span class="ar">→</span>
</button>
</div>
- <div class="irlpc-foot"><button class="irlpc-done" type="button" data-close>Done</button></div>`;
+ <div class="irlpc-foot">
+ <button class="irlpc-done" type="button" data-close>Done</button>
+ <a class="irlpc-learn" href="/irl-privacy" target="_blank" rel="noopener">How location works <span class="ar" aria-hidden="true">↗</span></a>
+ </div>`;
sheet.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', close));
@@ -216,7 +224,10 @@ export function maybeShowFirstRunDisclosure() {
<button class="irlpc-x" type="button" data-close aria-label="Close">×</button>
</div>
<div class="irlpc-sec">${factsHTML()}</div>
- <div class="irlpc-foot"><button class="irlpc-done" type="button" data-close>Got it</button></div>`;
+ <div class="irlpc-foot">
+ <button class="irlpc-done" type="button" data-close>Got it</button>
+ <a class="irlpc-learn" href="/irl-privacy" target="_blank" rel="noopener">Learn more <span class="ar" aria-hidden="true">↗</span></a>
+ </div>`;
sheet.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', close));
setTimeout(() => sheet.querySelector('.irlpc-done')?.focus(), 60);
}, { extraClass: 'irlpc-discl' });
diff --git a/tests/api/irl-interactions.test.js b/tests/api/irl-interactions.test.js
index 275028193..342f3eb7c 100644
--- a/tests/api/irl-interactions.test.js
+++ b/tests/api/irl-interactions.test.js
@@ -248,6 +248,65 @@ describe('POST — messages + owner replies', () => {
});
});
+describe('POST — payload serialization boundary (no uncaught 500)', () => {
+ it('400s a circular payload instead of crashing the INSERT', async () => {
+ // clampPayload collapses a circular blob to {} during its size check, so a
+ // circular `payload` alone can't reach the INSERT. The residual risk this
+ // guards is a value that survives clampPayload but later fails to serialize —
+ // exercised here by smuggling a circular reference past clampPayload via a
+ // toJSON() that returns a bounded object during the clamp but throws when the
+ // row is finally serialized.
+ let clampPass = true;
+ const hostile = {
+ toJSON() {
+ if (clampPass) { clampPass = false; return { ok: 1 }; }
+ throw new TypeError('Converting circular structure to JSON');
+ },
+ };
+ const { res, body } = await post({ pinId: 'pin-1', type: 'tap', payload: hostile, deviceToken: 'dev-A' });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/serializable/i);
+ expect(lastInsert).toBeNull(); // no row written when serialization fails
+ });
+
+ it('records a normal payload object as serialized JSONB', async () => {
+ const { res } = await post({ pinId: 'pin-1', type: 'tap', payload: { note: 'hi' }, deviceToken: 'dev-A' });
+ expect(res.statusCode).toBe(201);
+ // values[10] is the serialized payload text the INSERT binds to the ::jsonb cast.
+ expect(typeof lastInsert.values[10]).toBe('string');
+ expect(JSON.parse(lastInsert.values[10])).toMatchObject({ note: 'hi' });
+ });
+});
+
+describe('POST — view_count increment is logged, not swallowed', () => {
+ it('logs a failed counter bump with context but still 201s the view', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ // Reject only the view_count UPDATE; the pin lookup + INSERT still resolve.
+ sqlMock.mockImplementation((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/UPDATE irl_pins SET view_count/i.test(q)) return Promise.reject(new Error('db down'));
+ if (/FROM irl_pins[\s\S]*WHERE id =/i.test(q)) return Promise.resolve([pinRow]);
+ if (/SELECT id FROM irl_interactions[\s\S]*type = 'view'/i.test(q)) return Promise.resolve([]);
+ if (/INSERT INTO irl_interactions/i.test(q)) {
+ lastInsert = { values };
+ return Promise.resolve([{ id: 'ix-new', type: values[2], created_at: 'now' }]);
+ }
+ return Promise.resolve([]);
+ });
+ const { res } = await post({ pinId: 'pin-1', type: 'view', deviceToken: 'dev-fresh' });
+ expect(res.statusCode).toBe(201);
+ // The rejection is async fire-and-forget — let the microtask queue drain.
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(warn).toHaveBeenCalledWith(
+ '[irl/interactions] view_count increment failed',
+ expect.objectContaining({ pinId: 'pin-1', reason: 'db down' }),
+ );
+ warn.mockRestore();
+ sqlMock.mockClear();
+ });
+});
+
describe('GET ?mine=1 + PATCH', () => {
it('GET requires a session or deviceToken', async () => {
const { res } = await call('GET', { query: { mine: '1' } });
diff --git a/tests/api/irl-pins-calibrate.test.js b/tests/api/irl-pins-calibrate.test.js
index c4ef8b21e..3caa2bd5e 100644
--- a/tests/api/irl-pins-calibrate.test.js
+++ b/tests/api/irl-pins-calibrate.test.js
@@ -16,6 +16,12 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// shape regardless of call order. `pinRow` is the row the WHERE-id SELECT returns
// (null → "not found"); the UPDATE echoes back the bound values so success-path
// assertions see the persisted pose.
+//
+// The UPDATE binds, in order: lat, lng, anchor_yaw_deg, heading, anchor_height_m,
+// then a clearQuat boolean (anchor_quat CASE — task 02 retires the stored surface
+// quat when the owner manually re-yaws), then the WHERE id. The mock models that
+// CASE so a yaw nudge surfaces anchor_quat: null and a move/height-only nudge
+// leaves the stored quat untouched, exactly like the SQL.
let pinRow = null;
const sqlMock = vi.fn((strings, ...values) => {
const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
@@ -23,13 +29,14 @@ const sqlMock = vi.fn((strings, ...values) => {
return Promise.resolve(pinRow ? [pinRow] : []);
}
if (/UPDATE irl_pins SET/i.test(q)) {
- const [lat, lng, yaw, heading, height, id] = values;
+ const [lat, lng, yaw, heading, height, clearQuat, id] = values;
return Promise.resolve([{
id,
lat, lng,
heading: heading ?? pinRow?.heading ?? null,
anchor_yaw_deg: yaw ?? pinRow?.anchor_yaw_deg ?? null,
anchor_height_m: height ?? pinRow?.anchor_height_m ?? null,
+ anchor_quat: clearQuat ? null : (pinRow?.anchor_quat ?? null),
gps_accuracy_m: pinRow?.gps_accuracy_m ?? null,
}]);
}
@@ -88,6 +95,8 @@ beforeEach(() => {
heading: 90,
anchor_yaw_deg: 90,
anchor_height_m: 0,
+ // A WebXR placement that captured the full tap-moment surface orientation.
+ anchor_quat: [0, 0.7071, 0, 0.7071], // ≈ 90° about Y
gps_accuracy_m: 12,
};
sessionUser = null;
diff --git a/tests/api/irl-pins-hardening.test.js b/tests/api/irl-pins-hardening.test.js
index 7895f8b6a..006b32768 100644
--- a/tests/api/irl-pins-hardening.test.js
+++ b/tests/api/irl-pins-hardening.test.js
@@ -1,10 +1,11 @@
// /api/irl/pins — production hardening (tasks 11 / 12 / 13).
//
// These tests cover the backend-resilience + security-validation surface added to
-// api/irl/pins.js: radius + pin-id validation, the rate-limiter fail-open wrapper,
-// the Guardian degraded-state cache, the x402 allow-list parse, ownership + expiry
-// on calibrate/outfit/delete, and the no-internal-detail outfit-bake error. The
-// DB / auth / limiter / baker are mocked so the suite runs offline in Node.
+// api/irl/pins.js: radius + pin-id validation, the limiter degradation policy (the
+// public read fails CLOSED per H7; writes fail open), the Guardian degraded-state
+// cache, the x402 allow-list parse, ownership + expiry on calibrate/outfit/delete,
+// and the no-internal-detail outfit-bake error. The DB / auth / limiter / baker are
+// mocked so the suite runs offline in Node.
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -335,17 +336,25 @@ describe('DELETE /api/irl/pins?all=1 — bulk device purge', () => {
});
});
-// ── Rate-limiter fail-open (task 12) ─────────────────────────────────────────
-describe('rate limiter fail-open', () => {
- it('a throwing limiter does not 500 a GET — the request is allowed', async () => {
+// ── Rate-limiter degradation: read fails CLOSED, writes fail OPEN (task 12 + H7) ─
+describe('rate limiter degradation', () => {
+ it('a throwing limiter FAILS CLOSED on the public GET read — 429, never an unmetered scrape (H7)', async () => {
limiterThrows = true;
- const { res } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: '40' } });
- // Fail-open: the read proceeds to a normal 200, never a 500 from the limiter.
- expect(res.statusCode).toBe(200);
+ const { res, body } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: '40' } });
+ // The nearby read is the ONLY surface that reveals another agent's location, so a
+ // limiter it can't evaluate must DENY (retryable), never open an unmetered read.
+ expect(res.statusCode).toBe(429);
+ expect(body.reason).toBe('rate_limiter_unavailable');
+ // Denied before any location data left the DB — the pin SELECT never ran.
+ const ranSelect = sqlMock.mock.calls.some(([s]) =>
+ /lat BETWEEN/i.test(Array.isArray(s) ? s.join(' ') : String(s)));
+ expect(ranSelect).toBe(false);
});
- it('a throwing limiter does not 500 a DELETE — ownership is still enforced', async () => {
+ it('a throwing limiter does not 500 a DELETE — write fails open, ownership still enforced (task 12)', async () => {
limiterThrows = true;
const { res } = await del({ id: UUID, deviceToken: 'device-A' });
+ // Writes are bounded by the DB density/owner caps even when the limiter is blind,
+ // so an infra hiccup must never block a legitimate placement/removal.
expect(res.statusCode).toBe(200);
});
});
diff --git a/tests/api/irl-sweep-detection.test.js b/tests/api/irl-sweep-detection.test.js
new file mode 100644
index 000000000..3190cdcea
--- /dev/null
+++ b/tests/api/irl-sweep-detection.test.js
@@ -0,0 +1,94 @@
+// api/irl/pins.js — sweep anomaly detection (H7).
+//
+// The public nearby read is the only surface that reveals another agent's location.
+// A scraper can stay under the per-minute rate limit by reading slowly, but a sweep
+// is shaped differently from a real user: a real user polls ~1 geocell over and over
+// (they stand in one place), a harvester reads MANY distinct cells. recordCellRead()
+// tracks the distinct cells one caller reads in a short window and fires ONE deduped,
+// COORDINATE-FREE ops alert past the threshold. These tests pin that down:
+// - distinct cells accumulate per (hashed) IP; repeats don't double-count
+// - crossing the threshold fires exactly one alert (latched per window)
+// - the alert carries NO coordinate and NO raw IP — only a hash + a count
+// cache / alerts are mocked so the suite stays offline; db / auth / limiter are
+// stubbed only so importing pins.js doesn't reach real infra.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory cache stand-in so distinct-cell state persists across calls in a test.
+const store = new Map();
+vi.mock('../../api/_lib/cache.js', () => ({
+ cacheGet: vi.fn(async (k) => (store.has(k) ? store.get(k) : null)),
+ cacheSet: vi.fn(async (k, v) => { store.set(k, v); }),
+}));
+
+const alertSpy = vi.fn(async () => {});
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: (...a) => alertSpy(...a) }));
+
+// Minimal stubs so importing the handler module doesn't touch real infra.
+vi.mock('../../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => null) }));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { recordCellRead } = await import('../../api/irl/pins.js');
+
+const THRESHOLD = 12; // mirrors SWEEP_CELL_THRESHOLD in pins.js
+const cell = (i) => `u4pruyd${i}`.slice(0, 7) + i; // distinct geocell-shaped strings
+
+beforeEach(() => {
+ store.clear();
+ alertSpy.mockClear();
+});
+
+describe('recordCellRead — sweep anomaly detection', () => {
+ it('does not alert for a real user polling ONE cell repeatedly', async () => {
+ for (let i = 0; i < 30; i++) await recordCellRead('1.2.3.4', 'u4pruyd');
+ expect(alertSpy).not.toHaveBeenCalled();
+ });
+
+ it('does not alert below the distinct-cell threshold', async () => {
+ for (let i = 0; i < THRESHOLD - 1; i++) await recordCellRead('1.2.3.4', cell(i));
+ expect(alertSpy).not.toHaveBeenCalled();
+ });
+
+ it('fires exactly ONE deduped alert once distinct cells cross the threshold', async () => {
+ for (let i = 0; i < THRESHOLD + 8; i++) await recordCellRead('1.2.3.4', cell(i));
+ // Latched per window: one alert, not one-per-cell after the threshold.
+ expect(alertSpy).toHaveBeenCalledTimes(1);
+ const [title, detail, opts] = alertSpy.mock.calls[0];
+ expect(title).toBe('IRL sweep suspected');
+ // Deduped by the IP hash so a sustained sweep is one alert per window.
+ expect(opts.signature).toMatch(/^irl-sweep:[0-9a-f]{16}$/);
+ });
+
+ it('the alert is COORDINATE-FREE and never carries the raw IP', async () => {
+ const rawIp = '203.0.113.55';
+ for (let i = 0; i < THRESHOLD; i++) await recordCellRead(rawIp, cell(i));
+ expect(alertSpy).toHaveBeenCalledTimes(1);
+ const [, detail, opts] = alertSpy.mock.calls[0];
+ const blob = `${detail}\n${opts.signature}`;
+ // Never the raw IP, never a geocell value, never a lat/lng.
+ expect(blob).not.toContain(rawIp);
+ expect(blob).not.toContain(cell(0));
+ expect(blob).not.toMatch(/-?\d{1,3}\.\d{3,}/); // no decimal coordinate
+ // Carries the count + a 16-hex IP hash only.
+ expect(detail).toMatch(/\d+\+ distinct geocells/);
+ expect(detail).toMatch(/ip_hash [0-9a-f]{16}/);
+ });
+
+ it('scopes distinct-cell counting per caller — two IPs each under the threshold do not alert', async () => {
+ for (let i = 0; i < THRESHOLD - 2; i++) {
+ await recordCellRead('10.0.0.1', cell(i));
+ await recordCellRead('10.0.0.2', cell(i + 100));
+ }
+ expect(alertSpy).not.toHaveBeenCalled();
+ });
+
+ it('no-ops on a missing ip or cell (never throws)', async () => {
+ await expect(recordCellRead(null, 'u4pruyd')).resolves.toBeUndefined();
+ await expect(recordCellRead('1.2.3.4', null)).resolves.toBeUndefined();
+ expect(alertSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/irl-floor-anchor.test.js b/tests/irl-floor-anchor.test.js
index 795ffd21d..fffac1564 100644
--- a/tests/irl-floor-anchor.test.js
+++ b/tests/irl-floor-anchor.test.js
@@ -90,6 +90,56 @@ describe('anchorPoseToPin', () => {
});
});
+// ── Render-back yaw precision (irl-floor-anchor task 02) ─────────────────────
+// The viewer derives facing from the stored anchor_quat (full float) rather than
+// the rounded anchor_yaw_deg, so a non-axis placement reloads at the EXACT tap
+// angle for every viewer. These tests pin that the float survives the persist →
+// render-back round-trip — the justification for keeping anchor_quat a live column
+// instead of a dead field. pinYawRad in src/irl.js applies this same
+// yawDegFromQuat(...pin.anchor_quat) on the read path.
+describe('anchor_quat precision survives the persist → render-back round-trip', () => {
+ // What the renderer does with a stored pin: read yaw straight off anchor_quat,
+ // normalised to [0,360) exactly as pinYawRad / spawnNearbyPin reads it back.
+ const renderBackYaw = (quat) => (((yawDegFromQuat(...quat) % 360) + 360) % 360);
+
+ it('a fractional, non-axis yaw (137.4°) reloads within <0.5°', () => {
+ const TAP = 137.4; // deliberately off every cardinal AND not a whole degree
+ const pin = anchorPoseToPin({
+ originLat: ORIGIN.lat, originLng: ORIGIN.lng,
+ x: 0, y: 0, z: 0, quat: yawQuat(TAP),
+ });
+ // The render-back source (anchor_quat) keeps the fractional angle…
+ expect(Math.abs(renderBackYaw(pin.quat) - TAP)).toBeLessThan(0.5);
+ // …while the rounded heading column has already discarded the .4° tail. This
+ // gap is the whole reason render-back prefers the quat.
+ expect(pin.heading).toBe(137);
+ expect(Math.abs(pin.heading - TAP)).toBeGreaterThan(0.3);
+ });
+
+ it('a fine sweep of off-axis tap angles each reload within <0.5°', () => {
+ for (const TAP of [12.7, 47.6, 99.1, 137.4, 211.95, 268.3, 314.85, 359.6]) {
+ const pin = anchorPoseToPin({
+ originLat: ORIGIN.lat, originLng: ORIGIN.lng,
+ x: 0, y: 0, z: 0, quat: yawQuat(TAP),
+ });
+ const back = renderBackYaw(pin.quat);
+ // Compare on the circle so 359.6° vs 0.x° wraps cleanly.
+ const delta = Math.min(Math.abs(back - TAP), 360 - Math.abs(back - TAP));
+ expect(delta).toBeLessThan(0.5);
+ }
+ });
+
+ it('the quat-derived yaw beats the integer column for a sub-degree placement', () => {
+ // Two taps that the integer anchor_yaw_deg cannot tell apart (both round to
+ // 90°) stay distinct through the quat — proving the column carries real signal.
+ const a = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 0, y: 0, z: 0, quat: yawQuat(90.3) });
+ const b = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 0, y: 0, z: 0, quat: yawQuat(89.7) });
+ expect(a.heading).toBe(b.heading); // 90 === 90 — the rounded column collapses them
+ expect(renderBackYaw(a.quat)).not.toBe(renderBackYaw(b.quat)); // the quat does not
+ expect(renderBackYaw(a.quat) - renderBackYaw(b.quat)).toBeCloseTo(0.6, 5);
+ });
+});
+
describe('round-trip property: anchorPoseToPin then geoToLocal is identity', () => {
it('survives within 1e-6 for assorted offsets', () => {
for (const [x, z] of [[0, 0], [2, -3], [-4, 1], [12, 12], [-7.5, -2.25], [0.1, -0.1]]) {
diff --git a/vercel.json b/vercel.json
index 216c55018..53b073192 100644
--- a/vercel.json
+++ b/vercel.json
@@ -755,6 +755,10 @@
"src": "/irl/?",
"dest": "/irl.html"
},
+ {
+ "src": "/irl-privacy/?",
+ "dest": "/irl-privacy.html"
+ },
{
"src": "/ibm/x402-demo",
"dest": "/ibm/x402-demo.html"