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
feat(irl): mint permanent shareable links for placed pins
nirholas37f98704baea
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 8861f92a7..1c0084fe0 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -540,6 +540,11 @@ export const limits = {// · irlInteractIp — log a tap/view/message (lighter; legit viewing fans out)irlPinIp: (ip) => getLimiter('irl:pin:ip', { limit: 20, window: '10 m' }).limit(ip),irlInteractIp: (ip) => getLimiter('irl:interact:ip', { limit: 60, window: '1 m' }).limit(ip),+ // IRL shareable pin cards (api/irl/share.js) — uploads a real image to R2 per+ // call, so this sits between irlPinIp and irlInteractIp: generous enough for a+ // few reshares of the same moment, tight enough that scripting the upload path+ // can't be used as free image-hosting.+ irlShareIp: (ip) => getLimiter('irl:share:ip', { limit: 10, window: '10 m' }).limit(ip),// Living Stages tip recording (api/stage/tip.js). Each call carries a real// on-chain settlement signature and is deduped per signature, so the limiter// only blunts a forger spamming distinct fake signatures at the recorder — adiff --git a/api/irl/share.js b/api/irl/share.jsnew file mode 100644index 000000000..0e9fea2d7--- /dev/null+++ b/api/irl/share.js@@ -0,0 +1,102 @@+/**+ * IRL Shareable Pin Cards — turn a placed agent into a rich, unfurlable link.+ *+ * POST /api/irl/share?pinId=<id>&deviceToken=<token>+ * Body: raw PNG bytes (the composite AR photo captured client-side by+ * src/irl/share-frame.js), content-type application/octet-stream (see the+ * readBody() note in api/_lib/http.js for why octet-stream, not image/png).+ * Caller must own the pin (session user OR device token, same ownership+ * check as every other owner-gated /api/irl/pins mutation) and the pin must+ * be public (an unpublished/hidden pin can't be turned into a public link —+ * that would be a privacy downgrade the owner never asked for). Uploads the+ * photo to R2 and mints a permanent token.+ * → { token, url, imageUrl }+ *+ * GET /api/irl/share/[token].js serves the actual unfurl page for the token+ * this mints (og:image + a "Place your own agent" CTA) — see that file.+ *+ * The photo is the user's own real-world capture (their room, their street),+ * shared entirely at their own initiative — the same trust model as any+ * native camera-app share sheet. This endpoint adds no new privacy surface+ * beyond what the user just chose to photograph and explicitly tapped Share+ * on; it does NOT expose pin coordinates (the OG page only ever renders the+ * pin's caption/agent name, never lat/lng — see share/[token].js).+ */++import { wrap, cors, json, error, readBody } from '../_lib/http.js';+import { rateLimited } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { readDeviceToken } from '../_lib/irl-auth.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { randomToken } from '../_lib/crypto.js';+import { putObject, publicUrl } from '../_lib/r2.js';+import { logIrlEvent, ensureIrlAnalyticsSchema, hashDeviceToken } from '../_lib/irl-analytics.js';++const MAX_IMAGE_BYTES = 8 * 1024 * 1024; // a captured canvas PNG is typically a few hundred KB–2MB++function originFrom(req) {+ const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';+ const proto = req.headers['x-forwarded-proto'] || (/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https');+ return `${proto}://${host}`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (req.method?.toUpperCase() !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');++ const ip = clientIp(req);+ const rl = await limits.irlShareIp(ip);+ if (!rl.success) return rateLimited(res, rl, 'Too many shares from this connection. Try again shortly.');++ const url = new URL(req.url, 'http://x');+ const pinId = (url.searchParams.get('pinId') || '').trim();+ if (!pinId) return error(res, 400, 'bad_request', 'pinId is required');++ const session = await getSessionUser(req).catch(() => null);+ const deviceToken = readDeviceToken(req);+ if (!session && !deviceToken) return error(res, 401, 'unauthorized', 'sign in or a device token is required');++ let bytes;+ try {+ bytes = await readBody(req, MAX_IMAGE_BYTES);+ } catch (err) {+ return error(res, err.status || 400, 'bad_request', err.message || 'could not read image body');+ }+ if (!bytes || bytes.length < 100) return error(res, 400, 'bad_request', 'a PNG image body is required');++ await ensureIrlAnalyticsSchema();++ const [pin] = await sql`+ SELECT id, lat, lng, caption, avatar_name, published, hidden_at, user_id, device_token+ FROM irl_pins WHERE id = ${pinId}::uuid+ `;+ if (!pin) return error(res, 404, 'not_found', 'pin not found');+ const owns =+ (session && pin.user_id === session.id) ||+ (deviceToken && pin.device_token === deviceToken);+ if (!owns) return error(res, 403, 'forbidden', 'you can only share your own placement');+ if (pin.published === false) return error(res, 409, 'not_shareable', 'unpublish this pin first if you want it private — a private pin can\'t be turned into a public link');+ if (pin.hidden_at) return error(res, 409, 'not_shareable', 'this pin is under review and can\'t be shared right now');++ const token = randomToken(16);+ const key = `irl-share/${token}.png`;++ try {+ await putObject({ key, body: bytes, contentType: 'image/png', metadata: { pinId } });+ } catch (err) {+ return error(res, 502, 'upload_failed', err?.message || 'could not store the share image');+ }++ const imageUrl = publicUrl(key);+ const deviceHash = await hashDeviceToken(deviceToken);+ await sql`+ INSERT INTO irl_pin_shares (pin_id, token, image_key, image_url, device_hash)+ VALUES (${pinId}::uuid, ${token}, ${key}, ${imageUrl}, ${deviceHash})+ `;++ await logIrlEvent({ type: 'share_created', pinId, lat: pin.lat, lng: pin.lng, deviceToken, metadata: { token } });++ const origin = originFrom(req);+ return json(res, 201, { token, url: `${origin}/irl/s/${token}`, imageUrl });+});diff --git a/api/irl/share/[token].js b/api/irl/share/[token].jsnew file mode 100644index 000000000..16fc13356--- /dev/null+++ b/api/irl/share/[token].js@@ -0,0 +1,116 @@+/**+ * GET /api/irl/share/[token] — the unfurl page for a minted IRL share link+ * (see ../share.js for how a token is created). Exposed to browsers/crawlers+ * at the pretty path /irl/s/:token via a vercel.json rewrite.+ *+ * Renders the user's own AR capture full-bleed with real og:image/twitter:image+ * tags (so pasting the link into X/Discord/iMessage unfurls the actual photo,+ * not a generic logo) and a single "Place your own agent" CTA back to /irl —+ * the growth loop this whole feature exists for.+ *+ * Privacy: the page title/description ever renders the pin's caption or the+ * agent's name — NEVER coordinates, NEVER the owner's identity. Same rule the+ * rest of /api/irl/pins already enforces on every public projection.+ */++import { wrap, cors, error } from '../../_lib/http.js';+import { sql } from '../../_lib/db.js';+import { recordShareView } from '../../_lib/irl-analytics.js';++function esc(s) {+ return String(s || '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++function originFrom(req) {+ const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';+ const proto = req.headers['x-forwarded-proto'] || (/^localhost|127\.0\.0\.1/.test(host) ? 'http' : 'https');+ return `${proto}://${host}`;+}++function notFoundPage() {+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"/>+<meta name="viewport" content="width=device-width,initial-scale=1"/><title>Share link expired · three.ws</title>+<meta name="robots" content="noindex"/>+<style>:root{color-scheme:dark}body{margin:0;min-height:100dvh;display:flex;align-items:center;justify-content:center;+font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;background:radial-gradient(130% 130% at 50% 0%,#14161c,#08090c);color:#e8eaf0;text-align:center;padding:28px}+.c{max-width:38ch}.h{font-size:16px;font-weight:600;margin-bottom:10px}.m{color:#9aa3b2;font-size:13px;line-height:1.5}+a{display:inline-block;margin-top:16px;color:#0b0c10;background:#6ea8fe;border-radius:10px;padding:11px 18px;text-decoration:none;font-weight:700;font-size:13px}</style></head>+<body><div class="c"><div class="h">This share link isn't available anymore</div><div class="m">The agent may have moved, or the link expired.</div>+<a href="/irl">Open IRL</a></div></body></html>`;+}++function sharePage({ imageUrl, name, caption, pageUrl, origin }) {+ const t = name ? esc(name) : 'An agent';+ const desc = caption ? esc(caption).slice(0, 160) : 'Someone placed a living 3D agent in the real world with three.ws.';+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"/>+<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"/>+<title>${t} · IRL · three.ws</title>+<meta property="og:type" content="website"/>+<meta property="og:site_name" content="three.ws"/>+<meta property="og:title" content="${t} was placed in the real world"/>+<meta property="og:description" content="${desc}"/>+<meta property="og:image" content="${esc(imageUrl)}"/>+<meta property="og:url" content="${esc(pageUrl)}"/>+<meta name="twitter:card" content="summary_large_image"/>+<meta name="twitter:title" content="${t} was placed in the real world"/>+<meta name="twitter:description" content="${desc}"/>+<meta name="twitter:image" content="${esc(imageUrl)}"/>+<style>:root{color-scheme:dark;--accent:#6ea8fe}*{box-sizing:border-box}html,body{margin:0;height:100%}+body{font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;background:#08090c;color:#e8eaf0}+.wrap{display:flex;flex-direction:column;min-height:100dvh}+.stage{position:relative;flex:1 1 auto;min-height:0;display:flex;align-items:center;justify-content:center;background:#000}+.stage img{max-width:100%;max-height:100dvh;object-fit:contain}+.name{position:absolute;top:14px;left:50%;transform:translateX(-50%);max-width:min(86vw,48ch);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#cdd3de;font-size:13px;font-weight:600;background:rgba(10,11,14,.55);border:1px solid rgba(255,255,255,.08);border-radius:999px;padding:6px 14px;backdrop-filter:blur(8px)}+.bar{display:flex;flex-wrap:wrap;gap:10px;align-items:center;justify-content:center;padding:14px 16px;border-top:1px solid rgba(255,255,255,.07);background:rgba(10,11,14,.65);backdrop-filter:blur(8px)}+a.cta{appearance:none;cursor:pointer;text-decoration:none;font-size:14px;font-weight:700;color:#0b0c10;background:var(--accent);border:0;border-radius:12px;padding:12px 20px;display:inline-flex;align-items:center;gap:8px}+a.alt{color:#aeb6c4;font-size:12.5px;text-decoration:underline;align-self:center}</style></head>+<body><div class="wrap"><div class="stage">+<img src="${esc(imageUrl)}" alt="${t} placed in the real world" />+<div class="name">${t}${caption ? ' · ' + esc(caption).slice(0, 60) : ''}</div>+</div>+<div class="bar">+<a class="cta" href="${esc(origin)}/irl" aria-label="Place your own AI agent in augmented reality">📍 Place your own agent</a>+<a class="alt" href="${esc(origin)}/irl">What is this?</a>+</div></div></body></html>`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (req.method?.toUpperCase() !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const token = String(req.query?.token || '').trim();+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=600');++ if (!token) {+ res.statusCode = 404;+ return res.end(notFoundPage());+ }++ const [row] = await sql`+ SELECT s.image_url, p.avatar_name, p.caption, p.published, p.hidden_at+ FROM irl_pin_shares s+ JOIN irl_pins p ON p.id = s.pin_id+ WHERE s.token = ${token}+ `;++ if (!row || row.published === false || row.hidden_at) {+ res.statusCode = 404;+ return res.end(notFoundPage());+ }++ // Best-effort view counter; never blocks the render on a DB hiccup.+ recordShareView(token).catch(() => {});++ const origin = originFrom(req);+ res.statusCode = 200;+ return res.end(+ sharePage({+ imageUrl: row.image_url,+ name: row.avatar_name,+ caption: row.caption,+ pageUrl: `${origin}/irl/s/${token}`,+ origin,+ }),+ );+});diff --git a/src/irl.js b/src/irl.jsindex 584611ef5..a716fca7d 100644--- a/src/irl.js+++ b/src/irl.js@@ -2377,6 +2377,7 @@ async function savePin(lat, lng, heading = 0, caption = '', anchor = null, place};}const data = await r.json();+ if (data.pin) _lastPlacedPinId = data.pin.id;return data.pin? { ok: true, id: data.pin.id, permanent: !!data.pin.permanent }: { ok: false, error: 'error', message: saveErrorFallback() };@@ -2497,6 +2498,7 @@ async function postRoomPin({ lat, lng, heading, room, anchor, vps = null }) {updateNearbyBadge();revealMyPinsBtn();}+ _lastPlacedPinId = pin.id;return { ok: true, id: pin.id, permanent: data.pin.permanent === true };} catch {return { ok: false, error: 'network', message: saveErrorFallback('network') };@@ -3493,6 +3495,11 @@ wireShareButton($('irl-share-btn'), {getCanvas: () => canvas,getVideo: () => videoEl,getIsAR: () => arActive,+ // When the caller has an active placement, the capture is minted into a+ // permanent, unfurlable /irl/s/<token> link (api/irl/share.js) instead of a+ // bare file — the growth loop back to /irl.+ getPinId: () => _lastPlacedPinId,+ getDeviceToken: () => _deviceToken,filename: 'three-ws-irl.png',title: 'IRL · three.ws',});@@ -7117,6 +7124,9 @@ let _roomCal = null; // active one-gesture room-calibrate session, o// gold "your agent" label. The server re-checks ownership on every PATCH, so this// is convenience, not a security boundary.const _myPinIds = new Set();+// The most recently placed pin this session — what the share button turns into a+// permanent, unfurlable link (POST /api/irl/share). Null until a placement lands.+let _lastPlacedPinId = null;function isOwnPin(pin) {return _myPinIds.has(pin.id) || (gpsPin?.id != null && pin.id === gpsPin.id);}diff --git a/src/irl/share-frame.js b/src/irl/share-frame.jsindex 274ab3370..e52fc734f 100644--- a/src/irl/share-frame.js+++ b/src/irl/share-frame.js@@ -38,6 +38,53 @@ export async function captureComposite({ canvas, video, isAR }) {return await new Promise((resolve) => out.toBlob(resolve, 'image/png'));}+/**+ * Upload a captured composite to POST /api/irl/share so it becomes a permanent,+ * unfurlable link (og:image on X/Discord/iMessage) instead of a bare file that+ * dead-ends in the recipient's Photos app. Best-effort: any failure (network,+ * the pin got unpublished mid-share, rate limit) resolves to null so the caller+ * falls straight back to the plain native-file share — minting a share link is+ * a nice-to-have on top of sharing, never a blocker to it.+ *+ * @param {Blob} blob+ * @param {object} opts+ * @param {string} opts.pinId+ * @param {string} [opts.deviceToken]+ * @returns {Promise<string|null>} the permanent https://…/irl/s/<token> URL, or null+ */+export async function mintShareLink(blob, { pinId, deviceToken }) {+ if (!pinId) return null;+ try {+ const headers = { 'content-type': 'application/octet-stream' };+ if (deviceToken) headers['x-irl-device'] = deviceToken;+ const r = await fetch(`/api/irl/share?pinId=${encodeURIComponent(pinId)}`, {+ method: 'POST',+ credentials: 'include',+ headers,+ body: blob,+ });+ if (!r.ok) return null;+ const data = await r.json();+ return typeof data.url === 'string' ? data.url : null;+ } catch {+ return null;+ }+}++/** Share a URL through the native sheet, falling back to clipboard copy. */+async function shareUrlOrCopy(url, { title = 'IRL · three.ws' } = {}) {+ if (navigator.share) {+ try {+ await navigator.share({ title, url });+ return 'shared';+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ }+ }+ await navigator.clipboard.writeText(url);+ return 'copied';+}+/*** Share a blob through the native sheet, falling back to a desktop download.*@@ -81,11 +128,15 @@ function setButtonLabel(btn, text) {* @param {() => HTMLCanvasElement} opts.getCanvas* @param {() => HTMLVideoElement} [opts.getVideo]* @param {() => boolean} opts.getIsAR+ * @param {() => string|null} [opts.getPinId] the caller's currently-placed pin id, if any —+ * when present the capture is minted into a permanent share link (see mintShareLink) instead+ * of a bare file share.+ * @param {() => string|null} [opts.getDeviceToken]* @param {string} [opts.filename]* @param {string} [opts.title]* @returns {() => void} disposer*/-export function wireShareButton(btn, { getCanvas, getVideo, getIsAR, filename = 'three-ws-irl.png', title = 'IRL · three.ws' }) {+export function wireShareButton(btn, { getCanvas, getVideo, getIsAR, getPinId, getDeviceToken, filename = 'three-ws-irl.png', title = 'IRL · three.ws' }) {if (!btn) return () => {};const onClick = async () => {@@ -102,6 +153,16 @@ export function wireShareButton(btn, { getCanvas, getVideo, getIsAR, filename =isAR: !!getIsAR(),});if (blob) {+ const pinId = getPinId?.();+ if (pinId) {+ const shareUrl = await mintShareLink(blob, { pinId, deviceToken: getDeviceToken?.() });+ if (shareUrl) {+ const result = await shareUrlOrCopy(shareUrl, { title });+ setButtonLabel(btn, result === 'shared' ? 'Shared!' : 'Copied!');+ restore();+ return;+ }+ }const result = await shareOrDownload(blob, { filename, title });setButtonLabel(btn, result === 'shared' ? 'Shared!' : 'Saved!');restore();