Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix: change error logging to console.log for better visibility in index-delegations

nirholasbec89922407a
diff --git a/api/auth/wallets/index.js b/api/auth/wallets/index.js
index 1731d2588..d2e442132 100644
--- a/api/auth/wallets/index.js
+++ b/api/auth/wallets/index.js
@@ -6,13 +6,13 @@ import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { parse } from '../../_lib/validate.js';
+import { parseSiweMessage } from '../../_lib/siwe.js';
+import { env } from '../../_lib/env.js';
import { consumeNonce } from './_link-nonces.js';
const linkBody = z.object({
- address: z.string().regex(/^0x[a-fA-F0-9]{40}$/i),
message: z.string().min(64).max(4000),
signature: z.string().regex(/^0x[a-fA-F0-9]+$/),
- nonce: z.string().min(8).max(32),
});
export default wrap(async (req, res) => {
@@ -49,43 +49,78 @@ async function handleListWallets(userId, res) {
async function handleLinkWallet(userId, req, res) {
const body = parse(linkBody, await readJson(req));
- // 1. Verify nonce exists and is not expired.
- const nonceData = consumeNonce(body.nonce, userId);
+ // 1. Parse SIWE message.
+ const fields = parseSiweMessage(body.message);
+ if (!fields) return error(res, 400, 'invalid_message', 'malformed SIWE message');
+
+ // 2. Domain + URI must match this deployment.
+ const appOrigin = env.APP_ORIGIN;
+ const appHost = new URL(appOrigin).host;
+ const vercelHost = process.env.VERCEL_URL || null;
+ const isLocalDev =
+ process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';
+ const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));
+ const domainOk =
+ allowedHosts.has(fields.domain) || (isLocalDev && /^localhost(:\d+)?$/.test(fields.domain));
+ if (!domainOk) return error(res, 400, 'invalid_domain', `domain must be ${appHost}`);
+ try {
+ const u = new URL(fields.uri);
+ const allowedOrigins = new Set(
+ [appOrigin, vercelHost ? `https://${vercelHost}` : null].filter(Boolean),
+ );
+ const originOk =
+ allowedOrigins.has(u.origin) ||
+ (isLocalDev && /^https?:\/\/localhost(:\d+)?$/.test(u.origin));
+ if (!originOk) return error(res, 400, 'invalid_uri', 'uri origin mismatch');
+ } catch {
+ return error(res, 400, 'invalid_uri', 'uri not a valid URL');
+ }
+
+ // 3. Temporal checks.
+ const now = Date.now();
+ if (fields.expirationTime && Date.parse(fields.expirationTime) < now) {
+ return error(res, 400, 'expired', 'message expired');
+ }
+ if (fields.notBefore && Date.parse(fields.notBefore) > now) {
+ return error(res, 400, 'not_yet_valid', 'message not yet valid');
+ }
+
+ // 4. Verify nonce was issued to this user and burn it.
+ const nonceData = consumeNonce(fields.nonce, userId);
if (!nonceData) {
return error(res, 400, 'invalid_nonce', 'unknown, expired, or invalid nonce');
}
- // 2. Verify signature recovers the claimed address.
+ // 5. Verify signature recovers the address claimed in the message.
let recovered;
try {
recovered = verifyMessage(body.message, body.signature);
} catch {
return error(res, 401, 'invalid_signature', 'signature verification failed');
}
-
let claimed;
try {
- claimed = getAddress(body.address);
+ claimed = getAddress(fields.address);
} catch {
return error(res, 400, 'invalid_address', 'address not checksummed correctly');
}
-
if (recovered.toLowerCase() !== claimed.toLowerCase()) {
return error(res, 401, 'invalid_signature', 'signer does not match address');
}
const addrLower = claimed.toLowerCase();
+ const chainId = fields.chainId || null;
- // 3. Check if this address is already linked to this user (idempotent).
+ // 6. Check if this address is already linked to this user (idempotent).
const existing = await sql`
select id from user_wallets
where user_id = ${userId} and address = ${addrLower}
`;
if (existing.length > 0) {
- return json(res, 200, { wallet: { address: claimed, chain_id: null } });
+ return json(res, 200, { wallet: { address: claimed, chain_id: chainId } });
}
- // 4. Check if this address is already linked to a different user.
+ // 7. Check if this address is already linked to a different user.
const conflict = await sql`
select user_id from user_wallets
where address = ${addrLower}
@@ -99,11 +134,11 @@ async function handleLinkWallet(userId, req, res) {
);
}
- // 5. Insert the new wallet.
+ // 8. Insert the new wallet.
await sql`
insert into user_wallets (user_id, address, chain_id, is_primary)
- values (${userId}, ${addrLower}, null, false)
+ values (${userId}, ${addrLower}, ${chainId}, false)
`;
- return json(res, 201, { wallet: { address: claimed, chain_id: null } });
+ return json(res, 201, { wallet: { address: claimed, chain_id: chainId } });
}
diff --git a/api/auth/wallets/nonce.js b/api/auth/wallets/nonce.js
index 4183c8499..69e1ad67b 100644
--- a/api/auth/wallets/nonce.js
+++ b/api/auth/wallets/nonce.js
@@ -1,10 +1,19 @@
-// Issue a nonce for wallet linking (authenticated user only).
-// Different from login nonce: caller is already authenticated.
+// Issue a nonce + EIP-4361 (SIWE) message for wallet linking.
+// Caller must already be authenticated; the resulting message ties the wallet
+// signature to the active session's user.
+import { z } from 'zod';
import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { parse } from '../../_lib/validate.js';
+import { env } from '../../_lib/env.js';
import { issueNonce, NONCE_TTL_SEC } from './_link-nonces.js';
+const nonceBody = z.object({
+ address: z.string().regex(/^0x[a-fA-F0-9]{40}$/),
+ chainId: z.number().int().positive(),
+});
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
@@ -12,21 +21,27 @@ export default wrap(async (req, res) => {
const session = await getSessionUser(req);
if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+ const { address, chainId } = parse(nonceBody, await readJson(req));
+
const nonce = issueNonce(session.id);
- // Generate SIWE-like message for signing.
+ const appOrigin = env.APP_ORIGIN;
+ const domain = new URL(appOrigin).host;
+ const issuedAt = new Date().toISOString();
+ const expirationTime = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();
+
const message = [
- `three.ws wants you to sign in with your Ethereum account:`,
- `Address to link (will be filled by wallet):`,
+ `${domain} wants you to sign in with your Ethereum account:`,
+ address,
``,
`Link this wallet to three.ws account ${session.email}`,
``,
- `URI: ${process.env.APP_ORIGIN || 'https://three.ws/'}`,
+ `URI: ${appOrigin}`,
`Version: 1`,
- `Chain ID: (will be set by wallet)`,
+ `Chain ID: ${chainId}`,
`Nonce: ${nonce}`,
- `Issued At: ${new Date().toISOString()}`,
- `Expiration Time: ${new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString()}`,
+ `Issued At: ${issuedAt}`,
+ `Expiration Time: ${expirationTime}`,
].join('\n');
return json(res, 200, { nonce, message, ttl: NONCE_TTL_SEC });
diff --git a/api/cron/index-delegations.js b/api/cron/index-delegations.js
index 10c088a2c..38f489490 100644
--- a/api/cron/index-delegations.js
+++ b/api/cron/index-delegations.js
@@ -100,7 +100,7 @@ export default wrap(async (req, res) => {
const r = await indexChain(chainId, contract);
const summary = { chainId, ...r, elapsedMs: Date.now() - t0 };
report.chains.push(summary);
- console.error(JSON.stringify({ stage: 'index-delegations', ...summary }));
+ console.log(JSON.stringify({ stage: 'index-delegations', ...summary }));
} catch (err) {
const entry = { chainId, error: err.message || String(err) };
report.errors.push(entry);
diff --git a/public/dashboard/wallets.html b/public/dashboard/wallets.html
index cfebb100a..eaf8a69e2 100644
--- a/public/dashboard/wallets.html
+++ b/public/dashboard/wallets.html
@@ -342,19 +342,23 @@
}
try {
- // 1. Request accounts from MetaMask
+ // 1. Request accounts + chain from MetaMask
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts',
});
const address = accounts[0];
+ const chainIdHex = await window.ethereum.request({ method: 'eth_chainId' });
+ const chainId = parseInt(chainIdHex, 16);
- // 2. Get nonce from server
+ // 2. Get SIWE message + nonce from server (bound to this address + chain)
const nonceRes = await fetch(`${apiUrl}/auth/wallets/nonce`, {
method: 'POST',
credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ address, chainId }),
});
if (!nonceRes.ok) throw new Error('Failed to get nonce');
- const { nonce, message } = await nonceRes.json();
+ const { message } = await nonceRes.json();
// 3. Sign message with MetaMask
let signature;
@@ -372,12 +376,12 @@
return;
}
- // 4. Send signature to server
+ // 4. Send signed message to server
const linkRes = await fetch(`${apiUrl}/auth/wallets`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ address, message, signature, nonce }),
+ body: JSON.stringify({ message, signature }),
});
if (!linkRes.ok) {
const err = await linkRes.json();