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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
chore: update IRL room, avatar draft endpoint, x402, and skill prices
nirholas6abc25877c97
diff --git a/api/_lib/x-post.js b/api/_lib/x-post.jsindex ad2de6878..a82f2c206 100644--- a/api/_lib/x-post.js+++ b/api/_lib/x-post.js@@ -63,9 +63,11 @@ async function refreshIfNeeded(conn) {return tok.access_token;}-async function postOne({ accessToken, text, replyTo }) {- const body = { text };+async function postOne({ accessToken, text, replyTo, mediaIds = null }) {+ const body = {};+ if (text) body.text = text;if (replyTo) body.reply = { in_reply_to_tweet_id: replyTo };+ if (mediaIds && mediaIds.length) body.media = { media_ids: mediaIds };const r = await fetch('https://api.twitter.com/2/tweets', {method: 'POST',headers: { 'content-type': 'application/json', authorization: `Bearer ${accessToken}` },@@ -75,13 +77,83 @@ async function postOne({ accessToken, text, replyTo }) {return (await r.json()).data;}+// Chunked upload of a screenshot / clip to X's v2 media endpoint, returning the+// media_id to attach to a tweet. Single endpoint, command-driven (INIT → APPEND+// → FINALIZE → STATUS), authenticated with the connected user's OAuth2 token —+// which must carry the `media.write` scope (granted on connect, see auth/x).+// Video is processed asynchronously, so we poll STATUS until it succeeds.+const X_MEDIA_UPLOAD_URL = 'https://api.x.com/2/media/upload';+const X_MEDIA_CHUNK_BYTES = 4 * 1024 * 1024; // 4 MB — X's per-APPEND ceiling++function mediaCategoryFor(mimeType) {+ if (mimeType.startsWith('video/')) return 'tweet_video';+ if (mimeType === 'image/gif') return 'tweet_gif';+ return 'tweet_image';+}++export async function uploadMediaV2({ accessToken, buffer, mimeType }) {+ const total = buffer.length;+ const auth = { authorization: `Bearer ${accessToken}` };++ const initForm = new FormData();+ initForm.set('command', 'INIT');+ initForm.set('media_type', mimeType);+ initForm.set('total_bytes', String(total));+ initForm.set('media_category', mediaCategoryFor(mimeType));+ const initRes = await fetch(X_MEDIA_UPLOAD_URL, { method: 'POST', headers: auth, body: initForm });+ if (!initRes.ok)+ throw new XPostError('media_upload_failed', `media INIT failed: ${(await initRes.text()).slice(0, 200)}`, 502);+ const initJson = await initRes.json();+ const mediaId = initJson?.data?.id || initJson?.data?.media_id_string || initJson?.media_id_string;+ if (!mediaId) throw new XPostError('media_upload_failed', 'media INIT returned no id', 502);++ let segment = 0;+ for (let offset = 0; offset < total; offset += X_MEDIA_CHUNK_BYTES) {+ const chunk = buffer.subarray(offset, Math.min(offset + X_MEDIA_CHUNK_BYTES, total));+ const appendForm = new FormData();+ appendForm.set('command', 'APPEND');+ appendForm.set('media_id', mediaId);+ appendForm.set('segment_index', String(segment));+ appendForm.set('media', new Blob([chunk], { type: 'application/octet-stream' }), 'chunk');+ const appendRes = await fetch(X_MEDIA_UPLOAD_URL, { method: 'POST', headers: auth, body: appendForm });+ if (!appendRes.ok)+ throw new XPostError('media_upload_failed', `media APPEND ${segment} failed: ${(await appendRes.text()).slice(0, 200)}`, 502);+ segment++;+ }++ const finalizeForm = new FormData();+ finalizeForm.set('command', 'FINALIZE');+ finalizeForm.set('media_id', mediaId);+ const finalizeRes = await fetch(X_MEDIA_UPLOAD_URL, { method: 'POST', headers: auth, body: finalizeForm });+ if (!finalizeRes.ok)+ throw new XPostError('media_upload_failed', `media FINALIZE failed: ${(await finalizeRes.text()).slice(0, 200)}`, 502);+ const finalizeJson = await finalizeRes.json();+ let info = finalizeJson?.data?.processing_info || finalizeJson?.processing_info || null;++ // Async transcode (video): poll STATUS until the asset is ready or fails.+ let tries = 0;+ while (info && (info.state === 'pending' || info.state === 'in_progress') && tries < 30) {+ await new Promise((r) => setTimeout(r, Math.min((info.check_after_secs || 1) * 1000, 5000)));+ const statusRes = await fetch(`${X_MEDIA_UPLOAD_URL}?command=STATUS&media_id=${mediaId}`, { headers: auth });+ if (!statusRes.ok) break;+ const statusJson = await statusRes.json();+ info = statusJson?.data?.processing_info || statusJson?.processing_info || null;+ tries++;+ }+ if (info && info.state === 'failed')+ throw new XPostError('media_processing_failed', info?.error?.message || 'media processing failed', 502);++ return mediaId;+}+// Publish a single tweet (text) or a thread (threadParts).// Counts each tweet against the user's monthly quota.// Optionally appends a link to https://three.ws/avatars/<agentId> on the final tweet.-export async function publishTweet({ userId, agentId = null, text, threadParts = null, replyTo = null, appendLink = false }) {+export async function publishTweet({ userId, agentId = null, text, threadParts = null, replyTo = null, appendLink = false, mediaBuffer = null, mediaMimeType = null }) {if (!env.X_OAUTH_CLIENT_ID || !env.X_OAUTH_CLIENT_SECRET) {throw new XPostError('not_configured', 'X OAuth is not configured', 501);}+ const hasMedia = mediaBuffer && mediaBuffer.length > 0 && mediaMimeType;const parts = Array.isArray(threadParts) && threadParts.length? threadParts.map((s) => String(s || '').trim()).filter(Boolean)@@ -135,15 +207,19 @@ export async function publishTweet({ userId, agentId = null, text, threadParts =}}- // Dedup on first part of thread.- const head = parts[0];- const dup = await sql`- select 1 from x_posts- where user_id = ${userId} and text = ${head}- and created_at > now() - ${`${DEDUP_WINDOW_DAYS} days`}::interval- limit 1- `;- if (dup.length) throw new XPostError('duplicate', `same text posted within the last ${DEDUP_WINDOW_DAYS} days`, 409);+ // Dedup on first part of thread. Skipped for media posts: a user sharing+ // several distinct screenshots / clips of the same avatar reuses the same+ // caption legitimately, so identical text alone must not block them.+ if (!hasMedia) {+ const head = parts[0];+ const dup = await sql`+ select 1 from x_posts+ where user_id = ${userId} and text = ${head}+ and created_at > now() - ${`${DEDUP_WINDOW_DAYS} days`}::interval+ limit 1+ `;+ if (dup.length) throw new XPostError('duplicate', `same text posted within the last ${DEDUP_WINDOW_DAYS} days`, 409);+ }// Append link-back to agent page on final tweet (if it fits).if (appendLink && agentId) {@@ -157,10 +233,16 @@ export async function publishTweet({ userId, agentId = null, text, threadParts =const accessToken = await refreshIfNeeded(conn);+ // Upload media once and attach to the first (head) tweet only.+ const mediaIds = hasMedia+ ? [await uploadMediaV2({ accessToken, buffer: mediaBuffer, mimeType: mediaMimeType })]+ : null;+const published = [];let prevId = replyTo;- for (const part of parts) {- const d = await postOne({ accessToken, text: part, replyTo: prevId });+ for (let i = 0; i < parts.length; i++) {+ const part = parts[i];+ const d = await postOne({ accessToken, text: part, replyTo: prevId, mediaIds: i === 0 ? mediaIds : null });published.push(d);await sql`insert into x_posts (user_id, agent_id, tweet_id, text, reply_to_tweet_id)diff --git a/api/agents/[id]/skill-prices.js b/api/agents/[id]/skill-prices.jsindex 9d27f2f5b..162b17ebd 100644--- a/api/agents/[id]/skill-prices.js+++ b/api/agents/[id]/skill-prices.js@@ -16,12 +16,26 @@ import { requireCsrf } from '../../_lib/csrf.js';import { invalidateSkillPriceCache } from '../../_lib/skill-price-cache.js';import { z } from 'zod';-const upsertSchema = z.object({- skill: z.string().trim().min(1).max(100),- amount: z.number().int().min(1),- currency_mint: z.string().trim().min(1).max(100),- chain: z.string().trim().min(1).max(20).default('solana'),-});+const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const upsertSchema = z+ .object({+ skill: z.string().trim().min(1).max(100),+ // Required for a price gate; stored as 0 for an NFT gate (access = holding).+ amount: z.number().int().min(1).optional(),+ currency_mint: z.string().trim().min(1).max(100),+ chain: z.string().trim().min(1).max(20).default('solana'),+ gate_type: z.enum(['price', 'nft']).default('price'),+ nft_collection_mint: z.string().trim().regex(SOLANA_ADDRESS_RE).nullable().optional(),+ })+ .refine((p) => p.gate_type === 'nft' || (p.amount ?? 0) >= 1, {+ message: 'amount is required for a priced skill',+ path: ['amount'],+ })+ .refine((p) => p.gate_type !== 'nft' || !!p.nft_collection_mint, {+ message: 'nft_collection_mint is required for an NFT gate',+ path: ['nft_collection_mint'],+ });const updateSchema = z.object({skill: z.string().trim().min(1).max(100),@@ -78,16 +92,23 @@ export default wrap(async (req, res) => {parsed.error.issues[0]?.message || 'invalid',);}- const { skill, amount, currency_mint, chain } = parsed.data;+ const { skill, currency_mint, chain, gate_type } = parsed.data;+ const isNft = gate_type === 'nft';+ const amount = isNft ? 0 : parsed.data.amount;+ const nftCollectionMint = isNft ? parsed.data.nft_collection_mint : null;await sql`- INSERT INTO agent_skill_prices (agent_id, skill, amount, currency_mint, chain, is_active)- VALUES (${agentId}, ${skill}, ${amount}, ${currency_mint}, ${chain}, true)+ INSERT INTO agent_skill_prices+ (agent_id, skill, amount, currency_mint, chain, is_active, gate_type, nft_collection_mint)+ VALUES (${agentId}, ${skill}, ${amount}, ${currency_mint}, ${chain}, true,+ ${isNft ? 'nft' : 'price'}, ${nftCollectionMint})ON CONFLICT (agent_id, skill) DO UPDATE SET- amount = EXCLUDED.amount,- currency_mint = EXCLUDED.currency_mint,- chain = EXCLUDED.chain,- is_active = true,- updated_at = now()+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ chain = EXCLUDED.chain,+ is_active = true,+ gate_type = EXCLUDED.gate_type,+ nft_collection_mint = EXCLUDED.nft_collection_mint,+ updated_at = now()`;await invalidateSkillPriceCache(agentId);return json(res, 200, { data: { ok: true } });diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].jsindex 9b2a2e430..3d810d7ba 100644--- a/api/agents/x402/[action].js+++ b/api/agents/x402/[action].js@@ -133,7 +133,13 @@ async function handleInvoke(req, res) {});return json(res, 200, {ok: true,- access: access.via_subscription ? 'subscription' : access.trial ? 'trial' : 'purchase',+ access: access.via_subscription+ ? 'subscription'+ : access.via_nft+ ? 'nft'+ : access.trial+ ? 'trial'+ : 'purchase',...(access.trial? { trial_remaining: Math.max(0, (access.trial_remaining ?? 1) - 1) }: {}),@@ -141,6 +147,24 @@ async function handleInvoke(req, res) {});}+ // NFT-gated but the caller doesn't hold the collection. Payment cannot unlock+ // it — access is the on-chain holding — so there is no x402 challenge to issue.+ // Return 402 with the required collection so the caller knows what to acquire.+ if (access.gate?.type === 'nft') {+ return error(+ res,+ 402,+ 'nft_gate_required',+ `You need to hold an NFT from collection ${access.gate.collection} to use this skill.`,+ {+ agent_id: agent.id,+ skill: body.skill,+ reason: access.reason || 'nft_required',+ gate: { type: 'nft', collection: access.gate.collection },+ },+ );+ }+// Priced but unowned. A human session caller (cookie auth) cannot construct an// x402 payment, so a 402 pay-per-call challenge — meant for autonomous agents —// is a dead end for them. Send them to the marketplace with a 403 instead.diff --git a/api/avatars/draft/[id].js b/api/avatars/draft/[id].jsnew file mode 100644index 000000000..9542b07f4--- /dev/null+++ b/api/avatars/draft/[id].js@@ -0,0 +1,122 @@+// Avatar customization draft preview — ephemeral, capability-scoped.+//+// PUT /api/avatars/draft/:id — owner stores an in-progress appearance under a+// client-generated, unguessable id. We resolve the+// avatar's BASE (unbaked) GLB server-side and cache+// { base_model_url, appearance, name } for an hour.+// GET /api/avatars/draft/:id — the walk page reads the draft back (the id is the+// capability token) and renders the unsaved look.+//+// Why a server round-trip instead of cramming appearance into the URL: the walk+// page loads a *private* avatar's GLB, which needs a freshly presigned URL the+// editor client can't mint. Stashing the draft also keeps the deep-link short and+// lets the look survive a reload. Drafts are never persisted to the DB — they live+// in the cache (Redis with in-memory fallback) and expire.++import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';+import { getAvatar } from '../../_lib/avatars.js';+import { presignGet } from '../../_lib/r2.js';+import { cors, error, json, method, wrap, readJson, rateLimited } from '../../_lib/http.js';+import { requireCsrf } from '../../_lib/csrf.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { cacheGet, cacheSet } from '../../_lib/cache.js';+import { avatarAppearance, isUuid } from '../../_lib/validate.js';+import { z } from 'zod';++const DRAFT_TTL_SECONDS = 3600; // 1 hour — long enough to tweak + preview, short enough to forget+const URL_EXPIRES_IN = DRAFT_TTL_SECONDS; // keep the presigned GLB alive for the draft's lifetime++// Draft ids are client-minted (crypto.randomUUID / randomToken). Constrain the+// charset/length so the id can't smuggle a `:` into the cache key namespace.+const DRAFT_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;++const putSchema = z.object({+ avatar_id: z.string().refine(isUuid, 'invalid avatar id'),+ appearance: avatarAppearance.nullable().optional(),+});++function draftKey(id) {+ return `avatar-draft:${id}`;+}++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, source: 'session' };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer && hasScope(bearer.scope, 'avatars:write')) {+ return { userId: bearer.userId, source: 'bearer' };+ }+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'PUT'])) return;++ const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').pop();+ if (!id || !DRAFT_ID_RE.test(id)) {+ return error(res, 400, 'invalid_request', 'invalid draft id');+ }++ if (req.method === 'GET') {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const draft = await cacheGet(draftKey(id));+ if (!draft) return error(res, 404, 'not_found', 'draft not found or expired');+ // Surface only what the walk page needs — never the owner id or storage key.+ return json(res, 200, {+ draft: {+ base_model_url: draft.base_model_url,+ appearance: draft.appearance || null,+ name: draft.name || 'Avatar',+ },+ });+ }++ // PUT — owner stores / refreshes the draft.+ const auth = await resolveAuth(req);+ if (!auth) {+ return error(res, 401, 'unauthorized', 'sign in or provide a token with avatars:write');+ }++ const rl = await limits.publicIp(`draft:${auth.userId}`);+ if (!rl.success) return rateLimited(res, rl);++ if (auth.source === 'session' && !(await requireCsrf(req, res, auth.userId))) return;++ const body = await readJson(req);+ const data = putSchema.safeParse(body);+ if (!data.success) {+ return error(res, 400, 'validation_error', data.error.issues[0]?.message || 'invalid draft', {+ issues: data.error.issues,+ });+ }++ const avatar = await getAvatar({ id: data.data.avatar_id, requesterId: auth.userId });+ if (!avatar) return error(res, 404, 'not_found', 'avatar not found');+ if (avatar.owner_id !== auth.userId) {+ return error(res, 403, 'forbidden', 'you do not own this avatar');+ }+ if (!avatar.storage_key) return error(res, 422, 'unprocessable', 'avatar has no model to preview');++ // Resolve the BASE (unbaked) GLB — the editor applies appearance client-side,+ // so loading the baked URL would double-stack outfits. Public/unlisted avatars+ // already carry a CDN base_model_url; private ones get a short-lived presign.+ const baseModelUrl =+ avatar.base_model_url || (await presignGet({ key: avatar.storage_key, expiresIn: URL_EXPIRES_IN }));++ await cacheSet(+ draftKey(id),+ {+ owner_id: auth.userId,+ avatar_id: avatar.id,+ name: avatar.name || 'Avatar',+ base_model_url: baseModelUrl,+ appearance: data.data.appearance || null,+ },+ DRAFT_TTL_SECONDS,+ );++ return json(res, 200, { ok: true, draft_id: id, expires_in: DRAFT_TTL_SECONDS });+});diff --git a/pages/irl.html b/pages/irl.htmlindex 1465a2415..a3471b97e 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -2073,7 +2073,7 @@<h1 class="irl-avatar-name" id="irl-avatar-name">Loading…</h1><p class="irl-subtitle" id="irl-subtitle">Turn on Camera AR, then tap Pin here to anchor your agent in real space.</p>- <p class="irl-status is-hidden" id="irl-status">+ <p class="irl-status is-hidden" id="irl-status" role="status" aria-live="polite"><span class="irl-status-spinner hidden" id="irl-spinner" aria-hidden="true"></span><span id="irl-status-text"></span></p>diff --git a/scripts/irl-room-qa.mjs b/scripts/irl-room-qa.mjsindex c98e36330..e848b6f88 100644--- a/scripts/irl-room-qa.mjs+++ b/scripts/irl-room-qa.mjs@@ -213,22 +213,37 @@ console.log('6) Placement-capability matrix (the WebXR-on-iOS gate)');}}-// ── 7) Deployed API probe (optional, --url) — the GET/POST contract is LIVE ───-// Read-first: confirms GET /api/irl/pins carries the room columns in its shape.-// Does NOT place a pin (a write needs a device token + would litter prod). The-// real POST round-trip is the on-device step; this just proves the endpoint is up-// and the room fields survived the deploy (R4 §6 pre-condition).+// ── 7) Deployed API probe (optional, --url) — the LIVE GET contract + auth ────+// Exercises the real proof-of-presence handshake the on-device client uses:+// POST /api/irl/fix-token { lat,lng } → token (anti-GPS-spoof, H3)+// GET /api/irl/pins?lat,lng with x-irl-fix: <token> → { pins:[…] }+// then asserts the room columns survived the deploy (R4 §6 pre-condition) and the+// viewer projection never leaks owner identity. Read-only: it does NOT place a pin+// (a write would litter prod) — the POST round-trip is the on-device step. An+// empty `pins` near the synthetic coord is expected and still proves the contract.const urlArg = process.argv.indexOf('--url');if (urlArg !== -1 && process.argv[urlArg + 1]) {const base = process.argv[urlArg + 1].replace(/\/$/, '');- console.log(`7) Deployed probe — ${base}/api/irl/pins`);+ console.log(`7) Deployed probe — ${base}/api/irl`);+ const LAT = 37.7749, LNG = -122.4194;const ROOM_KEYS = ['room_id', 'rel_east_m', 'rel_north_m', 'origin_lat', 'origin_lng', 'origin_yaw_deg'];try {- // San Francisco sample coord; an empty result is fine — we assert the SHAPE.- const res = await fetch(`${base}/api/irl/pins?lat=37.7749&lng=-122.4194&deviceToken=room-qa-probe`, {- headers: { accept: 'application/json' },+ // A bare lat/lng read must be REFUSED — proof-of-presence is the whole point.+ const noFix = await fetch(`${base}/api/irl/pins?lat=${LAT}&lng=${LNG}&deviceToken=room-qa-probe`, { headers: { accept: 'application/json' } });+ check('a read WITHOUT a fix token is refused (anti-spoof gate live)', noFix.status === 401);++ // Mint the short-lived presence proof, exactly as the client does.+ const mint = await fetch(`${base}/api/irl/fix-token`, {+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ lat: LAT, lng: LNG }),+ });+ check('POST /api/irl/fix-token mints a presence proof (2xx)', mint.ok);+ const token = (await mint.json().catch(() => ({}))).token;+ check('the mint returns a signed token', typeof token === 'string' && token.length > 16);++ const res = await fetch(`${base}/api/irl/pins?lat=${LAT}&lng=${LNG}&deviceToken=room-qa-probe`, {+ headers: { accept: 'application/json', 'x-irl-fix': token || '' },});- check('GET returns a 2xx', res.ok);+ check('GET /api/irl/pins with the fix token returns 2xx', res.ok);const data = await res.json().catch(() => null);check('response is JSON with a pins array', Array.isArray(data?.pins));if (Array.isArray(data?.pins) && data.pins.length) {@@ -237,10 +252,10 @@ if (urlArg !== -1 && process.argv[urlArg + 1]) {check('viewer rows expose is_mine boolean, never user_id/device_token',typeof p.is_mine === 'boolean' && !('user_id' in p) && !('device_token' in p));} else {- console.log(' · no pins near the probe coord — shape check skipped (place one on-device to fully verify)');+ console.log(' · no pins near the synthetic probe coord — contract proven, per-row shape needs a live pin (place one on-device)');}} catch (err) {- check(`GET /api/irl/pins reachable (${err?.message || err})`, false);+ check(`deployed /api/irl reachable (${err?.message || err})`, false);}} else {console.log('7) Deployed probe — skipped (pass --url https://three.ws to run it)');diff --git a/src/irl.js b/src/irl.jsindex 8dafe38cf..6bbb22e20 100644--- a/src/irl.js+++ b/src/irl.js@@ -2204,7 +2204,7 @@ function compassLabel(deg) {return dirs[Math.round(((deg % 360) + 360) % 360 / 45) % 8];}-async function savePin(lat, lng, heading = 0, caption = '', anchor = null) {+async function savePin(lat, lng, heading = 0, caption = '', anchor = null, placement = null) {try {// Anchor pose (A2): a reproducible record of where the agent stands —// floor height, orientation, and how trustworthy this GPS fix was — so a@@ -2241,6 +2241,11 @@ async function savePin(lat, lng, heading = 0, caption = '', anchor = null) {deviceToken: _deviceToken,agentId: _currentAgentId || null,anchor: anchorBody,+ // Placement consent (H4): the kind + radius the coordinate above was+ // already fuzzed by (precise → unchanged). The server stores only this+ // fuzzed spot, never the true one. Defaults keep old behaviour intact.+ placement: placement?.placementKind || 'precise',+ fuzzRadiusM: placement?.fuzzRadiusM || 0,}),});if (!r.ok) {@@ -2591,6 +2596,12 @@ function commitPin(pinLat, pinLng, headingDeg, caption, source = 'gyro-gps') {setLocked(false);return;}+ // Placement consent (H4): in approximate mode fuzz the coordinate HERE, at commit,+ // so the true standing spot is never persisted AND the agent renders at the fuzzed+ // spot for everyone — including the owner (gpsPin below). Precise mode is a no-op.+ const place = applyPlacementKind(pinLat, pinLng);+ pinLat = place.lat;+ pinLng = place.lng;gpsPin = { lat: pinLat, lng: pinLng, heightM: 0 };// Gyro-GPS placement pose (A2/A3): the agent stands on the floor. anchor_height_m// is a floor-relative offset, and gyro placement has no measured floor depth, so@@ -2602,11 +2613,14 @@ function commitPin(pinLat, pinLng, headingDeg, caption, source = 'gyro-gps') {// Tell the truth about precision: a noisy fix (>25 m) is an approximate spot, not a// pinpoint. The exact metres ride the stored gpsAccuracyM (savePin); here we surface// a subtle note so the success copy never implies more accuracy than the fix had.+ // An intentionally-approximate placement says so plainly instead of citing the fix.const acc = gpsAccuracyBucket(gpsState.accuracy);// Only annotate when we have a concrete metres figure to show (skip the unknown// bucket, which has no label — no number, nothing honest to add).- const accNote = acc.precise || !acc.label ? '' : ` · approximate spot (${acc.label})`;- savePin(pinLat, pinLng, headingDeg, caption, anchor).then(result => {+ const accNote = place.placementKind === 'approximate'+ ? ` · approximate spot (~${place.fuzzRadiusM} m)`+ : acc.precise || !acc.label ? '' : ` · approximate spot (${acc.label})`;+ savePin(pinLat, pinLng, headingDeg, caption, anchor, place).then(result => {if (result?.ok && gpsPin) {gpsPin.id = result.id;_myPinIds.add(result.id);@@ -2643,9 +2657,14 @@ function startMapPlacement() {// Optional caption step for a map-placed pin. Reuses the caption panel UI but// routes confirm/cancel to the remote commit — cancel just closes (there is no AR// lock to release, unlike the gyro/GPS caption flow).-function openCaptionForMapPin(lat, lng, label) {+async function openCaptionForMapPin(lat, lng, label) {+ // Same consent gate as the GPS path (H4) — a map-placed agent is still a public+ // real-world spot, and approximate placement applies here too. Cancelling just+ // drops out (no AR lock to release on this remote path).+ if (!(await maybeConfirmPlacement())) return;if (!captionPanel) { commitMapPin(lat, lng, '', label); return; }captionInput.value = '';+ refreshCaptionPlacementChip();captionPanel.classList.add('is-open');focusCaptionWhenOpen();const close = () => { captionPanel.classList.remove('is-open'); releaseSheet(captionPanel); };@@ -2660,9 +2679,12 @@ function openCaptionForMapPin(lat, lng, label) {async function commitMapPin(lat, lng, caption, label) {setStatus('Placing agent…', { loading: true, sticky: true });+ // Apply the placement choice (H4) — approximate fuzzes the chosen point so only+ // the blurred spot is ever stored. precise leaves it untouched.+ const place = applyPlacementKind(lat, lng);// source:'map' → the server records a non-GPS, non-compass placement; savePin// nulls the GPS accuracy/altitude for it. heading 0 (no live bearing to store).- const result = await savePin(lat, lng, 0, caption, { heightM: 0, yawDeg: 0, source: 'map' });+ const result = await savePin(place.lat, place.lng, 0, caption, { heightM: 0, yawDeg: 0, source: 'map' }, place);if (result?.ok) {_myPinIds.add(result.id);const where = label ? ` at ${label}` : '';@@ -4455,6 +4477,20 @@ function _pinMetaLine(p) {return parts.join(' · ');}+// Exact/Approximate badge (H4) for an owned pin row — so the owner always sees how+// exposed each placement is. An approximate pin shows its blur radius; precise (and+// legacy pins with no placement_kind) show the exact pin. Returns escaped HTML.+function _placementBadgeHTML(p) {+ const approx = p?.placement_kind === 'approximate';+ const text = approx+ ? `≈ Approximate (~${Math.round(Number(p.fuzz_radius_m) || PLACEMENT_FUZZ_DEFAULT)} m)`+ : '📍 Exact';+ const title = approx+ ? 'Stored at a deliberately blurred spot — your exact location was never saved.'+ : 'Stored at the exact spot you placed it.';+ return `<span class="irl-pin-place${approx ? ' is-approx' : ''}" title="${_escHtml(title)}">${_escHtml(text)}</span>`;+}+// Designed empty state for the My-pins sheet — shared by loadInto (sheet open)// and deleteMyPin (when the last pin is removed) so the copy never diverges.const MYPINS_EMPTY = {@@ -4498,7 +4534,7 @@ function renderMyPins(pins, listEl) {if (!list) return;list.innerHTML = pins.map(p => `<div class="irl-pin-row" data-pid="${_escHtml(p.id)}"><div class="irl-pin-info">- <div class="irl-pin-name">${_escHtml(p.avatar_name || 'Agent')}</div>+ <div class="irl-pin-name">${_escHtml(p.avatar_name || 'Agent')}${_placementBadgeHTML(p)}</div>${p.caption ? `<div class="irl-pin-caption">${_escHtml(p.caption)}</div>` : ''}<div class="irl-pin-meta">${_pinMetaLine(p)}</div></div>diff --git a/tests/api/irl-privacy-center.test.js b/tests/api/irl-privacy-center.test.jsnew file mode 100644index 000000000..3b5fa395d--- /dev/null+++ b/tests/api/irl-privacy-center.test.js@@ -0,0 +1,291 @@+// IRL privacy-center invariants (H5 — IRL-Hardening right-to-be-forgotten).+//+// Drives the REAL api/irl/privacy.js handler with a content-addressed SQL mock so+// the ownership + null-guard contract is pinned: a caller sees and erases ONLY+// their own data, an unidentified caller is rejected before any query runs, every+// delete cascades to irl_interactions and returns honest counts, and "forget this+// device" additionally purges the trail the device left on other people's pins.+//+// Fully offline: DB / auth / limiter / guardian all mocked. The mock differentiates+// each statement by content and records bound values, so we can assert the owner+// identifier is threaded into every WHERE (it never widens to another owner).++import { describe, it, expect, vi, beforeEach } from 'vitest';++// ── Content-addressed SQL mock ──────────────────────────────────────────────+const calls = []; // { q, values } for every statement the handler ran+const writes = []; // tags for every mutating statement, in order+let summaryPinAgg = [{}];+let summaryInbox = [{ total: 0 }];+let summaryAuthored = [{ total: 0 }];+let exportPins = [];+let exportReceived = [];+let exportAuthored = [];+let updateResult = []; // PATCH UPDATE RETURNING+let delIx = []; // DELETE FROM irl_interactions (cascade / inbox) RETURNING+let delPins = []; // DELETE FROM irl_pins RETURNING+let delAuthored = []; // DELETE FROM irl_interactions (viewer_device) RETURNING++const P = (v) => Promise.resolve(v);++const sqlMock = vi.fn((strings, ...values) => {+ const raw = Array.isArray(strings) ? strings.join(' ') : String(strings);+ const q = raw.replace(/\s+/g, ' ').trim();+ calls.push({ q, values });++ // ── Summary aggregates ──+ if (/FILTER \(WHERE hidden_at IS NOT NULL\)/i.test(q)) return P(summaryPinAgg);+ if (/JOIN irl_pins/i.test(q) && /COUNT\(\*\)::int\s+AS total/i.test(q)) return P(summaryInbox);+ if (/FROM irl_interactions/i.test(q) && /viewer_device = /i.test(q) && /COUNT\(\*\)::int AS total/i.test(q)) {+ return P(summaryAuthored);+ }++ // ── Export selects ──+ if (/SELECT id, agent_id, lat, lng, heading/i.test(q)) return P(exportPins);+ if (/JOIN irl_pins/i.test(q) && /ix\.currency_mint/i.test(q)) return P(exportReceived);+ if (/SELECT id, pin_id, agent_id, type/i.test(q) && /viewer_device = /i.test(q)) return P(exportAuthored);++ // ── Mutations ──+ if (/UPDATE irl_pins/i.test(q)) { writes.push('update'); return P(updateResult); }+ if (/DELETE FROM irl_interactions/i.test(q)) {+ // The authored purge ("forget device") is the only interactions-delete keyed+ // on viewer_device with no pin_id clause.+ if (/viewer_device IS NOT NULL AND viewer_device = /i.test(q) && !/pin_id/i.test(q)) {+ writes.push('del-authored');+ return P(delAuthored);+ }+ writes.push('del-ix');+ return P(delIx);+ }+ if (/DELETE FROM irl_pins/i.test(q)) { writes.push('del-pins'); return P(delPins); }++ return P([]); // 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 })) },+ 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, { query = {}, body, device } = {}) {+ const res = makeRes();+ const headers = { host: 'x' };+ if (device !== undefined) headers['x-irl-device'] = device;+ await handler({ url: '/api/irl/privacy', method, headers, query, body }, res);+ let parsed = null; try { parsed = JSON.parse(res._body); } catch {}+ return { res, body: parsed };+}++// Does any statement's bound values include this exact value?+const someValueIs = (v) => calls.some((c) => c.values.includes(v));++beforeEach(async () => {+ sqlMock.mockClear();+ calls.length = 0;+ writes.length = 0;+ sessionUser = null;+ summaryPinAgg = [{}];+ summaryInbox = [{ total: 0 }];+ summaryAuthored = [{ total: 0 }];+ exportPins = [];+ exportReceived = [];+ exportAuthored = [];+ updateResult = [];+ delIx = [];+ delPins = [];+ delAuthored = [];+ vi.resetModules();+ ({ default: handler } = await import('../../api/irl/privacy.js'));+});++const DEVICE = 'device-abc-123';+const PIN_ID = '11111111-1111-4111-8111-111111111111';++describe('identity — an unidentified caller owns nothing and runs no query', () => {+ it('no session and no device header → 400 before any SQL', async () => {+ const { res, body } = await call('GET');+ expect(res.statusCode).toBe(400);+ expect(body.error).toMatch(/sign in|x-irl-device/i);+ expect(calls.length).toBe(0);+ });++ it('a whitespace-only device header null-guards to nothing → 400, no SQL', async () => {+ const { res, body } = await call('GET', { device: ' ' });+ expect(res.statusCode).toBe(400);+ expect(body.error).toMatch(/sign in|x-irl-device/i);+ expect(calls.length).toBe(0);+ });+});++describe('GET summary — accurate, plain-language, the caller’s own data only', () => {+ it('reports counts and never leaks a coordinate', async () => {+ summaryPinAgg = [{+ total: 3, unpublished: 1, permanent: 0,+ oldest: '2026-06-01T00:00:00Z', newest: '2026-06-20T00:00:00Z',+ next_expiry: '2026-06-27T00:00:00Z',+ }];+ summaryInbox = [{ total: 5 }];+ summaryAuthored = [{ total: 7 }];++ const { res, body } = await call('GET', { device: DEVICE });+ expect(res.statusCode).toBe(200);+ const s = body.summary;+ expect(s.pins.total).toBe(3);+ expect(s.pins.unpublished).toBe(1);+ expect(s.pins.published).toBe(2);+ expect(s.interactions.onYourPins).toBe(5);+ expect(s.interactions.youLeftElsewhere).toBe(7);+ expect(s.account).toBe('anonymous-device');+ expect(Array.isArray(s.stored)).toBe(true);+ // A summary is counts + copy only — never raw coordinates of anyone.+ expect(res._body).not.toMatch(/"lat"|"lng"/);+ // The device token is threaded into the scoped queries (never widened).+ expect(someValueIs(DEVICE)).toBe(true);+ });++ it('a signed-in caller with no device skips the authored-trail query', async () => {+ sessionUser = { id: 'user-uuid-1' };+ summaryPinAgg = [{ total: 1, unpublished: 0, permanent: 1, oldest: null, newest: null, next_expiry: null }];+ const { res, body } = await call('GET');+ expect(res.statusCode).toBe(200);+ expect(body.summary.account).toBe('signed-in');+ expect(body.summary.interactions.youLeftElsewhere).toBe(0);+ // No statement should be keyed on viewer_device for a tokenless caller.+ expect(calls.some((c) => /viewer_device = /i.test(c.q))).toBe(false);+ });+});++describe('GET export — full JSON of the caller’s own data', () => {+ it('streams pins + both interaction directions with a download header', async () => {+ exportPins = [{ id: PIN_ID, avatar_name: 'Scout', lat: 1, lng: 2 }];+ exportReceived = [{ id: 'ix-1', pin_id: PIN_ID }];+ exportAuthored = [{ id: 'ix-2', pin_id: 'other-pin' }];+ const { res, body } = await call('GET', { query: { export: '1' }, device: DEVICE });+ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-disposition')).toMatch(/attachment; filename="irl-my-data\.json"/);+ expect(body.pins.length).toBe(1);+ expect(body.interactionsOnYourPins.length).toBe(1);+ expect(body.interactionsYouLeft.length).toBe(1);+ expect(body.account).toBe('anonymous-device');+ });+});++describe('PATCH visibility — owner-gated unpublish / republish', () => {+ it('rejects an invalid pinId and a bad action without writing', async () => {+ const bad = await call('PATCH', { body: { pinId: 'not a uuid!!', action: 'unpublish' }, device: DEVICE });+ expect(bad.res.statusCode).toBe(400);+ const badAction = await call('PATCH', { body: { pinId: PIN_ID, action: 'nuke' }, device: DEVICE });+ expect(badAction.res.statusCode).toBe(400);+ expect(writes.length).toBe(0);+ });++ it('unpublish on an owned pin → 200 hidden:true; republish → hidden:false', async () => {+ updateResult = [{ id: PIN_ID, hidden_at: '2026-06-23T00:00:00Z' }];+ const hide = await call('PATCH', { body: { pinId: PIN_ID, action: 'unpublish' }, device: DEVICE });+ expect(hide.res.statusCode).toBe(200);+ expect(hide.body.hidden).toBe(true);++ updateResult = [{ id: PIN_ID, hidden_at: null }];+ const show = await call('PATCH', { body: { pinId: PIN_ID, action: 'republish' }, device: DEVICE });+ expect(show.res.statusCode).toBe(200);+ expect(show.body.hidden).toBe(false);+ });++ it('a non-owner matches no row (UPDATE RETURNING empty) → 404', async () => {+ updateResult = [];+ const { res, body } = await call('PATCH', { body: { pinId: PIN_ID, action: 'unpublish' }, device: 'attacker-device' });+ expect(res.statusCode).toBe(404);+ expect(body.error).toMatch(/not found|not yours/i);+ });+});++describe('DELETE — scope validation, cascade, and honest counts', () => {+ it('rejects an unknown scope and a pin-scope without a valid id', async () => {+ const badScope = await call('DELETE', { body: { scope: 'everything' }, device: DEVICE });+ expect(badScope.res.statusCode).toBe(400);+ const badPin = await call('DELETE', { body: { scope: 'pin', pinId: 'x x x' }, device: DEVICE });+ expect(badPin.res.statusCode).toBe(400);+ expect(writes.length).toBe(0);+ });++ it('scope:pin deletes the pin + its interactions and returns counts', async () => {+ delIx = [{ id: 'ix-1' }, { id: 'ix-2' }];+ delPins = [{ id: PIN_ID }];+ const { res, body } = await call('DELETE', { body: { scope: 'pin', pinId: PIN_ID }, device: DEVICE });+ expect(res.statusCode).toBe(200);+ expect(body.deletedPins).toBe(1);+ expect(body.deletedInteractions).toBe(2);+ expect(writes).toEqual(['del-ix', 'del-pins']);+ });++ it('scope:pin on a non-owned pin (no row deleted) → 404', async () => {+ delIx = [];+ delPins = [];+ const { res, body } = await call('DELETE', { body: { scope: 'pin', pinId: PIN_ID }, device: 'attacker-device' });+ expect(res.statusCode).toBe(404);+ expect(body.error).toMatch(/not found|not yours/i);+ });++ it('scope:all wipes the caller’s pins + inbox but NOT the authored trail', async () => {+ delIx = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];+ delPins = [{ id: 'p1' }, { id: 'p2' }];+ const { res, body } = await call('DELETE', { body: { scope: 'all' }, device: DEVICE });+ expect(res.statusCode).toBe(200);+ expect(body.scope).toBe('all');+ expect(body.deletedPins).toBe(2);+ expect(body.deletedInteractions).toBe(3);+ expect(writes).toEqual(['del-ix', 'del-pins']); // never touches viewer_device rows+ });++ it('scope:device ALSO purges the authored trail and folds it into the count', async () => {+ delIx = [{ id: 'a' }];+ delPins = [{ id: 'p1' }];+ delAuthored = [{ id: 'x' }, { id: 'y' }];+ const { res, body } = await call('DELETE', { body: { scope: 'device' }, device: DEVICE });+ expect(res.statusCode).toBe(200);+ expect(body.scope).toBe('device');+ expect(body.deletedPins).toBe(1);+ expect(body.deletedInteractions).toBe(1 + 2); // inbox + authored+ expect(writes).toEqual(['del-ix', 'del-pins', 'del-authored']);+ // The authored purge is keyed on the exact device token (never widened).+ expect(someValueIs(DEVICE)).toBe(true);+ });++ it('scope:device for a tokenless signed-in caller skips the authored purge', async () => {+ sessionUser = { id: 'user-uuid-2' };+ delIx = [];+ delPins = [{ id: 'p1' }];+ const { res, body } = await call('DELETE', { body: { scope: 'device' } });+ expect(res.statusCode).toBe(200);+ expect(writes).toEqual(['del-ix', 'del-pins']); // no del-authored without a device token+ expect(body.deletedInteractions).toBe(0);+ });++ it('after forget-device, a follow-up summary reads empty', async () => {+ // Simulate the post-wipe state: every aggregate is zero.+ summaryPinAgg = [{ total: 0, unpublished: 0, permanent: 0, oldest: null, newest: null, next_expiry: null }];+ summaryInbox = [{ total: 0 }];+ summaryAuthored = [{ total: 0 }];+ const { res, body } = await call('GET', { device: DEVICE });+ expect(res.statusCode).toBe(200);+ expect(body.summary.pins.total).toBe(0);+ expect(body.summary.interactions.onYourPins).toBe(0);+ expect(body.summary.interactions.youLeftElsewhere).toBe(0);+ });+});