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
fix(walk-avatar): accept an auth callback token only for a sign-in the extension started
nirholas4f14c091dc7a
diff --git a/extensions/walk-avatar/background.js b/extensions/walk-avatar/background.jsindex 8956a95d1..01ee2d5f3 100644--- a/extensions/walk-avatar/background.js+++ b/extensions/walk-avatar/background.js@@ -9,6 +9,7 @@// • Enforce the site allow/blocklist before an avatar is ever mounted.const THREEWS_ORIGIN = 'https://three.ws';+const AUTH_STATE_KEY = 'auth_pending_state';// Defaults are written on install and used as the merge base everywhere the UI// reads settings, so a missing key never produces `undefined` downstream.@@ -92,6 +93,19 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {break;}+ case 'begin-signin': {+ const bytes = crypto.getRandomValues(new Uint8Array(24));+ const state = btoa(String.fromCharCode(...bytes))+ .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+ await chrome.storage.session.set({ [AUTH_STATE_KEY]: state });+ const next = `/extension/auth-callback?state=${state}`;+ await chrome.tabs.create({+ url: `${THREEWS_ORIGIN}/login?next=${encodeURIComponent(next)}`,+ });+ sendResponse({ ok: true });+ break;+ }+case 'set-avatar': {await chrome.storage.sync.set({ avatarId: msg.avatarId });broadcast({ type: 'walk:setAvatar', avatarId: msg.avatarId });@@ -215,7 +229,8 @@ chrome.tabs.onRemoved.addListener((tabId) => {});// ── Auth callback capture ─────────────────────────────────────────────────────-// The popup opens three.ws/login?next=/extension/auth-callback. After a+// The popup asks us to 'begin-signin', which opens three.ws/login with+// next=/extension/auth-callback?state=<one-time nonce>. After a// successful sign-in the site lands on /extension/auth-callback, which mints a// Bearer token (POST /api/auth/extension-token) and redirects to// /extension/auth-callback?token=<token>. We read the token out of that tab's@@ -226,16 +241,25 @@ chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {if (!tab.url.startsWith(THREEWS_ORIGIN + '/extension/auth-callback')) return;let token = null;+ let state = null;try {const u = new URL(tab.url);token = u.searchParams.get('token') || u.hash.replace(/^#token=/, '') || null;+ state = u.searchParams.get('state');} catch {token = null;}- if (!token) return;+ if (!token || !state) return;- chrome.storage.local.set({ threews_session: token }).then(() => {+ // Accept the token only for a sign-in this extension started: the state must+ // match the one-time value minted by 'begin-signin', and it is consumed here+ // so a replayed or attacker-supplied callback URL cannot swap the session.+ chrome.storage.session.get(AUTH_STATE_KEY).then(async (stored) => {+ const expected = stored[AUTH_STATE_KEY];+ if (!expected || expected !== state) return;+ await chrome.storage.session.remove(AUTH_STATE_KEY);+ await chrome.storage.local.set({ threews_session: token });chrome.runtime.sendMessage({ type: 'session-updated', token }).catch(() => {});chrome.tabs.remove(tabId).catch(() => {});- });+ }).catch(() => {});});diff --git a/extensions/walk-avatar/options.js b/extensions/walk-avatar/options.jsindex 159594000..0345bffdb 100644--- a/extensions/walk-avatar/options.js+++ b/extensions/walk-avatar/options.js@@ -44,9 +44,7 @@ async function apiFetch(path) {}function openLogin() {- chrome.tabs.create({- url: `${THREEWS}/login?next=${encodeURIComponent('/extension/auth-callback')}`,- });+ chrome.runtime.sendMessage({ type: 'begin-signin' }).catch(() => {});}// ── Toast ──────────────────────────────────────────────────────────────────────diff --git a/extensions/walk-avatar/popup.js b/extensions/walk-avatar/popup.jsindex 750197101..4e2b29521 100644--- a/extensions/walk-avatar/popup.js+++ b/extensions/walk-avatar/popup.js@@ -47,9 +47,7 @@ function msg(type, data = {}) {}function openLogin() {- chrome.tabs.create({- url: `${THREEWS}/login?next=${encodeURIComponent('/extension/auth-callback')}`,- });+ chrome.runtime.sendMessage({ type: 'begin-signin' }).catch(() => {});}function thumbUrl(av) {diff --git a/public/extension-auth-callback.html b/public/extension-auth-callback.htmlindex 3538da2f4..2c91635e8 100644--- a/public/extension-auth-callback.html+++ b/public/extension-auth-callback.html@@ -95,6 +95,13 @@// background worker is reading it from this very URL — just confirm// success and stop. (Prevents a re-mint/redirect loop.)var params = new URLSearchParams(location.search);+ var state = params.get('state') || '';+ // Keep the extension's one-time state across a sign-in round trip.+ var loginNext = encodeURIComponent('/extension/auth-callback' ++ (state ? '?state=' + encodeURIComponent(state) : ''));+ Array.prototype.forEach.call(document.querySelectorAll('a[href^="/login"]'), function (a) {+ a.setAttribute('href', '/login?next=' + loginNext);+ });if (params.get('token')) {show('success');// Best-effort auto-close once the background worker has captured it.@@ -119,7 +126,8 @@if (!data || !data.token) throw new Error('No token returned');// Hand the token to the extension's background worker by putting// it in the URL it is watching, then re-render as success.- location.replace('/extension/auth-callback?token=' + encodeURIComponent(data.token));+ location.replace('/extension/auth-callback?token=' + encodeURIComponent(data.token) ++ '&state=' + encodeURIComponent(state));} catch (e) {$('error-msg').textContent = (e && e.message)? ('Something went wrong: ' + e.message)diff --git a/tests/walk-extension-auth-state.test.js b/tests/walk-extension-auth-state.test.jsnew file mode 100644index 000000000..954a655df--- /dev/null+++ b/tests/walk-extension-auth-state.test.js@@ -0,0 +1,86 @@+// Walk Avatar extension: the auth-callback tab may only install a session token+// when it carries the one-time state minted by a sign-in the extension started.+import { describe, it, expect, beforeEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import vm from 'node:vm';++const root = join(dirname(fileURLToPath(import.meta.url)), '..');+const src = readFileSync(join(root, 'extensions/walk-avatar/background.js'), 'utf8');++function loadBackground() {+ const area = () => {+ const data = {};+ return {+ data,+ get: async (k) => {+ if (k == null) return { ...data };+ const keys = Array.isArray(k) ? k : [k];+ return Object.fromEntries(keys.filter((x) => x in data).map((x) => [x, data[x]]));+ },+ set: async (o) => Object.assign(data, o),+ remove: async (k) => [].concat(k).forEach((x) => delete data[x]),+ };+ };+ const listeners = { updated: [], message: [] };+ const created = [];+ const ev = (bucket) => ({ addListener: (fn) => bucket?.push(fn) });+ const chrome = {+ storage: { local: area(), session: area(), sync: area() },+ runtime: {+ onInstalled: ev(), onMessage: ev(listeners.message),+ sendMessage: () => Promise.resolve(),+ },+ tabs: {+ onUpdated: ev(listeners.updated), onRemoved: ev(),+ create: async (o) => { created.push(o); return { id: 99 }; },+ remove: async () => {},+ },+ commands: { onCommand: ev() },+ action: {},+ };+ const ctx = vm.createContext({ chrome, URL, console, crypto, btoa, fetch: () => {} });+ vm.runInContext(src, ctx);+ return { chrome, listeners, created };+}++const beginSignin = (l) =>+ new Promise((resolve) => {+ for (const fn of l.message) fn({ type: 'begin-signin' }, {}, resolve);+ });++const fire = async (l, url) => {+ for (const fn of l.updated) fn(7, { status: 'complete' }, { url });+ await new Promise((r) => setTimeout(r, 10));+};++describe('walk-avatar auth callback state binding', () => {+ let bg;+ beforeEach(() => { bg = loadBackground(); });++ it('ignores a callback token when no sign-in was started', async () => {+ await fire(bg.listeners, 'https://three.ws/extension/auth-callback?token=attacker');+ expect(bg.chrome.storage.local.data.threews_session).toBeUndefined();+ });++ it('ignores a callback token with a wrong state', async () => {+ await beginSignin(bg.listeners);+ await fire(bg.listeners, 'https://three.ws/extension/auth-callback?token=attacker&state=wrong');+ expect(bg.chrome.storage.local.data.threews_session).toBeUndefined();+ });++ it('accepts the token once with the matching state, then rejects replay', async () => {+ await beginSignin(bg.listeners);+ const login = new URL(bg.created[0].url);+ const next = new URL(login.searchParams.get('next'), 'https://three.ws');+ const state = next.searchParams.get('state');+ expect(state).toMatch(/^[A-Za-z0-9_-]{20,}$/);+ const cb = `https://three.ws/extension/auth-callback?token=good&state=${state}`;+ await fire(bg.listeners, cb);+ expect(bg.chrome.storage.local.data.threews_session).toBe('good');+ delete bg.chrome.storage.local.data.threews_session;+ await fire(bg.listeners, cb);+ expect(bg.chrome.storage.local.data.threews_session).toBeUndefined();+ });+});