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
a
nirholasb6e063603d1c
diff --git a/.mcp.json b/.mcp.jsonnew file mode 100644index 000000000..7c86bc33f--- /dev/null+++ b/.mcp.json@@ -0,0 +1,10 @@+{+ "mcpServers": {+ "3d-agent": {+ "url": "https://3dagent.vercel.app/api/mcp",+ "headers": {+ "Authorization": "Bearer YOUR_API_KEY_HERE"+ }+ }+ }+}\ No newline at end of filediff --git a/api/auth/logout-everywhere.js b/api/auth/logout-everywhere.jsnew file mode 100644index 000000000..0b6f7f293--- /dev/null+++ b/api/auth/logout-everywhere.js@@ -0,0 +1,34 @@+// Revoke every session for the caller, including the current one, and clear the cookie.+// Different from DELETE /api/auth/sessions (which keeps the current session):+// this fully signs the user out on every device.++import { sql } from '../_lib/db.js';+import { getSessionUser, sessionCookie } from '../_lib/auth.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthenticated', 'not signed in');++ const ip = clientIp(req);+ const rl = await limits.authIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const result = await sql`+ update sessions+ set revoked_at = now()+ where user_id = ${user.id}+ and revoked_at is null+ `;++ const clearCookies = sessionCookie('', { clear: true });+ const existing = res.getHeader('set-cookie') || [];+ const arr = Array.isArray(existing) ? existing : [existing];+ res.setHeader('set-cookie', [...arr, ...clearCookies]);++ return json(res, 200, { ok: true, revoked: result.count });+});diff --git a/api/auth/sessions/[id].js b/api/auth/sessions/[id].jsindex ca2532531..e1fd2b11c 100644--- a/api/auth/sessions/[id].js+++ b/api/auth/sessions/[id].js@@ -23,6 +23,9 @@ export default wrap(async (req, res) => {if (!rows[0]) return error(res, 404, 'not_found', 'session not found');+ if (sessionId === user.sid)+ return error(res, 409, 'cannot_revoke_current', 'use POST /api/auth/logout to end the current session');+await sql`update sessions set revoked_at = now() where id = ${sessionId}`;return json(res, 200, { revoked: 1 });});diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex 3299709d8..f3344ae7b 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -646,6 +646,7 @@type="module"src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>+ <script type="module" src="/session-client.js"></script></head><body><header>diff --git a/public/login.html b/public/login.htmlindex 72e521536..753eff11a 100644--- a/public/login.html+++ b/public/login.html@@ -5,6 +5,7 @@<meta name="viewport" content="width=device-width,initial-scale=1" /><title>Sign in · 3D Agent</title><link rel="icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/wallet-connect.css" /><meta name="privy-app-id" content="" /><style>:root {@@ -190,21 +191,7 @@</svg>Sign in with Privy</button>- <button id="wallet" type="button" class="wallet-btn">- <svg- class="wallet-icon"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- stroke-width="2"- stroke-linecap="round"- stroke-linejoin="round"- >- <rect x="2" y="6" width="20" height="14" rx="2" />- <path d="M16 12h2" />- </svg>- Sign in with MetaMask- </button>+ <div id="wallet-mount"></div><div class="err" id="err"></div><p class="foot">No account? <a href="/register">Create one</a></p></form>diff --git a/public/session-client.js b/public/session-client.jsnew file mode 100644index 000000000..e122c73cb--- /dev/null+++ b/public/session-client.js@@ -0,0 +1,114 @@+// Wallet-disconnect UX for pages where the user is already signed in.+// Listens for MetaMask accountsChanged events and shows a non-blocking toast+// prompting sign-out if the wallet that was used to SIWE-auth disconnects.+//+// Add to authenticated pages:+// <script type="module" src="/session-client.js"></script>+//+// Does NOT auto-sign-out — SIWE proved ownership at sign-in; the user may+// intentionally disconnect for privacy. The choice is always theirs.++(function initSessionClient() {+ if (!window.ethereum) return;++ // Fetch the current session address once so we can detect relevant disconnects.+ let siweAddress = null;+ fetch('/api/auth/me', { credentials: 'include' })+ .then((r) => (r.ok ? r.json() : null))+ .then((data) => {+ // me.js returns { user: { wallet_address, ... } } — use that if present.+ siweAddress = data?.user?.wallet_address?.toLowerCase() || null;+ })+ .catch(() => {});++ let toastEl = null;++ function showDisconnectToast() {+ if (toastEl) return; // already showing++ toastEl = document.createElement('div');+ toastEl.setAttribute('role', 'status');+ toastEl.setAttribute('aria-live', 'polite');+ Object.assign(toastEl.style, {+ position: 'fixed',+ bottom: '20px',+ right: '20px',+ background: '#1c1c28',+ border: '1px solid #2a2a36',+ borderRadius: '10px',+ padding: '12px 16px',+ color: '#eee',+ fontSize: '14px',+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ zIndex: '9999',+ boxShadow: '0 4px 24px rgba(0,0,0,0.5)',+ maxWidth: '340px',+ });++ const msg = document.createElement('span');+ msg.textContent = 'MetaMask disconnected — you\u2019re still signed in.';++ const signOutBtn = document.createElement('button');+ signOutBtn.textContent = 'Sign out';+ Object.assign(signOutBtn.style, {+ background: 'transparent',+ border: '1px solid #3a3a4a',+ borderRadius: '6px',+ color: '#9a8cff',+ cursor: 'pointer',+ padding: '4px 10px',+ fontSize: '13px',+ whiteSpace: 'nowrap',+ });+ signOutBtn.onclick = () => {+ fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).finally(() => {+ location.href = '/login';+ });+ };++ const dismissBtn = document.createElement('button');+ dismissBtn.textContent = '×';+ dismissBtn.setAttribute('aria-label', 'Dismiss');+ Object.assign(dismissBtn.style, {+ background: 'transparent',+ border: 'none',+ color: '#666',+ cursor: 'pointer',+ fontSize: '18px',+ padding: '0 2px',+ lineHeight: '1',+ });+ dismissBtn.onclick = () => dismissToast();++ toastEl.appendChild(msg);+ toastEl.appendChild(signOutBtn);+ toastEl.appendChild(dismissBtn);+ document.body.appendChild(toastEl);+ }++ function dismissToast() {+ if (toastEl) {+ toastEl.remove();+ toastEl = null;+ }+ }++ function onAccountsChanged(accounts) {+ if (accounts.length === 0) {+ // Wallet fully disconnected — show toast only if this session used SIWE.+ // If siweAddress is null the user logged in via email; no toast needed.+ if (siweAddress) showDisconnectToast();+ } else {+ // Wallet reconnected or account switched — dismiss any toast.+ dismissToast();+ siweAddress = accounts[0].toLowerCase();+ }+ }++ window.ethereum.on('accountsChanged', onAccountsChanged);+ window.addEventListener('pagehide', () => {+ window.ethereum?.removeListener('accountsChanged', onAccountsChanged);+ });+})();diff --git a/public/wallet-connect-demo.html b/public/wallet-connect-demo.htmlnew file mode 100644index 000000000..ea3e2f7ff--- /dev/null+++ b/public/wallet-connect-demo.html@@ -0,0 +1,115 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Wallet Connect — QA Demo</title>+ <link rel="stylesheet" href="/wallet-connect.css" />+ <style>+ :root { color-scheme: dark; }+ body {+ font: 15px/1.5 system-ui, sans-serif;+ background: #0b0b10;+ color: #eee;+ margin: 0;+ min-height: 100vh;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 32px;+ padding: 32px;+ }+ h1 { margin: 0; font-size: 20px; }+ .demo-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+ gap: 24px;+ width: 100%;+ max-width: 800px;+ }+ .demo-card {+ background: #14141c;+ border: 1px solid #22222e;+ border-radius: 12px;+ padding: 20px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ }+ .demo-card h2 { margin: 0; font-size: 14px; color: #aaa; text-transform: uppercase; letter-spacing: 0.06em; }+ .log {+ font-size: 12px;+ font-family: monospace;+ color: #666;+ min-height: 40px;+ word-break: break-all;+ }+ </style>+ </head>+ <body>+ <h1>Wallet Connect — QA Demo</h1>+ <p style="color:#666;margin:0;font-size:13px;">Manual test page — not linked from site nav.</p>++ <div class="demo-grid">+ <div class="demo-card">+ <h2>Sign in</h2>+ <div id="mount-signin"></div>+ <div class="log" id="log-signin">State: idle</div>+ </div>+ <div class="demo-card">+ <h2>Link additional wallet</h2>+ <div id="mount-link"></div>+ <div class="log" id="log-link">State: idle</div>+ </div>+ <div class="demo-card">+ <h2>Register agent (ERC-8004)</h2>+ <div id="mount-agent"></div>+ <div class="log" id="log-agent">State: idle</div>+ </div>+ </div>++ <script type="module">+ import { createConnectWalletButton } from '/wallet/connect-button.js';++ const params = new URLSearchParams(location.search);+ const next = params.get('next') || '/dashboard/';++ function wire(mountId, logId, opts) {+ const mountEl = document.getElementById(mountId);+ const logEl = document.getElementById(logId);+ const ctrl = createConnectWalletButton(mountEl, opts);+ ctrl.addEventListener('change', (e) => {+ const { status, address, error } = e.detail;+ logEl.textContent = `State: ${status}${address ? ` · ${address.slice(0,6)}…${address.slice(-4)}` : ''}${error ? ` · ${error.message}` : ''}`;+ });+ return ctrl;+ }++ wire('mount-signin', 'log-signin', {+ verifyUrl: '/api/auth/siwe/verify',+ labels: { idle: 'Connect wallet', connected: null },+ onSuccess: () => {+ document.getElementById('log-signin').textContent = 'Success — redirecting…';+ setTimeout(() => location.href = next, 800);+ },+ });++ wire('mount-link', 'log-link', {+ verifyUrl: '/api/auth/wallet/link',+ labels: { idle: 'Link wallet', signing: 'Sign to link…', success: 'Wallet linked' },+ onSuccess: () => {+ document.getElementById('log-link').textContent = 'Wallet linked successfully.';+ },+ });++ wire('mount-agent', 'log-agent', {+ verifyUrl: '/api/auth/siwe/verify',+ labels: { idle: 'Connect for ERC-8004', signing: 'Sign to register…', success: 'Ready' },+ onSuccess: () => {+ document.getElementById('log-agent').textContent = 'Connected — ready for on-chain registration.';+ },+ });+ </script>+ </body>+</html>diff --git a/public/wallet-connect.css b/public/wallet-connect.cssnew file mode 100644index 000000000..7787eb4ec--- /dev/null+++ b/public/wallet-connect.css@@ -0,0 +1,85 @@+/* Wallet connect button — scoped via .cwb-btn and [data-state] attribute. */++.cwb-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ width: 100%;+ padding: 10px 18px;+ font: inherit;+ font-size: 14px;+ font-weight: 500;+ border-radius: 8px;+ border: 1px solid #2a2a36;+ background: #1c1c28;+ color: #eee;+ cursor: pointer;+ transition: background 0.15s, border-color 0.15s, opacity 0.15s;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.cwb-btn:hover:not(:disabled) {+ background: #22222e;+ border-color: #6a5cff;+}++.cwb-btn:disabled {+ opacity: 0.6;+ cursor: not-allowed;+}++/* State variants */+.cwb-btn[data-state="connected"] {+ border-color: #2a5c2a;+ background: #141c14;+ color: #7ddf7d;+}++.cwb-btn[data-state="wrong_chain"] {+ border-color: #7a5a00;+ background: #1c1800;+ color: #f0c040;+}++.cwb-btn[data-state="error"] {+ border-color: #5c2a2a;+ background: #1c1414;+ color: #df7d7d;+}++.cwb-btn[data-state="success"] {+ border-color: #2a5c2a;+ background: #141c14;+ color: #7ddf7d;+ cursor: default;+}++.cwb-btn[data-state="no_provider"] {+ border-color: #f6851b;+ color: #f6851b;+}++.cwb-btn[data-state="no_provider"]:hover {+ background: #1c1710;+ border-color: #f6851b;+}++/* Async spinner — simple border animation */+.cwb-btn[aria-busy="true"]::before {+ content: '';+ display: inline-block;+ width: 12px;+ height: 12px;+ border: 2px solid currentColor;+ border-top-color: transparent;+ border-radius: 50%;+ animation: cwb-spin 0.7s linear infinite;+ flex-shrink: 0;+}++@keyframes cwb-spin {+ to { transform: rotate(360deg); }+}diff --git a/public/wallet-login.js b/public/wallet-login.jsindex ba7fdb5cf..07bbaf7c2 100644--- a/public/wallet-login.js+++ b/public/wallet-login.js@@ -1,40 +1,37 @@// Client-side wallet authentication.-// Used by /login and /register pages. Supports two paths:+// Used by /login page. Supports two paths:// 1. Privy — email/social/wallet login with auto-created embedded wallets-// 2. Raw MetaMask/SIWE — direct Sign-In with Ethereum for existing wallets+// 2. Raw MetaMask/SIWE — via ConnectWalletController (unified state machine)//// Loaded as a module from login.html — imports from CDN so it works outside Vite.import { BrowserProvider } from 'https://esm.sh/[email protected]';+import { createConnectWalletButton } from '/wallet/connect-button.js';const params = new URLSearchParams(location.search);const next = params.get('next') || '/dashboard/';-// Privy app id comes from /api/config (backed by PRIVY_APP_ID env var). The-// meta tag is a local-dev fallback — prod should rely on the fetched config.+// Privy app id comes from /api/config (backed by PRIVY_APP_ID env var).let PRIVY_APP_ID = document.querySelector('meta[name="privy-app-id"]')?.content || '';const configReady = fetch('/api/config', { credentials: 'omit' })- .then((r) => r.ok ? r.json() : null)+ .then((r) => (r.ok ? r.json() : null)).then((cfg) => { if (cfg?.privyAppId) PRIVY_APP_ID = cfg.privyAppId; }).catch(() => {});// ── UI helpers ──────────────────────────────────────────────────────────────function ui() {- const walletBtn = document.getElementById('wallet');- const privyBtn = document.getElementById('privy');- const err = document.getElementById('err');+ const privyBtn = document.getElementById('privy');+ const errEl = document.getElementById('err');return {- walletBtn, privyBtn, err,- setErr: (m) => { if (err) { err.textContent = m; err.style.display = 'block'; } },- clearErr: () => { if (err) { err.style.display = 'none'; } },+ privyBtn,+ errEl,+ setErr: (m) => { if (errEl) { errEl.textContent = m; errEl.style.display = 'block'; } },+ clearErr: () => { if (errEl) errEl.style.display = 'none'; },};}-// ── Privy login (primary path) ─────────────────────────────────────────────-// Privy handles email + social + wallet login. On success it provides an-// EIP-1193 provider (embedded or external) which we SIWE-verify against our-// backend exactly like a raw MetaMask login.+// ── Privy login (primary path — unchanged from original) ──────────────────async function signInWithPrivy() {const { privyBtn, setErr, clearErr } = ui();@@ -57,7 +54,7 @@ async function signInWithPrivy() {if (!eip1193) throw new Error('No wallet provider returned by Privy.');const provider = new BrowserProvider(eip1193);- await completeSignIn(provider, privyBtn);+ await completePrivySignIn(provider, privyBtn);} catch (e) {const msg = e?.message || String(e);setErr(msg === 'user rejected action' || msg.includes('cancelled') ? 'Login cancelled.' : msg);@@ -65,36 +62,9 @@ async function signInWithPrivy() {}}-// ── Raw MetaMask / SIWE (fallback path) ────────────────────────────────────--async function signInWithWallet() {- const { walletBtn, setErr, clearErr } = ui();-- if (!window.ethereum) {- setErr('No wallet detected. Install MetaMask or another Ethereum wallet.');- return;- }-- clearErr();- if (walletBtn) { walletBtn.disabled = true; walletBtn.textContent = 'Connecting…'; }- const original = walletBtn?.innerHTML;-- try {- const provider = new BrowserProvider(window.ethereum);- await provider.send('eth_requestAccounts', []);- await completeSignIn(provider, walletBtn);- } catch (e) {- const msg = e?.info?.error?.message || e?.message || String(e);- setErr(msg === 'user rejected action' ? 'Signature cancelled.' : msg);- if (walletBtn) { walletBtn.disabled = false; walletBtn.innerHTML = original; }- }-}--// ── Shared SIWE flow ───────────────────────────────────────────────────────-// Both Privy and raw wallet paths use this to complete the login.--async function completeSignIn(provider, btn) {- const signer = await provider.getSigner();+// Privy-specific SIWE completion (kept separate from the controller flow).+async function completePrivySignIn(provider, btn) {+ const signer = await provider.getSigner();const address = await signer.getAddress();const network = await provider.getNetwork();const chainId = Number(network.chainId);@@ -105,8 +75,8 @@ async function completeSignIn(provider, btn) {const { nonce, csrf } = await nonceRes.json();const domain = location.host;- const uri = location.origin;- const issuedAt = new Date().toISOString();+ const uri = location.origin;+ const issuedAt = new Date().toISOString();const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();const message = [@@ -136,14 +106,39 @@ async function completeSignIn(provider, btn) {const data = await verifyRes.json();if (!verifyRes.ok) throw new Error(data.error_description || 'Verification failed');- try { localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() })); } catch { /* ignore */ }+ try {+ localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() }));+ } catch { /* ignore */ }location.href = next;}-// ── Bind buttons ────────────────────────────────────────────────────────────+// ── Raw MetaMask / SIWE — unified controller ───────────────────────────────++const walletMount = document.getElementById('wallet-mount');+if (walletMount) {+ const { setErr, clearErr } = ui();+ const ctrl = createConnectWalletButton(walletMount, {+ verifyUrl: '/api/auth/siwe/verify',+ onSuccess: () => {+ try {+ localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() }));+ } catch { /* ignore */ }+ location.href = next;+ },+ });++ ctrl.addEventListener('change', (e) => {+ const { status, error } = e.detail;+ if (status === 'error') {+ const msg = error?.message || 'Sign in failed.';+ setErr(msg === 'user rejected action' ? 'Signature cancelled.' : msg);+ } else {+ clearErr();+ }+ });+}-const walletBtn = document.getElementById('wallet');-const privyBtn = document.getElementById('privy');+// ── Privy button ────────────────────────────────────────────────────────────-if (walletBtn) walletBtn.addEventListener('click', signInWithWallet);-if (privyBtn) privyBtn.addEventListener('click', signInWithPrivy);+const privyBtn = document.getElementById('privy');+if (privyBtn) privyBtn.addEventListener('click', signInWithPrivy);diff --git a/public/wallet/connect-button.js b/public/wallet/connect-button.jsnew file mode 100644index 000000000..7cb222b23--- /dev/null+++ b/public/wallet/connect-button.js@@ -0,0 +1,258 @@+// Unified wallet connect controller + button factory (CDN-compatible).+// Mirrors src/wallet/connect-button.js but imports ethers from esm.sh.+// Loaded as a plain ES module from public pages outside Vite bundling.++import { BrowserProvider } from 'https://esm.sh/[email protected]';+import { STATES, initialState, reduce } from './state.js';++const DEFAULT_CHAIN_IDS = [1, 8453, 10, 42161, 11155111, 84532];++const CHAIN_NAMES = {+ 1: 'Mainnet',+ 8453: 'Base',+ 10: 'Optimism',+ 42161: 'Arbitrum One',+ 11155111: 'Sepolia',+ 84532: 'Base Sepolia',+};++const ASYNC_STATES = new Set([+ STATES.DETECTING,+ STATES.REQUESTING_ACCOUNTS,+ STATES.SIGNING,+ STATES.VERIFYING,+]);++function defaultMessageBuilder(address, chainId, nonce, { domain, uri, issuedAt, expirationTime }) {+ return [+ `${domain} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Sign in to 3D Agent. This does not cost anything and proves wallet ownership.',+ '',+ `URI: ${uri}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ `Expiration Time: ${expirationTime}`,+ ].join('\n');+}++export class ConnectWalletController extends EventTarget {+ #s;+ #opts;+ #onAccountsChanged;+ #onChainChanged;++ constructor(opts = {}) {+ super();+ this.#opts = {+ allowedChainIds: DEFAULT_CHAIN_IDS,+ nonceUrl: '/api/auth/siwe/nonce',+ verifyUrl: '/api/auth/siwe/verify',+ messageBuilder: defaultMessageBuilder,+ onSuccess: null,+ autoDetect: false,+ labels: {},+ ...opts,+ };+ this.#s = initialState();++ this.#onAccountsChanged = (accounts) => this.#dispatch({ type: 'ACCOUNTS_CHANGED', accounts });+ this.#onChainChanged = (chainIdHex) => {+ const chainId = parseInt(chainIdHex, 16);+ this.#dispatch({ type: 'CHAIN_CHANGED', chainId });+ if (!this.#opts.allowedChainIds.includes(chainId)) {+ this.#dispatch({ type: 'WRONG_CHAIN' });+ } else if (this.#s.status === STATES.WRONG_CHAIN) {+ this.#dispatch({ type: 'CHAIN_OK' });+ }+ };++ if (window.ethereum) {+ window.ethereum.on('accountsChanged', this.#onAccountsChanged);+ window.ethereum.on('chainChanged', this.#onChainChanged);+ }+ }++ get state() { return this.#s.status; }+ get address() { return this.#s.address; }+ get chainId() { return this.#s.chainId; }+ get error() { return this.#s.error; }++ #dispatch(action) {+ const next = reduce(this.#s, action);+ if (next === this.#s) return;+ this.#s = next;+ this.dispatchEvent(new CustomEvent('change', { detail: { ...next } }));+ }++ async connect() {+ if (this.#s.status !== STATES.IDLE) return;+ this.#dispatch({ type: 'CONNECT' });++ if (!window.ethereum) {+ this.#dispatch({ type: 'NO_PROVIDER' });+ return;+ }+ this.#dispatch({ type: 'HAS_PROVIDER' });++ try {+ const provider = new BrowserProvider(window.ethereum);+ await provider.send('eth_requestAccounts', []);+ const signer = await provider.getSigner();+ const address = await signer.getAddress();+ const network = await provider.getNetwork();+ const chainId = Number(network.chainId);+ this.#dispatch({ type: 'ACCOUNTS_RESOLVED', address, chainId });++ if (!this.#opts.allowedChainIds.includes(chainId)) {+ this.#dispatch({ type: 'WRONG_CHAIN' });+ await this.#trySwitchChain(provider);+ }+ } catch (e) {+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });+ }+ }++ async #trySwitchChain(provider) {+ const target = this.#opts.allowedChainIds[0];+ const hex = '0x' + target.toString(16);+ try {+ await provider.send('wallet_switchEthereumChain', [{ chainId: hex }]);+ } catch (e) {+ if (e?.code === 4902) {+ this.#dispatch({+ type: 'ERROR',+ error: new Error(`Chain ${CHAIN_NAMES[target] || target} not in wallet. Add it manually.`),+ });+ } else if (e?.code !== 4001) {+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });+ }+ }+ }++ async signAndVerify() {+ if (this.#s.status !== STATES.CONNECTED && this.#s.status !== STATES.WRONG_CHAIN) return;+ this.#dispatch({ type: 'SIGN' });++ try {+ const provider = new BrowserProvider(window.ethereum);+ const signer = await provider.getSigner();+ const address = await signer.getAddress();++ const nonceRes = await fetch(this.#opts.nonceUrl, { credentials: 'include' });+ if (!nonceRes.ok) throw new Error('Failed to get nonce');+ const { nonce, csrf } = await nonceRes.json();++ const domain = location.host;+ const uri = location.origin;+ const issuedAt = new Date().toISOString();+ const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();++ const message = this.#opts.messageBuilder(address, this.#s.chainId, nonce, {+ domain,+ uri,+ issuedAt,+ expirationTime,+ });++ const signature = await signer.signMessage(message);+ this.#dispatch({ type: 'SIGNATURE_OBTAINED' });++ const verifyRes = await fetch(this.#opts.verifyUrl, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },+ body: JSON.stringify({ message, signature }),+ });+ const data = await verifyRes.json();+ if (!verifyRes.ok) throw new Error(data.error_description || 'Verification failed');++ this.#dispatch({ type: 'SUCCESS' });+ if (this.#opts.onSuccess) this.#opts.onSuccess(data);+ } catch (e) {+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });+ }+ }++ reset() { this.#dispatch({ type: 'RESET' }); }++ dispose() {+ if (window.ethereum) {+ window.ethereum.removeListener('accountsChanged', this.#onAccountsChanged);+ window.ethereum.removeListener('chainChanged', this.#onChainChanged);+ }+ }+}++const LABEL_DEFAULTS = {+ idle: 'Connect wallet',+ detecting: 'Detecting…',+ no_provider: 'Install MetaMask',+ requesting_accounts: 'Check your wallet…',+ signing: 'Sign in your wallet…',+ verifying: 'Verifying…',+ success: 'Signed in',+ error: 'Retry',+};++export function createConnectWalletButton(mountEl, opts = {}) {+ const labels = { ...LABEL_DEFAULTS, ...(opts.labels || {}) };+ const allowedChainIds = opts.allowedChainIds || DEFAULT_CHAIN_IDS;+ const ctrl = new ConnectWalletController({ ...opts, allowedChainIds });++ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'cwb-btn';++ function render(detail) {+ const s = detail.status;+ btn.setAttribute('data-state', s);+ btn.disabled = ASYNC_STATES.has(s) || s === STATES.SUCCESS;+ btn.setAttribute('aria-busy', ASYNC_STATES.has(s) ? 'true' : 'false');++ if (s === STATES.CONNECTED || s === STATES.WRONG_CHAIN) {+ const addr = detail.address || '';+ const short = addr ? addr.slice(0, 6) + '…' + addr.slice(-4) : '';+ const chainName = CHAIN_NAMES[detail.chainId] || `Chain ${detail.chainId}`;+ btn.textContent =+ s === STATES.WRONG_CHAIN+ ? `Switch to ${CHAIN_NAMES[allowedChainIds[0]] || 'Mainnet'}`+ : `${short} · ${chainName}`;+ } else if (s === STATES.ERROR) {+ btn.textContent = labels.error;+ } else {+ btn.textContent = labels[s] || s;+ }+ }++ function updateClickHandler(status) {+ btn.onclick = null;+ if (status === STATES.NO_PROVIDER) {+ btn.onclick = () => window.open('https://metamask.io', '_blank', 'noopener');+ } else if (status === STATES.CONNECTED) {+ btn.onclick = () => ctrl.signAndVerify();+ } else if (status === STATES.WRONG_CHAIN) {+ btn.onclick = () => ctrl.connect();+ } else if (status === STATES.ERROR) {+ btn.onclick = () => { ctrl.reset(); ctrl.connect(); };+ } else if (status === STATES.IDLE) {+ btn.onclick = () => ctrl.connect();+ }+ }++ ctrl.addEventListener('change', (e) => {+ render(e.detail);+ updateClickHandler(e.detail.status);+ });++ render({ status: ctrl.state, address: ctrl.address, chainId: ctrl.chainId, error: ctrl.error });+ updateClickHandler(ctrl.state);++ mountEl.innerHTML = '';+ mountEl.appendChild(btn);++ return ctrl;+}diff --git a/public/wallet/state.js b/public/wallet/state.jsnew file mode 100644index 000000000..63816be2c--- /dev/null+++ b/public/wallet/state.js@@ -0,0 +1,55 @@+// Pure state machine for the wallet connect flow (CDN-compatible, no imports).+// Kept in sync with src/wallet/state.js — no external dependencies.++export const STATES = Object.freeze({+ IDLE: 'idle',+ DETECTING: 'detecting',+ NO_PROVIDER: 'no_provider',+ REQUESTING_ACCOUNTS: 'requesting_accounts',+ CONNECTED: 'connected',+ WRONG_CHAIN: 'wrong_chain',+ SIGNING: 'signing',+ VERIFYING: 'verifying',+ SUCCESS: 'success',+ ERROR: 'error',+});++export function initialState() {+ return { status: STATES.IDLE, address: null, chainId: null, error: null };+}++export function reduce(state, action) {+ switch (action.type) {+ case 'CONNECT':+ if (state.status !== STATES.IDLE) return state;+ return { ...state, status: STATES.DETECTING, error: null };+ case 'NO_PROVIDER':+ return { ...state, status: STATES.NO_PROVIDER };+ case 'HAS_PROVIDER':+ return { ...state, status: STATES.REQUESTING_ACCOUNTS };+ case 'ACCOUNTS_RESOLVED':+ return { ...state, status: STATES.CONNECTED, address: action.address, chainId: action.chainId };+ case 'WRONG_CHAIN':+ return { ...state, status: STATES.WRONG_CHAIN };+ case 'CHAIN_OK':+ return { ...state, status: STATES.CONNECTED };+ case 'SIGN':+ if (state.status !== STATES.CONNECTED && state.status !== STATES.WRONG_CHAIN) return state;+ return { ...state, status: STATES.SIGNING };+ case 'SIGNATURE_OBTAINED':+ return { ...state, status: STATES.VERIFYING };+ case 'SUCCESS':+ return { ...state, status: STATES.SUCCESS };+ case 'ERROR':+ return { ...state, status: STATES.ERROR, error: action.error ?? null };+ case 'RESET':+ return initialState();+ case 'ACCOUNTS_CHANGED':+ if (!action.accounts || action.accounts.length === 0) return initialState();+ return { ...state, address: action.accounts[0], chainId: state.chainId, status: STATES.CONNECTED };+ case 'CHAIN_CHANGED':+ return { ...state, chainId: action.chainId };+ default:+ return state;+ }+}diff --git a/src/element.js b/src/element.jsindex a60a9dfc5..00c33b632 100644--- a/src/element.js+++ b/src/element.js@@ -947,9 +947,10 @@ class Agent3DElement extends HTMLElement {return this._runtime.send(text, { voice: opts.voice ?? this.hasAttribute('voice') });}- // Emit speak directly on the protocol bus — triggers avatar animation without going through LLM.+ // Play talk animation directly via the scene — bypasses LLM, works in embedded context.speak(text, opts = {}) {- protocol.emit(ACTION_TYPES.SPEAK, { text, sentiment: opts.sentiment ?? 0 });+ const duration = Math.max(1.5, (text?.split(' ').length ?? 3) * 0.3);+ this._scene?.playAnimationByHint?.('talk', { duration });}async ask(text, opts = {}) {diff --git a/src/wallet/connect-button.js b/src/wallet/connect-button.jsnew file mode 100644index 000000000..5bbb2b0cc--- /dev/null+++ b/src/wallet/connect-button.js@@ -0,0 +1,322 @@+/**+ * Unified wallet connect controller + button factory.+ *+ * Usage (Vite-bundled apps):+ * import { createConnectWalletButton } from './wallet/connect-button.js';+ * const ctrl = createConnectWalletButton(mountEl, { onSuccess: (data) => ... });+ */++import { BrowserProvider } from 'ethers';+import { STATES, initialState, reduce } from './state.js';++/** Chain IDs that match known ERC-8004 registry deployments. */+const DEFAULT_CHAIN_IDS = [1, 8453, 10, 42161, 11155111, 84532];++const CHAIN_NAMES = {+ 1: 'Mainnet',+ 8453: 'Base',+ 10: 'Optimism',+ 42161: 'Arbitrum One',+ 11155111: 'Sepolia',+ 84532: 'Base Sepolia',+};++const ASYNC_STATES = new Set([+ STATES.DETECTING,+ STATES.REQUESTING_ACCOUNTS,+ STATES.SIGNING,+ STATES.VERIFYING,+]);++/**+ * Build the EIP-4361 SIWE message string.+ * Format must match the parser in api/auth/siwe/verify.js exactly.+ *+ * @param {string} address checksummed Ethereum address+ * @param {number} chainId+ * @param {string} nonce+ * @param {{ domain: string, uri: string, issuedAt: string, expirationTime: string }} ctx+ * @returns {string}+ */+function defaultMessageBuilder(address, chainId, nonce, { domain, uri, issuedAt, expirationTime }) {+ return [+ `${domain} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Sign in to 3D Agent. This does not cost anything and proves wallet ownership.',+ '',+ `URI: ${uri}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ `Expiration Time: ${expirationTime}`,+ ].join('\n');+}++/**+ * Headless state machine for wallet connect / SIWE.+ * Emits `change` CustomEvents on state transitions.+ *+ * @fires ConnectWalletController#change+ */+export class ConnectWalletController extends EventTarget {+ /** @type {import('./state.js').ConnectState} */+ #s;+ #opts;+ #onAccountsChanged;+ #onChainChanged;++ /**+ * @param {{+ * allowedChainIds?: number[],+ * nonceUrl?: string,+ * verifyUrl?: string,+ * messageBuilder?: Function,+ * onSuccess?: Function,+ * autoDetect?: boolean,+ * labels?: Record<string, string>,+ * }} [opts]+ */+ constructor(opts = {}) {+ super();+ this.#opts = {+ allowedChainIds: DEFAULT_CHAIN_IDS,+ nonceUrl: '/api/auth/siwe/nonce',+ verifyUrl: '/api/auth/siwe/verify',+ messageBuilder: defaultMessageBuilder,+ onSuccess: null,+ autoDetect: false,+ labels: {},+ ...opts,+ };+ this.#s = initialState();++ this.#onAccountsChanged = (accounts) => this.#dispatch({ type: 'ACCOUNTS_CHANGED', accounts });+ this.#onChainChanged = (chainIdHex) => {+ const chainId = parseInt(chainIdHex, 16);+ this.#dispatch({ type: 'CHAIN_CHANGED', chainId });+ if (!this.#opts.allowedChainIds.includes(chainId)) {+ this.#dispatch({ type: 'WRONG_CHAIN' });+ } else if (this.#s.status === STATES.WRONG_CHAIN) {+ this.#dispatch({ type: 'CHAIN_OK' });+ }+ };++ if (window.ethereum) {+ window.ethereum.on('accountsChanged', this.#onAccountsChanged);+ window.ethereum.on('chainChanged', this.#onChainChanged);+ }+ }++ get state() { return this.#s.status; }+ get address() { return this.#s.address; }+ get chainId() { return this.#s.chainId; }+ get error() { return this.#s.error; }++ /** @param {{ type: string, [k: string]: any }} action */+ #dispatch(action) {+ const next = reduce(this.#s, action);+ if (next === this.#s) return;+ this.#s = next;+ this.dispatchEvent(new CustomEvent('change', { detail: { ...next } }));+ }++ /** Initiate the connect flow from `idle`. Idempotent if already past idle. */+ async connect() {+ if (this.#s.status !== STATES.IDLE) return;+ this.#dispatch({ type: 'CONNECT' });++ if (!window.ethereum) {+ this.#dispatch({ type: 'NO_PROVIDER' });+ return;+ }+ this.#dispatch({ type: 'HAS_PROVIDER' });++ try {+ const provider = new BrowserProvider(window.ethereum);+ await provider.send('eth_requestAccounts', []);+ const signer = await provider.getSigner();+ const address = await signer.getAddress();+ const network = await provider.getNetwork();+ const chainId = Number(network.chainId);+ this.#dispatch({ type: 'ACCOUNTS_RESOLVED', address, chainId });++ if (!this.#opts.allowedChainIds.includes(chainId)) {+ this.#dispatch({ type: 'WRONG_CHAIN' });+ await this.#trySwitchChain(provider);+ }+ } catch (e) {+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });+ }+ }++ /** Attempt to switch to the first allowed chain via wallet_switchEthereumChain. */+ async #trySwitchChain(provider) {+ const target = this.#opts.allowedChainIds[0];+ const hex = '0x' + target.toString(16);+ try {+ await provider.send('wallet_switchEthereumChain', [{ chainId: hex }]);+ // chainChanged event fires and handles the CHAIN_OK dispatch.+ } catch (e) {+ if (e?.code === 4902) {+ this.#dispatch({+ type: 'ERROR',+ error: new Error(+ `Chain ${CHAIN_NAMES[target] || target} is not in your wallet. Add it manually.`,+ ),+ });+ } else if (e?.code !== 4001) {+ // 4001 = user rejected — surface as error; other codes are bugs+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });+ }+ }+ }++ /** Sign a SIWE message and verify with the backend. Call from `connected` state. */+ async signAndVerify() {+ if (this.#s.status !== STATES.CONNECTED && this.#s.status !== STATES.WRONG_CHAIN) return;+ this.#dispatch({ type: 'SIGN' });++ try {+ const provider = new BrowserProvider(window.ethereum);+ const signer = await provider.getSigner();+ const address = await signer.getAddress();++ const nonceRes = await fetch(this.#opts.nonceUrl, { credentials: 'include' });+ if (!nonceRes.ok) throw new Error('Failed to get nonce');+ const { nonce, csrf } = await nonceRes.json();++ const domain = location.host;+ const uri = location.origin;+ const issuedAt = new Date().toISOString();+ const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();++ const message = this.#opts.messageBuilder(address, this.#s.chainId, nonce, {+ domain,+ uri,+ issuedAt,+ expirationTime,+ });++ const signature = await signer.signMessage(message);+ this.#dispatch({ type: 'SIGNATURE_OBTAINED' });++ const verifyRes = await fetch(this.#opts.verifyUrl, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },+ body: JSON.stringify({ message, signature }),+ });+ const data = await verifyRes.json();+ if (!verifyRes.ok) throw new Error(data.error_description || 'Verification failed');++ this.#dispatch({ type: 'SUCCESS' });+ if (this.#opts.onSuccess) this.#opts.onSuccess(data);+ } catch (e) {+ this.#dispatch({ type: 'ERROR', error: e instanceof Error ? e : new Error(String(e)) });+ }+ }++ /** Return to `idle` state, clearing any error. */+ reset() {+ this.#dispatch({ type: 'RESET' });+ }++ /** Remove all event listeners. Call when unmounting in SPA contexts. */+ dispose() {+ if (window.ethereum) {+ window.ethereum.removeListener('accountsChanged', this.#onAccountsChanged);+ window.ethereum.removeListener('chainChanged', this.#onChainChanged);+ }+ }+}++const LABEL_DEFAULTS = {+ idle: 'Connect wallet',+ detecting: 'Detecting…',+ no_provider: 'Install MetaMask',+ requesting_accounts: 'Check your wallet…',+ signing: 'Sign in your wallet…',+ verifying: 'Verifying…',+ success: 'Signed in',+ error: 'Retry',+};++/**+ * Mount a wallet connect button into `mountEl`.+ * The element's contents are replaced with a single `<button class="cwb-btn">`.+ *+ * @param {HTMLElement} mountEl+ * @param {{+ * allowedChainIds?: number[],+ * nonceUrl?: string,+ * verifyUrl?: string,+ * messageBuilder?: Function,+ * onSuccess?: Function,+ * labels?: Record<string, string>,+ * }} [opts]+ * @returns {ConnectWalletController}+ */+export function createConnectWalletButton(mountEl, opts = {}) {+ const labels = { ...LABEL_DEFAULTS, ...(opts.labels || {}) };+ const allowedChainIds = opts.allowedChainIds || DEFAULT_CHAIN_IDS;+ const ctrl = new ConnectWalletController({ ...opts, allowedChainIds });++ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'cwb-btn';++ function render(detail) {+ const s = detail.status;+ btn.setAttribute('data-state', s);+ btn.disabled = ASYNC_STATES.has(s) || s === STATES.SUCCESS;+ btn.setAttribute('aria-busy', ASYNC_STATES.has(s) ? 'true' : 'false');++ if (s === STATES.CONNECTED || s === STATES.WRONG_CHAIN) {+ const addr = detail.address || '';+ const short = addr ? addr.slice(0, 6) + '…' + addr.slice(-4) : '';+ const chainName = CHAIN_NAMES[detail.chainId] || `Chain ${detail.chainId}`;+ btn.textContent =+ s === STATES.WRONG_CHAIN+ ? `Switch to ${CHAIN_NAMES[allowedChainIds[0]] || 'Mainnet'}`+ : `${short} · ${chainName}`;+ } else if (s === STATES.ERROR) {+ btn.textContent = labels.error;+ } else {+ btn.textContent = labels[s] || s;+ }+ }++ function updateClickHandler(status) {+ btn.onclick = null;+ if (status === STATES.NO_PROVIDER) {+ btn.onclick = () => window.open('https://metamask.io', '_blank', 'noopener');+ } else if (status === STATES.CONNECTED) {+ btn.onclick = () => ctrl.signAndVerify();+ } else if (status === STATES.WRONG_CHAIN) {+ btn.onclick = () => ctrl.connect();+ } else if (status === STATES.ERROR) {+ btn.onclick = () => {+ ctrl.reset();+ ctrl.connect();+ };+ } else if (status === STATES.IDLE) {+ btn.onclick = () => ctrl.connect();+ }+ }++ ctrl.addEventListener('change', (e) => {+ render(e.detail);+ updateClickHandler(e.detail.status);+ });++ // Initial render from current state.+ render({ status: ctrl.state, address: ctrl.address, chainId: ctrl.chainId, error: ctrl.error });+ updateClickHandler(ctrl.state);++ mountEl.innerHTML = '';+ mountEl.appendChild(btn);++ return ctrl;+}diff --git a/src/wallet/state.js b/src/wallet/state.jsnew file mode 100644index 000000000..6130989eb--- /dev/null+++ b/src/wallet/state.js@@ -0,0 +1,69 @@+/**+ * Pure state machine for the wallet connect flow.+ * No side effects — suitable for unit testing.+ */++/** @enum {string} */+export const STATES = Object.freeze({+ IDLE: 'idle',+ DETECTING: 'detecting',+ NO_PROVIDER: 'no_provider',+ REQUESTING_ACCOUNTS: 'requesting_accounts',+ CONNECTED: 'connected',+ WRONG_CHAIN: 'wrong_chain',+ SIGNING: 'signing',+ VERIFYING: 'verifying',+ SUCCESS: 'success',+ ERROR: 'error',+});++/**+ * @typedef {{ status: string, address: string|null, chainId: number|null, error: Error|null }} ConnectState+ */++/** @returns {ConnectState} */+export function initialState() {+ return { status: STATES.IDLE, address: null, chainId: null, error: null };+}++/**+ * Pure reducer — given a state and an action, return the next state.+ * @param {ConnectState} state+ * @param {{ type: string, [k: string]: any }} action+ * @returns {ConnectState}+ */+export function reduce(state, action) {+ switch (action.type) {+ case 'CONNECT':+ if (state.status !== STATES.IDLE) return state;+ return { ...state, status: STATES.DETECTING, error: null };+ case 'NO_PROVIDER':+ return { ...state, status: STATES.NO_PROVIDER };+ case 'HAS_PROVIDER':+ return { ...state, status: STATES.REQUESTING_ACCOUNTS };+ case 'ACCOUNTS_RESOLVED':+ return { ...state, status: STATES.CONNECTED, address: action.address, chainId: action.chainId };+ case 'WRONG_CHAIN':+ return { ...state, status: STATES.WRONG_CHAIN };+ case 'CHAIN_OK':+ return { ...state, status: STATES.CONNECTED };+ case 'SIGN':+ if (state.status !== STATES.CONNECTED && state.status !== STATES.WRONG_CHAIN) return state;+ return { ...state, status: STATES.SIGNING };+ case 'SIGNATURE_OBTAINED':+ return { ...state, status: STATES.VERIFYING };+ case 'SUCCESS':+ return { ...state, status: STATES.SUCCESS };+ case 'ERROR':+ return { ...state, status: STATES.ERROR, error: action.error ?? null };+ case 'RESET':+ return initialState();+ case 'ACCOUNTS_CHANGED':+ if (!action.accounts || action.accounts.length === 0) return initialState();+ return { ...state, address: action.accounts[0], chainId: state.chainId, status: STATES.CONNECTED };+ case 'CHAIN_CHANGED':+ return { ...state, chainId: action.chainId };+ default:+ return state;+ }+}diff --git a/vercel.json b/vercel.jsonindex 8e60218c8..3a329c677 100644--- a/vercel.json+++ b/vercel.json@@ -98,6 +98,8 @@{ "src": "/lobehub/iframe/", "dest": "/public/lobehub/iframe/index.html" },{ "src": "/lobehub/iframe/(.*)", "dest": "/public/lobehub/iframe/$1" },+ { "src": "/api/auth/logout-everywhere", "dest": "/api/auth/logout-everywhere" },+{ "src": "/api/llm/anthropic", "dest": "/api/llm/anthropic.js" },{ "src": "/api/agents/([^/]+)/usage", "dest": "/api/agents/[id]/usage?id=$1" },{ "src": "/dashboard/usage", "dest": "/public/dashboard/usage.html" },