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(studio): keep room owner keys server-side and verify the Discord activity token audience
nirholas1c3b47da0789
diff --git a/api/_lib/gateway/discord-activity-auth.js b/api/_lib/gateway/discord-activity-auth.jsindex 2532ea3c5..9d57acdeb 100644--- a/api/_lib/gateway/discord-activity-auth.js+++ b/api/_lib/gateway/discord-activity-auth.js@@ -10,7 +10,7 @@ import { createHmac, timingSafeEqual } from 'node:crypto';import { env } from '../env.js';const DISCORD_TOKEN_URL = 'https://discord.com/api/oauth2/token';-const DISCORD_USER_URL = 'https://discord.com/api/users/@me';+const DISCORD_TOKEN_INFO_URL = 'https://discord.com/api/oauth2/@me';const SESSION_TTL_S = 4 * 3600;export function discordActivityConfigured() {@@ -49,15 +49,23 @@ export async function exchangeActivityCode(code) {return { accessToken: data.access_token, scope: data.scope || null };}-/** Verify an access token is real by asking Discord who it belongs to. */+/**+ * Verify an access token is real AND was issued to this Discord application, by+ * asking Discord who it belongs to. /oauth2/@me reports the token's application,+ * so a token minted for any other app is refused.+ */export async function fetchDiscordUser(accessToken) {if (typeof accessToken !== 'string' || !accessToken) throw new DiscordActivityAuthError('bad_token', 'access_token is required', 400);- const resp = await fetch(DISCORD_USER_URL, { headers: { Authorization: `Bearer ${accessToken}` }, signal: AbortSignal.timeout(8000) });+ const resp = await fetch(DISCORD_TOKEN_INFO_URL, { headers: { Authorization: `Bearer ${accessToken}` }, signal: AbortSignal.timeout(8000) });const data = await resp.json().catch(() => null);- if (!resp.ok || !data?.id) {+ if (!resp.ok || !data?.user?.id) {throw new DiscordActivityAuthError('user_fetch_failed', data?.message || 'Discord rejected the access token', 502);}- return { id: String(data.id), username: data.username, globalName: data.global_name || null, avatar: data.avatar || null };+ if (String(data.application?.id || '') !== process.env.DISCORD_CLIENT_ID) {+ throw new DiscordActivityAuthError('wrong_audience', 'access token was not issued to this application', 401);+ }+ const u = data.user;+ return { id: String(u.id), username: u.username, globalName: u.global_name || null, avatar: u.avatar || null };}function sign(payload) {diff --git a/api/gateway/discord-activity-session.js b/api/gateway/discord-activity-session.jsindex a968e8646..7167e4c48 100644--- a/api/gateway/discord-activity-session.js+++ b/api/gateway/discord-activity-session.js@@ -3,7 +3,7 @@// access_token discordSdk.commands.authenticate() returned plus the instance's// guild/channel/instance ids (all from discordSdk.instanceId etc., never// trusted as identity on their own); this handler re-checks the token against-// Discord's own /users/@me before minting anything, so a forged client claim+// Discord's own /oauth2/@me before minting anything, so a forged client claim// can never seat an impostor in someone else's room.import { cors, json, method, error, readJson, wrap } from '../_lib/http.js';@@ -34,7 +34,12 @@ export default wrap(async (req, res) => {throw e;}- await ensureRoom({ roomId: instanceId, guildId, channelId });+ // An instance id is bound to the guild/channel it was first seen with; a later+ // request claiming the same id under another guild or channel is a squat.+ const room = await ensureRoom({ roomId: instanceId, guildId, channelId });+ if (String(room.guild_id) !== guildId || String(room.channel_id) !== channelId) {+ return error(res, 403, 'room_mismatch', 'this instance belongs to a different guild or channel');+ }await upsertParticipant({ roomId: instanceId, discordUserId: user.id, username: user.username, globalName: user.globalName });await appendEvent({ roomId: instanceId, kind: 'join', actorDiscordId: user.id, payload: { username: user.username } });diff --git a/multiplayer/src/rooms/StudioRoom.js b/multiplayer/src/rooms/StudioRoom.jsindex 9b7265e67..b4f2e8732 100644--- a/multiplayer/src/rooms/StudioRoom.js+++ b/multiplayer/src/rooms/StudioRoom.js@@ -13,6 +13,7 @@// yawDeg) — see studio-schemas.js. The client maps them to its own local floor,// or, when co-located via a QR marker, to the same physical spot.+import { createHash } from 'node:crypto';import { Room } from '@colyseus/core';import { StudioModel, StudioViewer, StudioState } from '../studio-schemas.js';@@ -62,6 +63,9 @@ export class StudioRoom extends Room {this._modelSeq = 0;// Per-session op-rate ledger: sessionId → { windowStart, count }.this._opLedger = new Map();+ // modelId -> private owner key. The key is the client's bearer id and is+ // never synced; peers only ever see ownerHandle(key).+ this._modelOwners = new Map();}onCreate(options) {@@ -104,6 +108,21 @@ export class StudioRoom extends Room {return client.userData?.ownerId || client.sessionId;}+ // Public, one-way handle for an owner key. Synced state carries this, never+ // the key, so a peer cannot replay what it reads as its own clientId.+ _ownerHandle(key) {+ return createHash('sha256').update(`${this.roomKey}\0${key}`).digest('hex').slice(0, 24);+ }++ _owners() {+ return (this._modelOwners ||= new Map());+ }++ _ownsModel(client, modelId) {+ const key = this._owners().get(modelId);+ return key !== undefined && key === this._ownerKey(client);+ }+// Token-bucket-ish per-second op gate. Returns false (drop) when a client// exceeds OPS_PER_SEC in the current 1 s window — a flood can't spam the room._opOk(sessionId) {@@ -131,7 +150,7 @@ export class StudioRoom extends Room {}const owner = this._ownerKey(client);let owned = 0;- for (const [, m] of this.state.models) if (m.ownerId === owner) owned++;+ for (const [, key] of this._owners()) if (key === owner) owned++;if (owned >= MAX_MODELS_PER_OWNER) {client.send('model:reject', { reason: 'owner_full' });return;@@ -150,8 +169,9 @@ export class StudioRoom extends Room {m.yawDeg = ((num(payload.yawDeg) % 360) + 360) % 360;m.scale = clamp(num(payload.scale, 1), SCALE_MIN, SCALE_MAX);m.height = clamp(num(payload.height, 0), 0, 20);- m.ownerId = owner;+ m.ownerId = this._ownerHandle(owner);m.ts = Date.now();+ this._owners().set(m.id, owner);this.state.models.set(m.id, m);}@@ -160,7 +180,7 @@ export class StudioRoom extends Room {if (!payload || typeof payload.id !== 'string') return;const m = this.state.models.get(payload.id);if (!m) return;- if (m.ownerId !== this._ownerKey(client)) return; // owner-only moves+ if (!this._ownsModel(client, payload.id)) return; // owner-only movesif (Number.isFinite(payload.relEast)) m.relEast = clamp(payload.relEast, -COORD_BOUND, COORD_BOUND);if (Number.isFinite(payload.relNorth)) m.relNorth = clamp(payload.relNorth, -COORD_BOUND, COORD_BOUND);if (Number.isFinite(payload.yawDeg)) m.yawDeg = ((payload.yawDeg % 360) + 360) % 360;@@ -173,8 +193,9 @@ export class StudioRoom extends Room {if (!payload || typeof payload.id !== 'string') return;const m = this.state.models.get(payload.id);if (!m) return;- if (m.ownerId !== this._ownerKey(client)) return; // owner-only removes+ if (!this._ownsModel(client, payload.id)) return; // owner-only removesthis.state.models.delete(payload.id);+ this._owners().delete(payload.id);}_handleHeartbeat(client) {@@ -193,9 +214,10 @@ export class StudioRoom extends Room {const v = new StudioViewer();v.id = client.sessionId;v.name = String(options?.name || '').slice(0, STR_MAX);- v.ownerId = client.userData.ownerId;+ v.ownerId = this._ownerHandle(this._ownerKey(client));v.tsServer = Date.now();this.state.viewers.set(client.sessionId, v);+ client.send('self', { ownerId: v.ownerId });console.log(`${this._tag()} +join (viewers=${this.state.viewers.size}, models=${this.state.models.size})`);}@@ -220,6 +242,7 @@ export class StudioRoom extends Room {onDispose() {this._opLedger.clear();+ this._owners().clear();console.log(`${this._tag()} disposed`);}}diff --git a/packages/ar-studio/src/studio/net.js b/packages/ar-studio/src/studio/net.jsindex d60ad8634..555102f7d 100644--- a/packages/ar-studio/src/studio/net.js+++ b/packages/ar-studio/src/studio/net.js@@ -94,6 +94,7 @@ export class StudioNet {this._destroyed = false;this._presenceQueued = false;this._modelsQueued = false;+ this._selfHandle = '';}/** Subscribe: 'status' | 'models' | 'model' | 'presence' | 'reject'. */@@ -168,6 +169,10 @@ export class StudioNet {$viewers.onRemove(() => this._queuePresence());}+ this.room.onMessage('self', (msg) => {+ this._selfHandle = String(msg?.ownerId || '');+ this._queueModels();+ });this.room.onMessage('model:reject', (msg) => this._emit('reject', msg));this.room.onLeave((code) => {if (this._destroyed || code === 1000) return;@@ -209,7 +214,7 @@ export class StudioNet {scale: m.scale,height: m.height,ownerId: m.ownerId,- mine: !!this.clientId && m.ownerId === this.clientId,+ mine: !!this._selfHandle && m.ownerId === this._selfHandle,};}diff --git a/tests/discord-activity-auth.test.js b/tests/discord-activity-auth.test.jsindex 1e351c90e..940563c23 100644--- a/tests/discord-activity-auth.test.js+++ b/tests/discord-activity-auth.test.js@@ -57,15 +57,20 @@ describe('discord-activity-auth', () => {expect(fetchSpy).not.toHaveBeenCalled();});- it('fetchDiscordUser re-verifies the token against /users/@me', async () => {- fetchSpy.mockResolvedValue({ ok: true, json: async () => ({ id: '123456789', username: 'alice', global_name: 'Alice', avatar: 'abc' }) });+ it('fetchDiscordUser re-verifies the token against /oauth2/@me and returns the user', async () => {+ fetchSpy.mockResolvedValue({ ok: true, json: async () => ({ application: { id: 'test-client-id' }, user: { id: '123456789', username: 'alice', global_name: 'Alice', avatar: 'abc' } }) });const user = await fetchDiscordUser('tok-123');expect(user).toEqual({ id: '123456789', username: 'alice', globalName: 'Alice', avatar: 'abc' });const [url, init] = fetchSpy.mock.calls[0];- expect(url).toBe('https://discord.com/api/users/@me');+ expect(url).toBe('https://discord.com/api/oauth2/@me');expect(init.headers.Authorization).toBe('Bearer tok-123');});+ it('fetchDiscordUser rejects a token issued to a different Discord application', async () => {+ fetchSpy.mockResolvedValue({ ok: true, json: async () => ({ application: { id: 'some-other-app' }, user: { id: '123456789', username: 'alice' } }) });+ await expect(fetchDiscordUser('foreign-app-token')).rejects.toMatchObject({ code: 'wrong_audience', status: 401 });+ });+it('fetchDiscordUser surfaces a rejected token as a DiscordActivityAuthError', async () => {fetchSpy.mockResolvedValue({ ok: false, json: async () => ({ message: '401: Unauthorized' }) });await expect(fetchDiscordUser('expired')).rejects.toBeInstanceOf(DiscordActivityAuthError);diff --git a/tests/discord-activity-session-binding.test.js b/tests/discord-activity-session-binding.test.jsnew file mode 100644index 000000000..98382d8f1--- /dev/null+++ b/tests/discord-activity-session-binding.test.js@@ -0,0 +1,73 @@+// POST /api/gateway/discord-activity-session: an instance id that already+// belongs to one guild/channel must not mint a session for a different one.+// Only the room store is stubbed (offline); Discord's endpoint is a fetch spy and+// the session signing is real.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { Readable } from 'node:stream';++process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret';+process.env.DISCORD_CLIENT_ID = 'test-client-id';+process.env.DISCORD_CLIENT_SECRET = 'test-client-secret';++const store = vi.hoisted(() => ({ room: null, participants: 0, events: 0 }));+vi.mock('../api/_lib/gateway/discord-activity-store.js', () => ({+ ensureRoom: async ({ roomId, guildId, channelId }) => {+ store.room ||= { id: roomId, guild_id: guildId, channel_id: channelId };+ return store.room;+ },+ upsertParticipant: async () => { store.participants++; },+ appendEvent: async () => { store.events++; },+}));++const { default: handler } = await import('../api/gateway/discord-activity-session.js');++function mockRes() {+ return {+ statusCode: 200, _headers: {}, _body: '',+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++async function post(body) {+ const req = Readable.from([Buffer.from(JSON.stringify(body))]);+ req.method = 'POST';+ req.url = '/api/gateway/discord-activity-session';+ req.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json' };+ const res = mockRes();+ await handler(req, res);+ return { status: res.statusCode, body: res.json };+}++describe('discord-activity-session room binding', () => {+ let fetchSpy;+ beforeEach(() => {+ store.room = null; store.participants = 0; store.events = 0;+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ ok: true,+ json: async () => ({ application: { id: 'test-client-id' }, user: { id: '42', username: 'eve' } }),+ });+ });+ afterEach(() => fetchSpy.mockRestore());++ const base = { instance_id: 'inst-1', guild_id: '111', channel_id: '222', access_token: 't' };++ it('mints a session for the guild/channel the room was created with', async () => {+ expect((await post(base)).status).toBe(200);+ expect((await post(base)).status).toBe(200);+ });++ it('refuses a session for an existing instance id claimed under another guild or channel', async () => {+ await post(base);+ const squat = await post({ ...base, guild_id: '999', channel_id: '888' });+ expect(squat.status).toBe(403);+ expect(squat.body.session_token).toBeUndefined();+ expect(store.participants).toBe(1);+ expect(store.events).toBe(1);+ });+});diff --git a/tests/studio-room.test.js b/tests/studio-room.test.jsindex 73ecc0195..8c2d417ff 100644--- a/tests/studio-room.test.js+++ b/tests/studio-room.test.js@@ -49,7 +49,7 @@ describe('StudioRoom — model:spawn', () => {expect(room.state.models.size).toBe(1);const m = [...room.state.models.values()][0];expect(m.src).toBe(HTTPS);- expect(m.ownerId).toBe('alice'); // stable owner key, not sessionId+ expect(m.ownerId).toBe(room._ownerHandle('alice')); // stable owner handle, not the raw keyexpect(m.relEast).toBe(1);expect(m.scale).toBe(1.5);});@@ -147,3 +147,29 @@ describe('StudioRoom — rate limiting', () => {expect(room.state.models.size).toBe(0); // rate-limited before any write});});++describe('StudioRoom - owner key is never published', () => {+ it('syncs an opaque owner handle, so a peer cannot replay it as a clientId', () => {+ const room = makeRoom();+ const alice = makeClient(room, { sessionId: 's_a', ownerId: 'alice-secret' });+ const mallory = makeClient(room, { sessionId: 's_m', ownerId: 'mallory' });+ join(room, alice); join(room, mallory);+ room._handleSpawn(alice, { src: HTTPS, relEast: 0, relNorth: 0, id: 'M1' });+ const published = room.state.models.get('M1').ownerId;+ expect(published).not.toBe('alice-secret');++ // Mallory rejoins asserting the value she read from synced state.+ const replay = makeClient(room, { sessionId: 's_r', ownerId: published });+ join(room, replay);+ room._handleUpdate(replay, { id: 'M1', relEast: 9 });+ expect(room.state.models.get('M1').relEast).toBe(0);+ room._handleRemove(replay, { id: 'M1' });+ expect(room.state.models.has('M1')).toBe(true);++ // The real owner (same secret, new session) still controls the model.+ const aliceAgain = makeClient(room, { sessionId: 's_a2', ownerId: 'alice-secret' });+ join(room, aliceAgain);+ room._handleUpdate(aliceAgain, { id: 'M1', relEast: 4 });+ expect(room.state.models.get('M1').relEast).toBe(4);+ });+});