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.

feat: Privy auth integration (JWKS verify, DID linking, login UI)

nirholas6c443fe55171
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index ffb0cd326..899d31b81 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -1,7 +1,7 @@
// Auth primitives: password hashing, JWTs, session cookies, bearer extraction.
import bcrypt from 'bcryptjs';
-import { SignJWT, jwtVerify } from 'jose';
+import { SignJWT, jwtVerify, createRemoteJWKSet } from 'jose';
import { env } from './env.js';
import { sql } from './db.js';
import { logAudit } from './audit.js';
@@ -304,6 +304,62 @@ export async function authenticateBearer(token, { audience } = {}) {
}
}
+// ── Privy token verification (JWKS) ─────────────────────────────────────────
+// Lazy singleton — the JWKS set caches the remote keyset and handles rotation
+// automatically; it is only created on first call so imports don't fail when
+// PRIVY_APP_ID is unset in environments that don't use Privy.
+let _privyJWKS;
+function privyJWKS() {
+ if (!_privyJWKS) {
+ const endpoint = env.PRIVY_JWKS_ENDPOINT;
+ if (!endpoint) throw new Error('Missing required env var: PRIVY_JWKS_ENDPOINT (or VITE_PRIVY_APP_ID)');
+ // cooldownDuration throttles refetches when an unknown `kid` is seen
+ // (rotation), so a burst of requests during a key rotation triggers at
+ // most one upstream fetch instead of one per request.
+ _privyJWKS = createRemoteJWKSet(new URL(endpoint), { cooldownDuration: 30_000 });
+ }
+ return _privyJWKS;
+}
+
+// Verify a Privy access token issued by the Privy auth service.
+// Returns the JWT payload on success; throws on invalid/expired tokens.
+// payload.sub is the user's Privy DID (e.g. "did:privy:clxxx...").
+// clockTolerance absorbs small skew between Privy's clock and ours so a freshly
+// minted token isn't rejected as "not yet valid".
+export async function verifyPrivyToken(token) {
+ if (!token) throw new Error('missing token');
+ const { payload } = await jwtVerify(token, privyJWKS(), {
+ issuer: 'privy.io',
+ audience: env.PRIVY_APP_ID,
+ clockTolerance: 30,
+ });
+ return payload;
+}
+
+// Privy sends its access token as the `privy-id-token` header, an
+// Authorization: Bearer, or the `privy-token` cookie (in that preference order).
+// Returns the raw token string or null.
+export function extractPrivyToken(req) {
+ const header = req.headers['privy-id-token'];
+ if (header) return Array.isArray(header) ? header[0] : header;
+ const bearer = extractBearer(req);
+ if (bearer) return bearer;
+ const cookie = req.headers.cookie || '';
+ const m = cookie.match(/(?:^|;\s*)privy-token=([^;]+)/);
+ return m ? decodeURIComponent(m[1]) : null;
+}
+
+// Non-throwing resolver mirroring authenticateBearer(): verifies the request's
+// Privy token and returns the payload, or null on any failure. Use this in
+// route handlers that want "authenticated or not" without try/catch.
+export async function authenticatePrivy(req) {
+ try {
+ return await verifyPrivyToken(extractPrivyToken(req));
+ } catch {
+ return null;
+ }
+}
+
export function hasScope(granted, required) {
const g = new Set((granted || '').split(/\s+/).filter(Boolean));
return required.split(/\s+/).every((s) => g.has(s));
diff --git a/api/_lib/env.js b/api/_lib/env.js
index dc44eebf3..245c1b851 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -627,6 +627,23 @@ export const env = {
return opt('BUBBLEGUM_TREE_AUTHORITY');
},
+ // Privy — embedded wallet + social auth. App ID is public (used on the frontend);
+ // app secret is server-only. JWKS endpoint is derived from the app ID by default.
+ get PRIVY_APP_ID() {
+ return opt('VITE_PRIVY_APP_ID') || opt('PRIVY_APP_ID');
+ },
+ get PRIVY_APP_SECRET() {
+ return opt('PRIVY_APP_SECRET');
+ },
+ get PRIVY_JWKS_ENDPOINT() {
+ return opt(
+ 'PRIVY_JWKS_ENDPOINT',
+ this.PRIVY_APP_ID
+ ? `https://auth.privy.io/api/v1/apps/${this.PRIVY_APP_ID}/jwks.json`
+ : undefined,
+ );
+ },
+
// GitHub OAuth — social memory seeding. When unset, /api/auth/github/connect returns 501.
get GITHUB_OAUTH_CLIENT_ID() {
return opt('GITHUB_OAUTH_CLIENT_ID');
diff --git a/api/_lib/migrations/20260605150000_users_privy_did.sql b/api/_lib/migrations/20260605150000_users_privy_did.sql
new file mode 100644
index 000000000..b6f540c06
--- /dev/null
+++ b/api/_lib/migrations/20260605150000_users_privy_did.sql
@@ -0,0 +1,14 @@
+-- Durable Privy identity link.
+--
+-- Until now the Privy login flow (api/auth/privy/verify.js) located returning
+-- users by a synthetic email of the shape `privy-<did>@privy.local`. That made
+-- the DID a string baked into an email column — impossible to query directly,
+-- and brittle once a user also has a real email on the row.
+--
+-- privy_did stores the Privy DID (`did:privy:…`) as a first-class, unique key so
+-- a returning user is resolved by exact DID match regardless of their email, and
+-- an existing email/password user can link their Privy account without spawning
+-- a duplicate row. Partial unique index allows many NULLs (non-Privy users).
+alter table users add column if not exists privy_did text;
+create unique index if not exists users_privy_did_unique
+ on users(privy_did) where privy_did is not null;
diff --git a/api/_lib/privy.js b/api/_lib/privy.js
new file mode 100644
index 000000000..cf02bfab0
--- /dev/null
+++ b/api/_lib/privy.js
@@ -0,0 +1,99 @@
+// Privy server-side REST client.
+//
+// The Privy *access token* (verified in auth.js#verifyPrivyToken) carries identity
+// — `sub` is the user's DID — but it does NOT reliably include the user's linked
+// accounts (email, embedded wallets). Those live in the Privy user object, which
+// is fetched server-side with the app secret. This module is that fetch.
+//
+// Auth: HTTP Basic with `app_id:app_secret`, plus a `privy-app-id` header, per
+// https://docs.privy.io/reference/sdk/server-auth . When the secret is unset the
+// helpers return null so callers degrade to whatever the token alone provides.
+
+import { env } from './env.js';
+
+const PRIVY_API_BASE = 'https://auth.privy.io/api/v1';
+
+function authHeaders() {
+ const appId = env.PRIVY_APP_ID;
+ const secret = env.PRIVY_APP_SECRET;
+ if (!appId || !secret) return null;
+ const basic = Buffer.from(`${appId}:${secret}`).toString('base64');
+ return {
+ Authorization: `Basic ${basic}`,
+ 'privy-app-id': appId,
+ 'Content-Type': 'application/json',
+ };
+}
+
+/**
+ * Fetch the full Privy user object by DID. Returns the parsed user (including
+ * `linked_accounts`) or null when Privy is unconfigured or the lookup fails.
+ * @param {string} did e.g. "did:privy:clxxx..."
+ */
+export async function fetchPrivyUser(did) {
+ const headers = authHeaders();
+ if (!headers || !did) return null;
+ const res = await fetch(`${PRIVY_API_BASE}/users/${encodeURIComponent(did)}`, { headers });
+ if (!res.ok) return null;
+ return res.json();
+}
+
+// Privy tags every linked account with a `type`. Map the wallet ones to our
+// user_wallets.chain_type domain ('evm' | 'solana'); ignore the rest.
+function walletChainType(account) {
+ // Embedded + external wallets expose `chain_type` ('ethereum' | 'solana').
+ const ct = account.chain_type || account.chainType;
+ if (ct === 'solana') return 'solana';
+ if (ct === 'ethereum') return 'evm';
+ // Older payloads omit chain_type; infer from address shape (0x = EVM).
+ if (typeof account.address === 'string') {
+ return account.address.startsWith('0x') ? 'evm' : 'solana';
+ }
+ return null;
+}
+
+/**
+ * Normalize a Privy user's linked accounts into the bits we persist.
+ * Accepts either a fetched user object or a token payload carrying
+ * `linked_accounts`, so callers can pass whichever they have.
+ * @returns {{ email: string|null, wallets: Array<{address:string, chainType:string}> }}
+ */
+export function extractIdentity(privyUserOrPayload) {
+ const accounts = Array.isArray(privyUserOrPayload?.linked_accounts)
+ ? privyUserOrPayload.linked_accounts
+ : [];
+
+ const emailAccount = accounts.find(
+ (a) =>
+ a.type === 'email' ||
+ a.type === 'google_oauth' ||
+ a.type === 'twitter_oauth' ||
+ a.type === 'github_oauth',
+ );
+ const email = emailAccount?.address || emailAccount?.email || null;
+
+ const wallets = [];
+ for (const a of accounts) {
+ if (a.type !== 'wallet' && a.type !== 'smart_wallet') continue;
+ if (!a.address) continue;
+ const chainType = walletChainType(a);
+ if (!chainType) continue;
+ // EVM addresses are case-insensitive — lowercase to match the unique index;
+ // Solana base58 is case-sensitive, so leave it untouched.
+ const address = chainType === 'evm' ? a.address.toLowerCase() : a.address;
+ wallets.push({ address, chainType });
+ }
+ return { email, wallets };
+}
+
+/**
+ * Resolve a Privy user's linked wallets by DID via the server API. Falls back to
+ * whatever the token payload carried when the API is unconfigured/unavailable.
+ * @param {string} did
+ * @param {object} [tokenPayload] the verified access-token payload (optional)
+ */
+export async function fetchPrivyWallets(did, tokenPayload) {
+ const user = await fetchPrivyUser(did);
+ if (user) return extractIdentity(user).wallets;
+ return tokenPayload ? extractIdentity(tokenPayload).wallets : [];
+}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 23d40ea13..30ba25878 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -25,8 +25,10 @@ create table if not exists users (
alter table users add column if not exists wallet_address text;
alter table users add column if not exists is_admin boolean not null default false;
alter table users add column if not exists username text;
+alter table users add column if not exists privy_did text;
create unique index if not exists users_wallet_unique on users(wallet_address) where wallet_address is not null;
create unique index if not exists users_username_unique on users(lower(username)) where username is not null;
+create unique index if not exists users_privy_did_unique on users(privy_did) where privy_did is not null;
-- ── user_subdomains — tracks `<label>.threews.sol` SNS claims ───────────────
-- Populated by /api/threews/subdomain POST; read by /api/threews/* + a few
diff --git a/api/auth/privy/verify.js b/api/auth/privy/verify.js
new file mode 100644
index 000000000..9e464a805
--- /dev/null
+++ b/api/auth/privy/verify.js
@@ -0,0 +1,148 @@
+// Verify a Privy auth token and issue a three.ws session.
+// POST /api/auth/privy/verify { token: string }
+//
+// The token is a Privy identity JWT signed by Privy's private key.
+// We verify it against Privy's published JWKS endpoint (no app secret needed).
+// On success we find-or-create a user and issue the standard session cookie.
+
+import { createRemoteJWKSet, jwtVerify } from 'jose';
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { createSession, sessionCookie, destroySession } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { seedDefaultAgent } from '../../_lib/seed-default-agent.js';
+import { logAudit } from '../../_lib/audit.js';
+
+const bodySchema = z.object({
+ token: z.string().min(10),
+});
+
+// jose caches the JWKS in memory between calls on the same warm instance.
+const jwksSets = new Map();
+function getJwks(appId) {
+ if (!jwksSets.has(appId)) {
+ jwksSets.set(
+ appId,
+ createRemoteJWKSet(new URL(`https://auth.privy.io/api/v1/apps/${appId}/jwks.json`)),
+ );
+ }
+ return jwksSets.get(appId);
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');
+
+ const appId = process.env.PRIVY_APP_ID || process.env.VITE_PRIVY_APP_ID;
+ if (!appId) return error(res, 503, 'not_configured', 'Privy is not configured on this server');
+
+ const { token } = parse(bodySchema, await readJson(req));
+
+ // Verify the Privy identity token with Privy's JWKS.
+ let payload;
+ try {
+ const JWKS = getJwks(appId);
+ const result = await jwtVerify(token, JWKS, {
+ issuer: 'privy.io',
+ audience: appId,
+ });
+ payload = result.payload;
+ } catch {
+ return error(res, 401, 'invalid_token', 'Privy token verification failed');
+ }
+
+ const privyDid = payload.sub; // 'did:privy:xxxxxxxx'
+ if (!privyDid) return error(res, 401, 'invalid_token', 'missing subject claim');
+
+ // Extract the most useful identity info Privy bundles in the token.
+ const linkedAccounts = Array.isArray(payload.linked_accounts) ? payload.linked_accounts : [];
+ const emailAccount = linkedAccounts.find(
+ (a) => a.type === 'email' || a.type === 'google_oauth' || a.type === 'twitter_oauth' || a.type === 'github_oauth',
+ );
+ const walletAccount = linkedAccounts.find((a) => a.type === 'wallet');
+
+ const realEmail = emailAccount?.address || emailAccount?.email || null;
+ // Stable synthetic email scoped to this Privy DID — same pattern as SIWE/SIWS.
+ const syntheticEmail = `privy-${privyDid.replace('did:privy:', '')}@privy.local`;
+ const effectiveEmail = realEmail || syntheticEmail;
+ const displayName =
+ emailAccount?.name ||
+ (realEmail ? realEmail.split('@')[0] : null) ||
+ privyDid.slice(-8);
+
+ // Find or create user. Look up by synthetic email first (stable per Privy DID),
+ // then fall through to real email (lets an existing email/password user link
+ // their Privy account on next login without creating a duplicate).
+ let userId;
+ let isNew = false;
+
+ const [byDid] = await sql`
+ select id from users
+ where email = ${syntheticEmail} and deleted_at is null
+ limit 1
+ `;
+
+ if (byDid) {
+ userId = byDid.id;
+ } else if (realEmail) {
+ const [byReal] = await sql`
+ select id from users
+ where email = ${realEmail} and deleted_at is null
+ limit 1
+ `;
+ if (byReal) {
+ userId = byReal.id;
+ }
+ }
+
+ if (!userId) {
+ // Create a new passwordless user. ON CONFLICT guards against a concurrent verify.
+ const [created] = await sql`
+ insert into users (email, display_name)
+ values (${effectiveEmail}, ${displayName})
+ on conflict (email) do update
+ set deleted_at = null,
+ display_name = excluded.display_name
+ returning id, (xmax = 0) as inserted
+ `;
+ userId = created.id;
+ isNew = created.inserted;
+ }
+
+ if (isNew) {
+ queueMicrotask(() => seedDefaultAgent(userId));
+ }
+
+ // If Privy returned an embedded wallet, record it in user_wallets.
+ if (walletAccount?.address) {
+ const addr = walletAccount.address.toLowerCase();
+ await sql`
+ insert into user_wallets (user_id, address, chain_type, is_primary)
+ values (${userId}, ${addr}, 'evm', true)
+ on conflict (address) do update
+ set last_used_at = now()
+ `.catch(() => {});
+ }
+
+ await destroySession(req);
+ const sessionToken = await createSession({
+ userId,
+ userAgent: req.headers['user-agent'],
+ ip,
+ });
+ res.setHeader('set-cookie', sessionCookie(sessionToken));
+ logAudit({ userId, action: 'login:privy', req });
+
+ const [userRow] = await sql`
+ select id, email, display_name, plan, avatar_url, created_at
+ from users where id = ${userId} limit 1
+ `;
+
+ return json(res, 200, { user: userRow });
+});
diff --git a/api/config.js b/api/config.js
index f989d8ddd..14b42d387 100644
--- a/api/config.js
+++ b/api/config.js
@@ -26,6 +26,7 @@ export default wrap(async (req, res) => {
return json(res, 200, {
walletConnectProjectId: process.env.VITE_WALLETCONNECT_PROJECT_ID || '',
+ privyAppId: process.env.VITE_PRIVY_APP_ID || process.env.PRIVY_APP_ID || '',
features: {
// /create/selfie + /scan use /api/avatars/reconstruct, which 501s
// unless an ML backend is wired. The pages read this to either show the
diff --git a/package-lock.json b/package-lock.json
index 4601a74f1..e9833a187 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -56,6 +56,7 @@
"@noble/curves": "^2.2.0",
"@octokit/rest": "^22.0.1",
"@pixiv/three-vrm": "^3.5.3",
+ "@privy-io/js-sdk-core": "^0.67.0",
"@pump-fun/agent-payments-sdk": "^3.1.0",
"@pump-fun/pump-sdk": "^1.36.0",
"@pump-fun/pump-swap-sdk": "^1.16.0",
@@ -15300,6 +15301,101 @@
"integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",
"license": "MIT"
},
+ "node_modules/@privy-io/api-base": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/@privy-io/api-base/-/api-base-1.9.0.tgz",
+ "integrity": "sha512-8OJ2chadFcgUwr+Kqim0z5paIdadEdMH8pW94WJz0O3s2X4aX7vhN1eqiNZqcdgSIk9FHm8c3A+/epJUwiTYuQ==",
+ "dependencies": {
+ "zod": "^3.24.3"
+ }
+ },
+ "node_modules/@privy-io/api-types": {
+ "version": "0.15.0",
+ "resolved": "https://registry.npmjs.org/@privy-io/api-types/-/api-types-0.15.0.tgz",
+ "integrity": "sha512-VT5/Wau37+ZRaVZ8CPa224z5qcJTeaQtamq6TfOcPJSdV6cNyX+Phlaeg13xFLjj3dIGkqibZvr0f45VT6PX3A==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@privy-io/chains": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/@privy-io/chains/-/chains-0.3.0.tgz",
+ "integrity": "sha512-27dTj94S4PbyiJuknRuqXzYZSqbk62y2Ht/8ppSNlsaIswxrso9uE8w5PKX82zNyz7crHRULfxDPv2xM2ZXHTg==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@privy-io/encoding": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/@privy-io/encoding/-/encoding-0.1.3.tgz",
+ "integrity": "sha512-tvSuC0umDmkfmdKe339P/IZzqh04y7WQ7fOB5iU0aQoxdEivjO0hAD4GHxNOTdn9be9hS2WfIp7u/q6h7ZvvTg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@scure/base": "^1.2.6"
+ }
+ },
+ "node_modules/@privy-io/ethereum": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/@privy-io/ethereum/-/ethereum-0.1.4.tgz",
+ "integrity": "sha512-YuxGO18eY9miw2CyyxOugOOSoFnsg0uM3KU3/bUwRZmIdOQzzyOuSV2ZoOJmZs2H4u5ofuI4vunjgqw1wOM3ng==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "viem": "2.52.0"
+ }
+ },
+ "node_modules/@privy-io/js-sdk-core": {
+ "version": "0.67.0",
+ "resolved": "https://registry.npmjs.org/@privy-io/js-sdk-core/-/js-sdk-core-0.67.0.tgz",
+ "integrity": "sha512-v9QI/hnucgCHykQutkQd807/bm6NvqNnzf+9fBUwVO1QNFoyOd7aGQ9jDCK441hp5Ecl1EzLs2LARihauJ4RCQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@privy-io/api-base": "1.9.0",
+ "@privy-io/api-types": "0.15.0",
+ "@privy-io/chains": "0.3.0",
+ "@privy-io/encoding": "0.1.3",
+ "@privy-io/ethereum": "0.1.4",
+ "@privy-io/routes": "0.2.4",
+ "canonicalize": "^2.0.0",
+ "eventemitter3": "^5.0.1",
+ "fetch-retry": "^6.0.0",
+ "jose": "^4.15.5",
+ "js-cookie": "^3.0.5",
+ "libphonenumber-js": "^1.10.44",
+ "set-cookie-parser": "^2.6.0"
+ },
+ "peerDependencies": {
+ "permissionless": "^0.2.47",
+ "viem": "2.52.0"
+ },
+ "peerDependenciesMeta": {
+ "permissionless": {
+ "optional": true
+ },
+ "viem": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@privy-io/js-sdk-core/node_modules/jose": {
+ "version": "4.15.9",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz",
+ "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
+ "node_modules/@privy-io/js-sdk-core/node_modules/set-cookie-parser": {
+ "version": "2.7.2",
+ "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
+ "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
+ "license": "MIT"
+ },
+ "node_modules/@privy-io/routes": {
+ "version": "0.2.4",
+ "resolved": "https://registry.npmjs.org/@privy-io/routes/-/routes-0.2.4.tgz",
+ "integrity": "sha512-rPb9z8q7gYSp4ip9I9wuISzf6oo4rTcu3VLmNvRmU4hXfEDzZ2qZhBIwLwwPPvxH+P2pAyaVhlKwV7jOKaeS7A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@privy-io/api-types": "0.15.0"
+ }
+ },
"node_modules/@pump-fun/agent-payments-sdk": {
"resolved": "agent-payments-sdk",
"link": true
@@ -26561,6 +26657,15 @@
],
"license": "CC-BY-4.0"
},
+ "node_modules/canonicalize": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/canonicalize/-/canonicalize-2.1.0.tgz",
+ "integrity": "sha512-F705O3xrsUtgt98j7leetNhTWPe+5S72rlL5O4jA1pKqBVQ/dT1O1D6PFxmSXvc0SUOinWS57DKx0I3CHrXJHQ==",
+ "license": "Apache-2.0",
+ "bin": {
+ "canonicalize": "bin/canonicalize.js"
+ }
+ },
"node_modules/case": {
"version": "1.6.3",
"resolved": "https://registry.npmjs.org/case/-/case-1.6.3.tgz",
@@ -31420,6 +31525,12 @@
"node": "^12.20 || >= 14.13"
}
},
+ "node_modules/fetch-retry": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/fetch-retry/-/fetch-retry-6.0.0.tgz",
+ "integrity": "sha512-BUFj1aMubgib37I3v4q78fYo63Po7t4HUPTpQ6/QE6yK6cIQrP+W43FYToeTEyg5m2Y7eFUtijUuAv/PDlWuag==",
+ "license": "MIT"
+ },
"node_modules/fflate": {
"version": "0.7.4",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.7.4.tgz",
@@ -37844,6 +37955,12 @@
"integrity": "sha512-hNngCeKxIUQiEUN3GPJOkz4wF/YvdUdbNL9hsBcMQTkKzboD7T/q3OYOuuPZLUE6dBxSGpwhk5mwuDud7JVAow==",
"license": "BSD-3-Clause"
},
+ "node_modules/js-cookie": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/js-cookie/-/js-cookie-3.0.8.tgz",
+ "integrity": "sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==",
+ "license": "MIT"
+ },
"node_modules/js-sdsl": {
"version": "4.4.2",
"resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.4.2.tgz",
@@ -38713,6 +38830,12 @@
"integrity": "sha512-eh6eHCrRi1+POZ3dA+Dq1C6jhP1GNtr9CRINMb67OKzqW9I5DUuZM/3jLPlzhgpGeiNUlEGEbkCYChXMCc/8DQ==",
"license": "Apache-2.0 OR MIT"
},
+ "node_modules/libphonenumber-js": {
+ "version": "1.13.5",
+ "resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.13.5.tgz",
+ "integrity": "sha512-7/kRezHmQlMfO6pmvt34orO/g3j1C47k8FCBXFgj/mklTLwQdBca1LkhDK6RM8UyM6JqHFAIikMdkKkyfQy39A==",
+ "license": "MIT"
+ },
"node_modules/lie": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
diff --git a/package.json b/package.json
index d25ce43e0..2b4d846ec 100644
--- a/package.json
+++ b/package.json
@@ -143,6 +143,7 @@
"@noble/curves": "^2.2.0",
"@octokit/rest": "^22.0.1",
"@pixiv/three-vrm": "^3.5.3",
+ "@privy-io/js-sdk-core": "^0.67.0",
"@pump-fun/agent-payments-sdk": "^3.1.0",
"@pump-fun/pump-sdk": "^1.36.0",
"@pump-fun/pump-swap-sdk": "^1.16.0",
diff --git a/pages/create.html b/pages/create.html
index b16684dfa..30081a976 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -867,13 +867,13 @@
<div class="your-avatars-row" id="your-avatars-row"></div>
</section>
- <!-- Recommended: customize a base avatar (hero) -->
+ <!-- Recommended: start with a template (hero) -->
<div
class="create-card hero-card is-recommended"
- id="card-customize"
+ id="card-default-editor"
role="button"
tabindex="0"
- aria-label="Customize a base avatar in the editor (recommended)"
+ aria-label="Start with a ready-made template (recommended)"
>
<span class="recommended-badge" aria-hidden="true">Recommended</span>
<div class="hero-card-body">
@@ -886,19 +886,19 @@
<path d="M18 3l3 3-9 9-4 1 1-4 9-9z" />
</svg>
</div>
- <h2 class="card-title">Customize a base avatar</h2>
+ <h2 class="card-title">Start with a template</h2>
</div>
<p class="card-subtitle">
- Sculpt the face, pick outfits and colors in our in-browser
- editor. Start from a base and make it unmistakably yours.
+ Pick a ready-made avatar and make it yours. The fastest way to
+ start — preview, save, then customize.
</p>
<div class="card-meta" aria-hidden="true">
- <span class="chip">Faces & outfits</span>
- <span class="chip">~1 min</span>
- <span class="chip chip-ok">No sign-in</span>
+ <span class="chip chip-ok">Free</span>
+ <span class="chip">~15 sec</span>
+ <span class="chip chip-ok">No sign-in to try</span>
</div>
<span class="card-cta">
- Open editor
+ Browse templates
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="5" y1="12" x2="19" y2="12" />
<polyline points="12 5 19 12 12 19" />
@@ -908,7 +908,7 @@
<div class="hero-card-preview">
<model-viewer
src="/avatars/default.glb"
- alt="Base 3D avatar you can customize"
+ alt="Ready-made 3D avatar template"
auto-rotate
auto-rotate-delay="0"
rotation-per-second="18deg"
@@ -928,7 +928,7 @@
</div>
<div class="secondary-grid" role="group" aria-label="More ways to create">
- <div class="create-card tile" id="card-default-editor" role="button" tabindex="0" aria-label="Start with a ready-made template">
+ <div class="create-card tile" id="card-customize" role="button" tabindex="0" aria-label="Customize a base avatar in the editor">
<div class="card-icon-row">
<div class="card-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
@@ -937,19 +937,19 @@
<path d="M18 3l3 3-9 9-4 1 1-4 9-9z" />
</svg>
</div>
- <h2 class="card-title">Start with a template</h2>
+ <h2 class="card-title">Customize a base avatar</h2>
</div>
<p class="card-subtitle">
- Pick a ready-made avatar and make it yours. The fastest way to
- start — preview, save, then customize.
+ Sculpt the face, pick outfits and colors in our in-browser
+ editor. Start from a base and make it unmistakably yours.
</p>
<div class="card-meta" aria-hidden="true">
- <span class="chip">Free</span>
- <span class="chip">~15 sec</span>
- <span class="chip chip-ok">No sign-in to try</span>
+ <span class="chip">Faces & outfits</span>
+ <span class="chip">~1 min</span>
+ <span class="chip chip-ok">No sign-in</span>
</div>
<span class="card-cta card-cta--ghost">
- Browse templates
+ Open editor
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="5" y1="12" x2="19" y2="12" />
<polyline points="12 5 19 12 12 19" />
diff --git a/pages/home.html b/pages/home.html
index 56b5e0e16..b1a720206 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -388,37 +388,6 @@
}
.logo-row .logo:hover { opacity: 1; }
- /* ── PRESS / LISTINGS ────────────────────────────────────── */
- .press-strip { padding: 64px 0; border-bottom: 1px solid var(--hairline); }
- .press-cap {
- font-family: var(--font-mono); font-size: 10.5px;
- letter-spacing: 0.2em; text-transform: uppercase;
- color: var(--text-4); text-align: center; margin-bottom: 22px;
- }
- .press-row {
- display: flex; flex-wrap: wrap; justify-content: center;
- gap: 14px; align-items: stretch; max-width: 920px; margin: 0 auto;
- }
- .press-chip {
- display: inline-flex; align-items: center; gap: 8px;
- padding: 10px 16px; border: 1px solid var(--hairline);
- border-radius: 10px; background: var(--surface-2, rgba(255,255,255,0.03));
- font-family: var(--font-display); font-size: 14px; font-weight: 500;
- letter-spacing: -0.01em; color: var(--text-3); text-decoration: none;
- transition: color 0.15s, border-color 0.15s, background 0.15s, transform 0.15s;
- }
- .press-chip:hover { color: var(--text); border-color: var(--text-3); transform: translateY(-2px); }
- .press-chip:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
- .press-chip .press-arrow { font-size: 11px; opacity: 0.5; }
- .press-divider { height: 30px; }
- .press-ca {
- margin: 26px auto 0; text-align: center;
- font-family: var(--font-mono); font-size: 11px; color: var(--text-4);
- word-break: break-all; max-width: 520px; line-height: 1.5;
- }
- .press-ca code { color: var(--text-3); }
- @media (max-width: 720px) { .press-strip { padding: 48px 0; } }
-
/* ── SECTION FRAME ───────────────────────────────────────── */
section.block { padding: 112px 0; border-top: 1px solid var(--hairline); }
@media (max-width: 720px) { section.block { padding: 72px 0; } }
@@ -2870,31 +2839,6 @@
</div>
</div>
-<!-- ── PRESS / LISTINGS ──────────────────────────────────────────── -->
-<!-- Coinbase + CoinGecko route to our own listings post on purpose: their public
- pages can surface a non-canonical mint, so we keep the destination on a page
- we control that shows the canonical $three contract. -->
-<section class="press-strip" id="press" aria-label="Press coverage and exchange listings">
- <div class="wrap-1280">
- <div class="press-cap">In the press</div>
- <div class="press-row">
- <a class="press-chip" href="https://markets.businessinsider.com/news/stocks/three-ws-and-ibm-announce-strategic-partnership-to-advance-ai-powered-3d-agent-technology-1036222181" target="_blank" rel="noopener noreferrer">Business Insider <span class="press-arrow" aria-hidden="true">↗</span></a>
- <a class="press-chip" href="https://finance.yahoo.com/sectors/technology/articles/ibm-extends-ai-narrative-three-010650764.html" target="_blank" rel="noopener noreferrer">Yahoo Finance <span class="press-arrow" aria-hidden="true">↗</span></a>
- </div>
- <div class="press-divider"></div>
- <div class="press-cap">Trading $three</div>
- <div class="press-row">
- <a class="press-chip" href="/blog/three-token-listings.html">Coinbase</a>
- <a class="press-chip" href="/blog/three-token-listings.html">CoinGecko</a>
- <a class="press-chip" href="https://announcements.bybit.com/en/article/three-is-now-live-on-bybit-alpha-bltc04fc471efada919/" target="_blank" rel="noopener noreferrer">Bybit <span class="press-arrow" aria-hidden="true">↗</span></a>
- <a class="press-chip" href="https://www.kucoin.com/news/flash/solana-meme-coin-three-surges-104-in-two-hours-reaches-16m-market-cap" target="_blank" rel="noopener noreferrer">KuCoin <span class="press-arrow" aria-hidden="true">↗</span></a>
- <a class="press-chip" href="https://www.mexc.com/exchange/THREE_USDT" target="_blank" rel="noopener noreferrer">MEXC <span class="press-arrow" aria-hidden="true">↗</span></a>
- <a class="press-chip" href="https://www.tradingview.com/news/coinmarketcal:f0996d63c094b:0-three-ws-three-kucoin-listing-02-june-2026/" target="_blank" rel="noopener noreferrer">TradingView <span class="press-arrow" aria-hidden="true">↗</span></a>
- </div>
- <p class="press-ca">$three contract · <code>FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump</code></p>
- </div>
-</section>
-
<!-- ── PLAYGROUND ──────────────────────────────────────────────────── -->
<section class="block" id="embed">
<div class="wrap-1280">
diff --git a/public/feed.css b/public/feed.css
deleted file mode 100644
index 643fa22f6..000000000
--- a/public/feed.css
+++ /dev/null
@@ -1,283 +0,0 @@
-/* three.ws live activity ticker — the site-wide "something is always happening
- * here" widget. Loaded on every page by nav.js, mounted bottom-left (the Walk
- * Companion owns bottom-right). Tokens fall back to literals so the widget looks
- * right on pages that don't load style.css. */
-
-.tws-feed {
- position: fixed;
- left: 16px;
- bottom: 16px;
- z-index: 2147482000; /* below the Walk Companion (…483000), above page chrome */
- font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
- color: var(--ink, var(--ink));
- -webkit-user-select: none;
- user-select: none;
-}
-
-.tws-feed[hidden] {
- display: none;
-}
-
-/* ── Collapsed pill ─────────────────────────────────────────────────────── */
-.tws-feed-pill {
- display: inline-flex;
- align-items: center;
- gap: 8px;
- max-width: min(320px, calc(100vw - 32px));
- padding: 8px 12px 8px 11px;
- border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
- border-radius: 999px;
- background: var(--surface-2, rgba(20, 21, 28, 0.82));
- backdrop-filter: blur(12px);
- -webkit-backdrop-filter: blur(12px);
- box-shadow: 0 8px 28px rgba(0, 0, 0, 0.35);
- color: inherit;
- font: inherit;
- font-size: 12.5px;
- line-height: 1.2;
- cursor: pointer;
- transition: transform 0.18s ease, border-color 0.18s ease, background 0.18s ease;
-}
-.tws-feed-pill:hover {
- transform: translateY(-1px);
- border-color: var(--stroke-strong, rgba(255, 255, 255, 0.18));
- background: var(--surface-3, rgba(28, 30, 40, 0.9));
-}
-.tws-feed-pill:focus-visible {
- outline: 2px solid var(--success, var(--success));
- outline-offset: 2px;
-}
-
-.tws-feed-dot {
- flex: 0 0 auto;
- width: 8px;
- height: 8px;
- border-radius: 50%;
- background: var(--success, var(--success));
- box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.5);
- animation: tws-feed-pulse 2.4s ease-out infinite;
-}
-@keyframes tws-feed-pulse {
- 0% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.45); }
- 70% { box-shadow: 0 0 0 7px rgba(74, 222, 128, 0); }
- 100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }
-}
-
-.tws-feed-pill-text {
- overflow: hidden;
- white-space: nowrap;
- text-overflow: ellipsis;
- color: var(--ink, var(--ink));
-}
-.tws-feed-pill-text b {
- font-weight: 600;
-}
-
-.tws-feed-count {
- flex: 0 0 auto;
- min-width: 18px;
- height: 18px;
- padding: 0 5px;
- border-radius: 999px;
- background: var(--success, var(--success));
- color: #06210f;
- font-size: 11px;
- font-weight: 700;
- line-height: 18px;
- text-align: center;
-}
-.tws-feed-count[hidden] {
- display: none;
-}
-
-/* ── Expanded panel ─────────────────────────────────────────────────────── */
-.tws-feed-panel {
- width: min(330px, calc(100vw - 32px));
- border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
- border-radius: var(--radius-card, 14px);
- background: var(--surface-2, rgba(16, 17, 24, 0.92));
- backdrop-filter: blur(16px);
- -webkit-backdrop-filter: blur(16px);
- box-shadow: 0 18px 48px rgba(0, 0, 0, 0.5);
- overflow: hidden;
- transform-origin: bottom left;
- animation: tws-feed-open 0.18s ease;
-}
-@keyframes tws-feed-open {
- from { opacity: 0; transform: translateY(8px) scale(0.98); }
- to { opacity: 1; transform: translateY(0) scale(1); }
-}
-
-.tws-feed-head {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 11px 12px;
- border-bottom: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
-}
-.tws-feed-head .tws-feed-dot {
- width: 7px;
- height: 7px;
-}
-.tws-feed-title {
- flex: 1 1 auto;
- font-size: 12.5px;
- font-weight: 600;
- letter-spacing: 0.02em;
- color: var(--ink, var(--ink));
-}
-.tws-feed-close {
- flex: 0 0 auto;
- width: 24px;
- height: 24px;
- display: grid;
- place-items: center;
- border: none;
- border-radius: 8px;
- background: transparent;
- color: var(--ink-dim, #888);
- font-size: 17px;
- line-height: 1;
- cursor: pointer;
- transition: background 0.15s ease, color 0.15s ease;
-}
-.tws-feed-close:hover {
- background: var(--surface-3, rgba(255, 255, 255, 0.08));
- color: var(--ink, var(--ink));
-}
-.tws-feed-close:focus-visible {
- outline: 2px solid var(--success, var(--success));
- outline-offset: 1px;
-}
-
-.tws-feed-list {
- max-height: min(56vh, 420px);
- overflow-y: auto;
- overscroll-behavior: contain;
- padding: 4px;
- margin: 0;
- list-style: none;
- scrollbar-width: thin;
- scrollbar-color: rgba(255, 255, 255, 0.18) transparent;
-}
-.tws-feed-list::-webkit-scrollbar { width: 8px; }
-.tws-feed-list::-webkit-scrollbar-thumb {
- background: rgba(255, 255, 255, 0.16);
- border-radius: 8px;
-}
-
-/* ── Rows ───────────────────────────────────────────────────────────────── */
-.tws-feed-item {
- display: flex;
- align-items: flex-start;
- gap: 10px;
- padding: 9px 9px;
- border-radius: 10px;
- text-decoration: none;
- color: inherit;
- transition: background 0.14s ease;
- animation: tws-feed-row-in 0.32s ease both;
-}
-a.tws-feed-item:hover {
- background: var(--surface-3, rgba(255, 255, 255, 0.06));
-}
-a.tws-feed-item:focus-visible {
- outline: 2px solid var(--success, var(--success));
- outline-offset: -2px;
-}
-@keyframes tws-feed-row-in {
- from { opacity: 0; transform: translateY(-6px); }
- to { opacity: 1; transform: translateY(0); }
-}
-
-.tws-feed-ico {
- flex: 0 0 auto;
- width: 26px;
- height: 26px;
- display: grid;
- place-items: center;
- border-radius: 8px;
- background: var(--surface-3, rgba(255, 255, 255, 0.08));
- font-size: 14px;
- line-height: 1;
-}
-.tws-feed-ico[data-kind='coin-buy'] { color: var(--success, var(--success)); }
-.tws-feed-ico[data-kind='agent-deploy'] { color: var(--ink-dim, #888888); }
-.tws-feed-ico[data-kind='level-up'] { color: var(--warn, #fbbf24); }
-.tws-feed-ico[data-kind='world-join'] { color: #7dd3fc; }
-.tws-feed-ico[data-kind='jackpot'] { color: var(--warn, #fbbf24); }
-.tws-feed-ico[data-kind='member-join'] { color: #5eead4; }
-
-.tws-feed-body {
- flex: 1 1 auto;
- min-width: 0;
-}
-.tws-feed-text {
- font-size: 12.5px;
- line-height: 1.35;
- color: var(--ink, var(--ink));
- word-break: break-word;
-}
-.tws-feed-text b {
- font-weight: 600;
-}
-.tws-feed-time {
- margin-top: 2px;
- font-size: 11px;
- color: var(--ink-dim, #888);
-}
-
-/* ── Skeleton / empty / error ───────────────────────────────────────────── */
-.tws-feed-skel {
- display: flex;
- gap: 10px;
- padding: 9px;
- align-items: center;
-}
-.tws-feed-skel span {
- display: block;
- height: 10px;
- border-radius: 6px;
- background: linear-gradient(90deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.06));
- background-size: 200% 100%;
- animation: tws-feed-shimmer 1.3s linear infinite;
-}
-.tws-feed-skel .s-ico { width: 26px; height: 26px; border-radius: 8px; flex: 0 0 auto; }
-.tws-feed-skel .s-a { width: 70%; }
-.tws-feed-skel .s-b { width: 40%; margin-top: 6px; }
-@keyframes tws-feed-shimmer {
- from { background-position: 200% 0; }
- to { background-position: -200% 0; }
-}
-
-.tws-feed-msg {
- padding: 22px 18px;
- text-align: center;
- color: var(--ink-dim, #888);
- font-size: 12.5px;
- line-height: 1.5;
-}
-.tws-feed-msg strong {
- display: block;
- color: var(--ink, var(--ink));
- font-weight: 600;
- margin-bottom: 3px;
-}
-.tws-feed-msg a {
- color: var(--success, var(--success));
- text-decoration: none;
-}
-.tws-feed-msg a:hover { text-decoration: underline; }
-
-/* ── Motion / responsive ────────────────────────────────────────────────── */
-@media (max-width: 520px) {
- .tws-feed { left: 10px; bottom: 10px; }
- .tws-feed-pill .tws-feed-pill-text { max-width: 150px; }
-}
-@media (prefers-reduced-motion: reduce) {
- .tws-feed-dot { animation: none; }
- .tws-feed-panel,
- .tws-feed-item { animation: none; }
- .tws-feed-skel span { animation: none; }
- .tws-feed-pill { transition: none; }
-}
diff --git a/public/feed.js b/public/feed.js
deleted file mode 100644
index 7043218b7..000000000
--- a/public/feed.js
+++ /dev/null
@@ -1,505 +0,0 @@
-// three.ws live activity ticker — the site-wide "something is always happening
-// here" widget. Self-mounting: nav.js loads this on every page. Renders a small
-// pulsing pill bottom-left that expands into a live panel of recent platform
-// events (coin buys, agent deploys, member sign-ins, level-ups, world joins).
-// Loads the backlog once from GET /api/feed, then subscribes to /api/feed-stream
-// (SSE) so new activity appears in real time; a slow poll stays on as a backstop
-// and to refresh relative timestamps. Falls back to polling where SSE is absent.
-//
-// Opt out per page with <html data-feed="off"> or window.__twsFeedOff = true.
-// The data source and event shape live in api/_lib/feed.js.
-
-(function () {
- 'use strict';
-
- if (window.__twsFeed) return; // idempotent — never double-mount
- if (typeof document === 'undefined') return;
- if (document.documentElement.getAttribute('data-feed') === 'off') return;
- if (window.__twsFeedOff) return;
-
- var API = '/api/feed?limit=30';
- // Polled from every page the widget mounts on. Kept at/above the endpoint's
- // edge-cache window so the CDN absorbs most polls instead of each one hitting
- // Redis — the feed is a delight layer, so 20s feels live and saves quota.
- var POLL_MS = 20000;
- var STORE_KEY = 'tws-feed:open'; // remember collapsed vs expanded across pages
-
- // ── State ────────────────────────────────────────────────────────────────
- var events = []; // newest-first, capped
- var seenIds = Object.create(null);
- var unseen = 0; // new since last time the panel was open
- var open = false;
- var loaded = false;
- var errored = false;
- var pollTimer = null;
- var root, pill, pillText, pillCount, panel, list;
-
- try {
- open = localStorage.getItem(STORE_KEY) === '1';
- } catch (_) {}
-
- // ── Rendering helpers ─────────────────────────────────────────────────────
- function el(tag, cls, text) {
- var n = document.createElement(tag);
- if (cls) n.className = cls;
- if (text != null) n.textContent = text;
- return n;
- }
-
- function shortMint(m) {
- m = String(m || '');
- return m.length > 8 ? m.slice(0, 4) + '…' + m.slice(-4) : m;
- }
-
- function fmtSol(n) {
- var v = Number(n);
- if (!isFinite(v) || v <= 0) return '';
- if (v >= 100) return Math.round(v).toString();
- // up to 3 significant decimals, trimmed
- return parseFloat(v.toFixed(3)).toString();
- }
-
- function relTime(ts) {
- var s = Math.max(0, Math.floor((Date.now() - ts) / 1000));
- if (s < 10) return 'just now';
- if (s < 60) return s + 's ago';
- var m = Math.floor(s / 60);
- if (m < 60) return m + 'm ago';
- var h = Math.floor(m / 60);
- if (h < 24) return h + 'h ago';
- var d = Math.floor(h / 24);
- return d + 'd ago';
- }
-
- // Per-type presentation. Returns { icon, href, build(textNode) } where build
- // fills a container with text — user-supplied strings go in via textContent
- // (createTextNode / el(text)), never innerHTML, so the world-readable feed
- // can't inject markup.
- var KINDS = {
- 'coin-buy': {
- icon: '↗',
- href: function (e) { return e.mint ? '/play?coin=' + encodeURIComponent(e.mint) : '/play'; },
- parts: function (e) {
- var sol = fmtSol(e.sol);
- return [
- bold(e.actor || 'Someone'),
- ' aped ',
- sol ? bold(sol + ' SOL') : 'in',
- ' into ',
- bold(shortMint(e.mint)),
- ];
- },
- },
- 'agent-deploy': {
- icon: '✦',
- href: function (e) { return e.agentId ? '/agent/' + encodeURIComponent(e.agentId) : '/discover'; },
- parts: function (e) { return [bold(e.name || e.actor || 'A new agent'), ' just joined three.ws']; },
- },
- 'member-join': {
- icon: '✷',
- href: function (e) { return e.handle ? 'https://x.com/' + encodeURIComponent(e.handle) : '/play'; },
- parts: function (e) { return [bold('@' + (e.handle || e.actor || 'someone')), ' just joined three.ws']; },
- },
- 'agent-onchain': {
- icon: '⛓',
- href: function (e) { return e.agentId ? '/agent/' + encodeURIComponent(e.agentId) : '/discover'; },
- parts: function (e) {
- var who = bold(e.name || e.actor || 'An agent');
- return e.chain ? [who, ' deployed on-chain on ', bold(e.chain)] : [who, ' just deployed on-chain'];
- },
- },
- 'level-up': {
- icon: '⬆',
- href: function () { return '/play'; },
- parts: function (e) {
- return [bold(e.actor || 'A player'), ' reached ', bold(cap(e.skill) + ' ' + e.level)];
- },
- },
- 'world-join': {
- icon: '◉',
- href: function (e) { return e.coin ? '/play?coin=' + encodeURIComponent(e.coin) : '/play'; },
- parts: function (e) {
- return [bold(e.actor || 'Someone'), ' is hanging out in ', bold(e.coinName || 'a world')];
- },
- },
- jackpot: {
- icon: '★',
- href: function () { return '/play'; },
- parts: function (e) { return [bold(e.actor || 'A player'), ' won ', bold(e.reward || 'the jackpot')]; },
- },
- 'mission-complete': {
- icon: '◈',
- href: function (e) { return e.coin ? '/play?coin=' + encodeURIComponent(e.coin) : '/play'; },
- parts: function (e) {
- var verb = e.coop ? ' pulled off the heist ' : ' completed ';
- var out = [bold(e.actor || 'A player'), verb, bold(e.mission || 'a job')];
- if (e.gold) out.push(' for ', bold(Number(e.gold).toLocaleString() + ' gold'));
- return out;
- },
- },
- payment: {
- icon: '✓',
- href: function (e) { return e.explorerUrl || null; },
- parts: function (e) {
- var amtParts = [];
- if (e.usdcAtomic != null) {
- var dec = Number(e.usdcAtomic) / 1e6;
- var fmt = dec < 0.01 ? dec.toFixed(4) : dec < 1 ? dec.toFixed(3) : dec.toFixed(2);
- amtParts.push(' $' + fmt);
- }
- var toParts = e.recipientLabel ? [' to ', bold(String(e.recipientLabel).slice(0, 40))] : [];
- var actorParts = [bold(e.actor || 'User'), ' paid'];
- return actorParts.concat(amtParts).concat(toParts);
- },
- },
- };
-
- function bold(t) {
- var b = document.createElement('b');
- b.textContent = t == null ? '' : String(t);
- return b;
- }
- function cap(s) {
- s = String(s || '');
- return s ? s.charAt(0).toUpperCase() + s.slice(1) : '';
- }
-
- // Flatten a parts array (strings + <b> nodes) into a target element.
- function fillText(target, parts) {
- for (var i = 0; i < parts.length; i++) {
- var p = parts[i];
- target.appendChild(typeof p === 'string' ? document.createTextNode(p) : p);
- }
- }
-
- function buildRow(e) {
- var kind = KINDS[e.type];
- if (!kind) return null;
- var href = kind.href(e);
- var row = el(href ? 'a' : 'div', 'tws-feed-item');
- if (href) {
- row.href = href;
- row.setAttribute('role', 'listitem');
- }
- var ico = el('span', 'tws-feed-ico');
- ico.setAttribute('data-kind', e.type);
- ico.setAttribute('aria-hidden', 'true');
- ico.textContent = kind.icon;
- var body = el('div', 'tws-feed-body');
- var text = el('div', 'tws-feed-text');
- fillText(text, kind.parts(e));
- var time = el('div', 'tws-feed-time', relTime(e.ts));
- time.setAttribute('data-ts', e.ts);
- body.appendChild(text);
- body.appendChild(time);
- row.appendChild(ico);
- row.appendChild(body);
- return row;
- }
-
- // One-line summary for the collapsed pill (latest event).
- function pillSummary(e) {
- var kind = KINDS[e.type];
- if (!kind) return null;
- var frag = document.createDocumentFragment();
- fillText(frag, kind.parts(e));
- return frag;
- }
-
- // ── DOM build ──────────────────────────────────────────────────────────────
- function mount() {
- ensureCss();
- root = el('div', 'tws-feed');
- root.setAttribute('aria-live', 'off');
-
- pill = el('button', 'tws-feed-pill');
- pill.type = 'button';
- pill.appendChild(el('span', 'tws-feed-dot'));
- pillText = el('span', 'tws-feed-pill-text');
- pillText.appendChild(document.createTextNode('Live activity'));
- pill.appendChild(pillText);
- pillCount = el('span', 'tws-feed-count');
- pillCount.hidden = true;
- pill.appendChild(pillCount);
- pill.addEventListener('click', expand);
-
- panel = el('div', 'tws-feed-panel');
- panel.hidden = true;
- var head = el('div', 'tws-feed-head');
- head.appendChild(el('span', 'tws-feed-dot'));
- head.appendChild(el('span', 'tws-feed-title', 'Live activity'));
- var close = el('button', 'tws-feed-close', '×');
- close.type = 'button';
- close.setAttribute('aria-label', 'Collapse activity feed');
- close.addEventListener('click', collapse);
- head.appendChild(close);
- list = el('ul', 'tws-feed-list');
- list.setAttribute('role', 'log');
- list.setAttribute('aria-label', 'Recent activity');
- list.setAttribute('aria-live', 'polite');
- panel.appendChild(head);
- panel.appendChild(list);
-
- root.appendChild(pill);
- root.appendChild(panel);
- document.body.appendChild(root);
-
- applyOpenState();
- renderSkeleton();
-
- // Keyboard: Escape collapses an open panel.
- document.addEventListener('keydown', function (ev) {
- if (ev.key === 'Escape' && open) collapse();
- });
- // Pause polling on hidden tabs; refresh immediately on return.
- document.addEventListener('visibilitychange', function () {
- if (document.hidden) {
- stopPolling();
- stopStream();
- } else {
- poll();
- startPolling();
- startStream();
- }
- });
- // Hide entirely while a page element is fullscreen (immersive 3D etc.).
- document.addEventListener('fullscreenchange', function () {
- root.hidden = !!document.fullscreenElement;
- });
- }
-
- function ensureCss() {
- if (document.querySelector('link[href="/feed.css"]')) return;
- var link = document.createElement('link');
- link.rel = 'stylesheet';
- link.href = '/feed.css';
- document.head.appendChild(link);
- }
-
- // ── State transitions ──────────────────────────────────────────────────────
- function applyOpenState() {
- panel.hidden = !open;
- pill.hidden = open;
- pill.setAttribute('aria-expanded', open ? 'true' : 'false');
- if (open) {
- unseen = 0;
- updateCount();
- }
- }
- function expand() {
- open = true;
- try { localStorage.setItem(STORE_KEY, '1'); } catch (_) {}
- applyOpenState();
- render();
- }
- function collapse() {
- open = false;
- try { localStorage.setItem(STORE_KEY, '0'); } catch (_) {}
- applyOpenState();
- updatePill();
- }
-
- function updateCount() {
- if (unseen > 0) {
- pillCount.hidden = false;
- pillCount.textContent = unseen > 9 ? '9+' : String(unseen);
- pill.setAttribute('aria-label', 'Live activity — ' + unseen + ' new. Open feed.');
- } else {
- pillCount.hidden = true;
- pill.setAttribute('aria-label', 'Live activity. Open feed.');
- }
- }
-
- function updatePill() {
- var latest = events[0];
- // Empty the text node container, then refill.
- while (pillText.firstChild) pillText.removeChild(pillText.firstChild);
- if (latest) {
- var frag = pillSummary(latest);
- if (frag) pillText.appendChild(frag);
- else pillText.appendChild(document.createTextNode('Live activity'));
- } else if (errored && !loaded) {
- pillText.appendChild(document.createTextNode('Activity'));
- } else {
- pillText.appendChild(document.createTextNode(loaded ? "It's quiet right now" : 'Live activity'));
- }
- updateCount();
- }
-
- // ── Render the panel list ──────────────────────────────────────────────────
- function renderSkeleton() {
- list.textContent = '';
- for (var i = 0; i < 4; i++) {
- var li = el('li', 'tws-feed-skel');
- li.appendChild(el('span', 's-ico'));
- var col = el('div');
- col.style.flex = '1';
- col.appendChild(el('span', 's-a'));
- col.appendChild(el('span', 's-b'));
- li.appendChild(col);
- list.appendChild(li);
- }
- }
-
- function renderMessage(strongTxt, rest) {
- list.textContent = '';
- var li = el('li');
- var msg = el('div', 'tws-feed-msg');
- msg.appendChild(el('strong', null, strongTxt));
- if (rest) msg.appendChild(rest);
- li.appendChild(msg);
- list.appendChild(li);
- }
-
- function render() {
- if (!open) { updatePill(); return; }
- if (!loaded && !errored) { renderSkeleton(); return; }
- if (!events.length) {
- if (errored) {
- var retry = document.createElement('a');
- retry.href = '#';
- retry.textContent = 'Try again';
- retry.addEventListener('click', function (e) { e.preventDefault(); poll(); });
- renderMessage('Activity paused', wrapMsg('Couldn’t reach the feed. ', retry));
- } else {
- var go = document.createElement('a');
- go.href = '/play';
- go.textContent = 'Drop into a world';
- renderMessage("It's quiet right now", wrapMsg('Be the first — ', go));
- }
- return;
- }
- list.textContent = '';
- for (var i = 0; i < events.length; i++) {
- var row = buildRow(events[i]);
- if (row) list.appendChild(row);
- }
- }
-
- function wrapMsg(text, node) {
- var span = el('span', null, text);
- if (node) span.appendChild(node);
- return span;
- }
-
- // Refresh the "2m ago" labels in place without rebuilding rows.
- function refreshTimes() {
- var nodes = list.querySelectorAll('.tws-feed-time');
- for (var i = 0; i < nodes.length; i++) {
- var ts = Number(nodes[i].getAttribute('data-ts'));
- if (ts) nodes[i].textContent = relTime(ts);
- }
- }
-
- // ── Data ───────────────────────────────────────────────────────────────────
- function merge(incoming) {
- var added = 0;
- var fresh = [];
- for (var i = 0; i < incoming.length; i++) {
- var e = incoming[i];
- if (!e || !e.id || seenIds[e.id]) continue;
- seenIds[e.id] = 1;
- fresh.push(e);
- added++;
- }
- if (added) {
- // Incoming is newest-first; prepend and keep the list bounded.
- events = fresh.concat(events).slice(0, 40);
- if (!open && loaded) unseen = Math.min(99, unseen + added);
- }
- return added;
- }
-
- // Reflect freshly-merged events into the UI. Shared by the poll and the SSE
- // stream so both paths animate in identically.
- function onIngest(added, first) {
- if (open) {
- if (first || added) render();
- else refreshTimes();
- } else {
- updatePill();
- }
- }
-
- function poll() {
- fetch(API, { headers: { accept: 'application/json' }, credentials: 'omit' })
- .then(function (r) {
- if (!r.ok) throw new Error('http ' + r.status);
- return r.json();
- })
- .then(function (data) {
- errored = false;
- var first = !loaded;
- loaded = true;
- onIngest(merge(Array.isArray(data.events) ? data.events : []), first);
- })
- .catch(function () {
- errored = true;
- if (!loaded) {
- if (open) render();
- else updatePill();
- }
- });
- }
-
- // ── Real-time stream ─────────────────────────────────────────────────────
- // EventSource pushes new events within ~1.5s of them happening (vs the poll's
- // 20s). The poll stays on as a slow backstop that also refreshes "Nm ago"
- // labels and reconciles anything the stream missed across a reconnect. When
- // EventSource is unavailable the poll alone carries the feed.
- var es = null;
- function startStream() {
- if (typeof EventSource === 'undefined' || es) return;
- try {
- es = new EventSource('/api/feed-stream');
- } catch (_) {
- es = null;
- return;
- }
- es.addEventListener('event', function (msg) {
- var ev = null;
- try { ev = JSON.parse(msg.data); } catch (_) { return; }
- if (!ev) return;
- loaded = true;
- errored = false;
- onIngest(merge([ev]), false);
- });
- // On error EventSource auto-reconnects; nothing to do. The backstop poll
- // covers the gap. We deliberately don't tear down on error.
- }
- function stopStream() {
- if (es) { try { es.close(); } catch (_) {} es = null; }
- }
-
- function startPolling() {
- stopPolling();
- pollTimer = setInterval(function () {
- poll();
- refreshTimes();
- }, POLL_MS);
- }
- function stopPolling() {
- if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
- }
-
- // ── Public surface ─────────────────────────────────────────────────────────
- window.__twsFeed = {
- open: expand,
- close: collapse,
- refresh: poll,
- events: function () { return events.slice(); },
- };
-
- function boot() {
- mount();
- poll();
- startPolling();
- startStream();
- }
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', boot);
- } else {
- boot();
- }
-})();
diff --git a/public/footer.html b/public/footer.html
index 7aaf38343..876083a4f 100644
--- a/public/footer.html
+++ b/public/footer.html
@@ -86,11 +86,17 @@
<a href="https://jup.ag/tokens/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener">Buy on Jupiter</a>
<a href="https://www.coingecko.com/en/coins/three-ws" target="_blank" rel="noopener">CoinGecko</a>
<a href="https://www.coinbase.com/price/threews-solana-aba58c21" target="_blank" rel="noopener">Coinbase</a>
+ <a href="https://announcements.bybit.com/en/article/three-is-now-live-on-bybit-alpha-bltc04fc471efada919/" target="_blank" rel="noopener">Bybit</a>
+ <a href="https://www.kucoin.com/news/flash/solana-meme-coin-three-surges-104-in-two-hours-reaches-16m-market-cap" target="_blank" rel="noopener">KuCoin</a>
+ <a href="https://www.mexc.com/exchange/THREE_USDT" target="_blank" rel="noopener">MEXC</a>
+ <a href="https://www.tradingview.com/news/coinmarketcal:f0996d63c094b:0-three-ws-three-kucoin-listing-02-june-2026/" target="_blank" rel="noopener">TradingView</a>
<a href="https://phantom.com/tokens/solana/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener">Phantom</a>
<a href="/rider">Rider VR Gate</a>
</div>
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Press</h4>
+ <a href="https://markets.businessinsider.com/news/stocks/three-ws-and-ibm-announce-strategic-partnership-to-advance-ai-powered-3d-agent-technology-1036222181" target="_blank" rel="noopener">Business Insider</a>
+ <a href="https://finance.yahoo.com/sectors/technology/articles/ibm-extends-ai-narrative-three-010650764.html" target="_blank" rel="noopener">Yahoo Finance</a>
<a href="https://www.crunchbase.com/organization/three-ws" target="_blank" rel="noopener">Crunchbase</a>
<a href="https://www.vogue.com/photovogue/photographers/416428" target="_blank" rel="noopener">Vogue</a>
</div>
diff --git a/public/login.html b/public/login.html
index b94090b41..dbb484aab 100644
--- a/public/login.html
+++ b/public/login.html
@@ -299,6 +299,48 @@
/* .password-wrap, .password-toggle, .caps-warn come from /auth.css. */
+ /* ── Privy section ── */
+ #privy-section { margin: 0 0 2px; }
+ #privy-toggle-btn {
+ width: 100%;
+ margin-top: 0;
+ padding: 11px 16px;
+ background: #0e0e0e;
+ border: 1px solid rgba(255,255,255,0.1);
+ border-radius: 10px;
+ color: #d0d0d0;
+ font-size: 14px;
+ font-weight: 500;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 9px;
+ transition: background 0.12s, border-color 0.12s, color 0.12s;
+ letter-spacing: -0.01em;
+ }
+ #privy-toggle-btn:hover { background: #161616; border-color: rgba(255,255,255,0.18); color: #fff; }
+ #privy-toggle-btn svg { flex-shrink: 0; }
+ #privy-expanded { margin-top: 8px; }
+ .privy-row { display: flex; gap: 8px; align-items: flex-start; }
+ .privy-row input { flex: 1; margin: 0; }
+ .privy-row-btn {
+ width: auto; margin: 0; padding: 11px 16px;
+ background: #fff; color: #000; border-radius: 10px;
+ font-size: 14px; font-weight: 600; border: none; cursor: pointer;
+ white-space: nowrap; flex-shrink: 0;
+ transition: background 0.12s, opacity 0.12s;
+ }
+ .privy-row-btn:hover:not(:disabled) { background: #e8ecf4; }
+ .privy-row-btn:disabled { opacity: 0.4; cursor: default; }
+ #privy-inline-err { margin: 6px 0 0; font-size: 12px; color: #ff9a9a; }
+ .privy-back-link {
+ display: inline-block; margin-top: 8px; font-size: 12px;
+ color: #444; cursor: pointer; background: none; border: none;
+ padding: 0; text-decoration: underline; text-underline-offset: 2px; width: auto;
+ }
+ .privy-back-link:hover { color: #888; }
+
/* ── No-wallet welcome banner ── */
.no-wallet-hint {
display: none;
@@ -485,6 +527,31 @@
No wallet needed — sign in with your email below.
</p>
+ <!-- Privy social / email-OTP login -->
+ <div id="privy-section">
+ <button type="button" id="privy-toggle-btn">
+ <svg width="18" height="18" viewBox="0 0 36 36" fill="none" aria-hidden="true"><rect width="36" height="36" rx="8" fill="#2563EB"/><path d="M18 8C12.477 8 8 12.477 8 18s4.477 10 10 10 10-4.477 10-10S23.523 8 18 8zm0 3a7 7 0 110 14A7 7 0 0118 11zm0 2a5 5 0 100 10A5 5 0 0018 13zm0 2a3 3 0 110 6 3 3 0 010-6z" fill="#fff" opacity=".9"/></svg>
+ Continue with Privy
+ </button>
+ <div id="privy-expanded" hidden>
+ <div id="privy-step-email">
+ <div class="privy-row">
+ <input id="privy-email-input" type="email" inputmode="email" placeholder="Email address" autocomplete="email" autocapitalize="none" />
+ <button type="button" id="privy-send-btn" class="privy-row-btn">Send code</button>
+ </div>
+ </div>
+ <div id="privy-step-code" hidden>
+ <div class="privy-row">
+ <input id="privy-code-input" type="text" inputmode="numeric" placeholder="6-digit code" maxlength="6" autocomplete="one-time-code" />
+ <button type="button" id="privy-verify-btn" class="privy-row-btn">Verify</button>
+ </div>
+ </div>
+ <p id="privy-inline-err" hidden></p>
+ <button type="button" id="privy-back-btn" class="privy-back-link">← Back</button>
+ </div>
+ </div>
+ <div class="or-divider" id="privy-or-divider">or</div>
+
<label for="email">Email or username</label>
<input id="email" name="username" type="text" inputmode="email" autocapitalize="none" autocomplete="username email" autofocus required aria-describedby="email-err" />
<p class="field-err" id="email-err" role="alert"></p>
@@ -644,6 +711,7 @@
</div>
</footer>
<script type="module" src="/wallet-login.js"></script>
+ <script type="module" src="/privy-login.js"></script>
<script>
(function () {
const form = document.getElementById('f');
diff --git a/public/nav.js b/public/nav.js
index 264606316..1846b54fd 100644
--- a/public/nav.js
+++ b/public/nav.js
@@ -7,17 +7,6 @@
// styles (public/nav.css) and behavior here mirror pages/home.html so every
// page reads as the same site.
-// Load the site-wide live activity ticker (public/feed.js) on every page that
-// carries the shared nav. Self-mounting + idempotent; honours <html data-feed="off">.
-function loadActivityFeed() {
- if (document.documentElement.getAttribute('data-feed') === 'off') return;
- if (document.querySelector('script[src="/feed.js"]')) return;
- const s = document.createElement('script');
- s.src = '/feed.js';
- s.defer = true;
- document.head.appendChild(s);
-}
-
// Load the site-wide glossary tooltip system (public/glossary.js) on every
// page. Self-mounting + idempotent; honours <html data-glossary="off">.
function loadGlossary() {
@@ -76,7 +65,6 @@ function loadDiscovery() {
}
function boot() {
- loadActivityFeed();
loadGlossary();
loadSearch();
loadDiscovery();
diff --git a/public/privy-login.js b/public/privy-login.js
new file mode 100644
index 000000000..db6a9c05a
--- /dev/null
+++ b/public/privy-login.js
@@ -0,0 +1,165 @@
+// Privy headless email-OTP auth for login and register pages.
+// Wires up the #privy-section UI block that both pages include.
+// On success POSTs the Privy identity_token to /api/auth/privy/verify
+// which issues our standard session cookie, then redirects.
+
+import Privy, { LocalStorage } from '@privy-io/js-sdk-core';
+
+const next =
+ window.__loginNext ||
+ new URLSearchParams(location.search).get('next') ||
+ sessionStorage.getItem('login_redirect') ||
+ '/dashboard';
+sessionStorage.removeItem('login_redirect');
+
+// ── Bootstrap ────────────────────────────────────────────────────────────────
+
+async function getAppId() {
+ try {
+ const r = await fetch('/api/config');
+ const cfg = await r.json();
+ return cfg.privyAppId || null;
+ } catch {
+ return null;
+ }
+}
+
+const appId = await getAppId();
+
+// If Privy is not configured, hide the section and exit.
+const section = document.getElementById('privy-section');
+if (!appId) {
+ if (section) section.style.display = 'none';
+ // Also hide the "or" divider if nothing else is above it.
+ const divider = document.getElementById('privy-or-divider');
+ if (divider) divider.style.display = 'none';
+} else {
+ const privy = new Privy({ appId, storage: new LocalStorage() });
+ await privy.initialize();
+ mountPrivyUI(privy);
+}
+
+// ── UI ───────────────────────────────────────────────────────────────────────
+
+function mountPrivyUI(privy) {
+ // Elements
+ const toggleBtn = document.getElementById('privy-toggle-btn');
+ const expandedArea = document.getElementById('privy-expanded');
+ const stepEmail = document.getElementById('privy-step-email');
+ const stepCode = document.getElementById('privy-step-code');
+ const emailInput = document.getElementById('privy-email-input');
+ const codeInput = document.getElementById('privy-code-input');
+ const sendBtn = document.getElementById('privy-send-btn');
+ const verifyBtn = document.getElementById('privy-verify-btn');
+ const backBtn = document.getElementById('privy-back-btn');
+ const errEl = document.getElementById('privy-inline-err');
+
+ if (!toggleBtn || !expandedArea) return;
+
+ let pendingEmail = '';
+
+ function showErr(msg) {
+ if (errEl) { errEl.textContent = msg; errEl.hidden = false; }
+ }
+ function clearErr() {
+ if (errEl) { errEl.textContent = ''; errEl.hidden = true; }
+ }
+
+ function expand() {
+ toggleBtn.hidden = true;
+ expandedArea.hidden = false;
+ showStep('email');
+ emailInput?.focus();
+ }
+ function collapse() {
+ toggleBtn.hidden = false;
+ expandedArea.hidden = true;
+ clearErr();
+ if (emailInput) emailInput.value = '';
+ if (codeInput) codeInput.value = '';
+ }
+
+ function showStep(step) {
+ clearErr();
+ stepEmail.hidden = step !== 'email';
+ stepCode.hidden = step !== 'code';
+ }
+
+ // Open / close
+ toggleBtn.addEventListener('click', expand);
+ backBtn?.addEventListener('click', collapse);
+
+ // Send OTP code
+ sendBtn?.addEventListener('click', async () => {
+ const email = emailInput?.value.trim();
+ if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
+ showErr('Enter a valid email address.'); return;
+ }
+ sendBtn.disabled = true;
+ sendBtn.textContent = 'Sending…';
+ clearErr();
+ try {
+ await privy.auth.email.sendCode(email);
+ pendingEmail = email;
+ showStep('code');
+ codeInput?.focus();
+ } catch (e) {
+ showErr(e?.message || 'Failed to send code. Try again.');
+ sendBtn.disabled = false;
+ sendBtn.textContent = 'Send code';
+ }
+ });
+
+ // Keyboard submit on email field
+ emailInput?.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') { e.preventDefault(); sendBtn?.click(); }
+ });
+
+ // Verify OTP code
+ verifyBtn?.addEventListener('click', async () => {
+ const code = codeInput?.value.trim();
+ if (!code || code.length < 4) {
+ showErr('Enter the code from your email.'); return;
+ }
+ verifyBtn.disabled = true;
+ verifyBtn.textContent = 'Verifying…';
+ clearErr();
+ try {
+ const { identity_token } = await privy.auth.email.loginWithCode(pendingEmail, code);
+ if (!identity_token) throw new Error('No identity token returned.');
+
+ verifyBtn.textContent = 'Signing in…';
+ const res = await fetch('/api/auth/privy/verify', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ token: identity_token }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(data.error_description || 'Sign-in failed.');
+
+ try {
+ localStorage.setItem(
+ '3dagent:auth-hint',
+ JSON.stringify({ authed: true, name: data.user?.display_name || '', ts: Date.now() }),
+ );
+ } catch { /* ignore */ }
+
+ location.href = next;
+ } catch (e) {
+ showErr(e?.message || 'Verification failed. Check the code and try again.');
+ verifyBtn.disabled = false;
+ verifyBtn.textContent = 'Verify';
+ }
+ });
+
+ // Keyboard submit on code field
+ codeInput?.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') { e.preventDefault(); verifyBtn?.click(); }
+ });
+
+ // Auto-format OTP (digits only)
+ codeInput?.addEventListener('input', () => {
+ codeInput.value = codeInput.value.replace(/\D/g, '').slice(0, 6);
+ });
+}