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(oracle): require proof of Telegram chat control before follow and test alerts
nirholas2753f9403eda
diff --git a/api/_lib/oracle/verified-chat.js b/api/_lib/oracle/verified-chat.jsnew file mode 100644index 000000000..0a71a4199--- /dev/null+++ b/api/_lib/oracle/verified-chat.js@@ -0,0 +1,36 @@+/**+ * Proof of Telegram chat control for the Oracle alert endpoints.+ *+ * A Telegram private chat id equals the Telegram user id, and that id is+ * verified when an account links Telegram (widget HMAC or the /start deep-link+ * claimed by the bot webhook, see api/_lib/account-link/telegram-login.js).+ * So the only chat a signed-in user has proven to control is the subject of+ * their linked `telegram` identity.+ */++import { sql } from '../db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../auth.js';++export async function resolveUserId(req) {+ const session = await getSessionUser(req);+ if (session) return session.id;+ const bearer = await authenticateBearer(extractBearer(req));+ return bearer ? bearer.userId : null;+}++/** The chat id the user verified by linking Telegram, or null when none is linked. */+export async function verifiedTelegramChatId(userId) {+ const [row] = await sql`+ select subject from user_identities+ where user_id = ${userId} and provider = 'telegram'+ limit 1+ `;+ return row?.subject ? String(row.subject) : null;+}++export const UNVERIFIED_CHAT_MESSAGE =+ 'chat_id must be the Telegram chat you linked to your account (sign in with Telegram at /login first)';++export function escapeTelegramHtml(s) {+ return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+}diff --git a/api/oracle/follow.js b/api/oracle/follow.jsindex 867f924c0..56494b2da 100644--- a/api/oracle/follow.js+++ b/api/oracle/follow.js@@ -11,8 +11,11 @@* DELETE /api/oracle/follow { agent_id, chat_id }* → { ok: true }*- * No auth required: the Telegram chat_id is the caller-supplied identity.- * Rate-limited per IP and per (agent_id, chat_id) pair to prevent spam.+ * Auth: session cookie or bearer token, and chat_id must be the Telegram chat the+ * caller verified by linking Telegram to their account (their linked identity's+ * id, which is their private chat id). A caller-supplied chat_id alone proves+ * nothing, so without this anyone could unsubscribe or subscribe someone else.+ * Rate-limited per IP.** How the signals are delivered: when an armed Oracle agent makes a conviction* buy (in `workers/oracle/agent-loop.js`), the agent-loop calls@@ -24,6 +27,7 @@ import { cors, json, readJson, wrap, error, rateLimited } from '../_lib/http.js'import { limits, clientIp } from '../_lib/rate-limit.js';import { sql, isDbUnavailableError } from '../_lib/db.js';import { isUuid } from '../_lib/validate.js';+import { resolveUserId, verifiedTelegramChatId, UNVERIFIED_CHAT_MESSAGE } from '../_lib/oracle/verified-chat.js';const NETWORKS = new Set(['mainnet', 'devnet']);@@ -57,6 +61,22 @@ function asTrimmedString(v) {return typeof v === 'string' ? v.trim() : '';}+// Last trusted decision point for every verb: the caller must be signed in and+// chat_id must be the chat their linked Telegram identity proves they control.+async function requireOwnChat(req, res, chatId) {+ const userId = await resolveUserId(req);+ if (!userId) {+ error(res, 401, 'unauthorized', 'sign in to manage Oracle follows');+ return false;+ }+ const verified = await verifiedTelegramChatId(userId);+ if (!verified || verified !== chatId) {+ error(res, 403, 'forbidden', UNVERIFIED_CHAT_MESSAGE);+ return false;+ }+ return true;+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', origins: '*' })) return;const ip = clientIp(req);@@ -77,6 +97,7 @@ export default wrap(async (req, res) => {if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a UUID');if (!validateChatId(chatId)) return error(res, 400, 'validation_error', 'chat_id must be a numeric ID or @handle');+ if (!(await requireOwnChat(req, res, chatId))) return;const rows = await sql`select min_score from oracle_followers@@ -105,6 +126,7 @@ export default wrap(async (req, res) => {if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a UUID');if (!validateChatId(chatId)) return error(res, 400, 'validation_error', 'chat_id must be a numeric Telegram ID or @handle');+ if (!(await requireOwnChat(req, res, chatId))) return;// Ensure the agent exists (guard against phantom subscriptions)const agentRows = await sql`@@ -149,6 +171,7 @@ export default wrap(async (req, res) => {if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a UUID');if (!validateChatId(chatId)) return error(res, 400, 'validation_error', 'chat_id must be a numeric Telegram ID or @handle');+ if (!(await requireOwnChat(req, res, chatId))) return;// No `.catch()` swallow: this statement IS the response. Reporting// `{ ok: true }` on a delete that never ran leaves the follower subscribeddiff --git a/api/oracle/test-alert.js b/api/oracle/test-alert.jsindex 574270732..f71ff8240 100644--- a/api/oracle/test-alert.js+++ b/api/oracle/test-alert.js@@ -13,7 +13,7 @@*/import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { resolveUserId, verifiedTelegramChatId, escapeTelegramHtml, UNVERIFIED_CHAT_MESSAGE } from '../_lib/oracle/verified-chat.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';import { isUuid } from '../_lib/validate.js';@@ -21,14 +21,6 @@ import { isUuid } from '../_lib/validate.js';import { fetchUpstream } from '../_lib/upstream-fetch.js';const CHAT_ID_RE = /^-?\d{1,20}$|^@[A-Za-z0-9_]{3,32}$/;-async function resolveUserId(req) {- const session = await getSessionUser(req);- if (session) return session.id;- const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return bearer.userId;- return null;-}-export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;if (!method(req, res, ['POST'])) return;@@ -46,6 +38,10 @@ export default wrap(async (req, res) => {if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'invalid agent_id');if (!CHAT_ID_RE.test(chatId)) return error(res, 400, 'validation_error', 'chat_id must be a numeric ID or @handle');+ // The destination must be the chat the caller verified by linking Telegram.+ const verifiedChat = await verifiedTelegramChatId(userId);+ if (!verifiedChat || verifiedChat !== chatId) return error(res, 403, 'forbidden', UNVERIFIED_CHAT_MESSAGE);+// Verify ownership.const [agent] = await sql`select name from agent_identities@@ -61,7 +57,7 @@ export default wrap(async (req, res) => {const text = [`🔮 <b>Oracle alerts are working</b>`,``,- `<b>${agentName}</b> will send signals here when a coin crosses your conviction threshold.`,+ `<b>${escapeTelegramHtml(agentName)}</b> will send signals here when a coin crosses your conviction threshold.`,``,`<i>This is a test message from <a href="https://three.ws/oracle">three.ws Oracle</a>.</i>`,].join('\n');diff --git a/tests/oracle/api-db-outage.test.js b/tests/oracle/api-db-outage.test.jsindex f94ca9e54..3d703d2a8 100644--- a/tests/oracle/api-db-outage.test.js+++ b/tests/oracle/api-db-outage.test.js@@ -53,6 +53,13 @@ vi.mock('../../api/_lib/http.js', async () => {};});+// Follow now requires a signed-in caller whose linked Telegram identity is the+// chat_id; the outage tests below run as that caller (see VERIFIED_CHAT).+vi.mock('../../api/_lib/auth.js', async () => {+ const actual = await vi.importActual('../../api/_lib/auth.js');+ return { ...actual, getSessionUser: async () => ({ id: 'ab2aabd2-39f7-493b-8191-c9f174af62ab' }) };+});+vi.mock('../../api/_lib/rate-limit.js', () => ({limits: {publicIp: vi.fn(async () => ({ success: true })),@@ -213,6 +220,10 @@ describe('GET /api/oracle/agent-stats', () => {});describe('/api/oracle/follow', () => {+ // First read is the linked-identity lookup; the read under test comes after it.+ const VERIFIED_CHAT = [{ subject: '12345' }];+ beforeEach(() => { dbQueue = [VERIFIED_CHAT]; });+it('GET propagates a connectivity failure instead of reporting following: false', async () => {nextDbError = CONN_ERROR;await expect(follow(fakeReq(`/api/oracle/follow?agent_id=${AGENT_ID}&chat_id=12345`), fakeRes()))diff --git a/tests/oracle/chat-control-proof.test.js b/tests/oracle/chat-control-proof.test.jsnew file mode 100644index 000000000..a0f715ac5--- /dev/null+++ b/tests/oracle/chat-control-proof.test.js@@ -0,0 +1,120 @@+// Oracle follow and test-alert must bind chat_id to a Telegram chat the caller+// verified by linking Telegram, and test-alert must HTML-escape the agent name.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../../api/_lib/http.js', async () => {+ const actual = await vi.importActual('../../api/_lib/http.js');+ return {+ ...actual,+ wrap: (fn) => fn,+ cors: () => false,+ method: () => true,+ rateLimited: (res) => { res._rateLimited = true; },+ json: (res, status, body) => { res._json = { status, body }; return res; },+ error: (res, status, code, message) => {+ res._json = { status, body: { error: code, error_description: message } };+ return res;+ },+ readJson: async (req) => JSON.parse(req._rawBody),+ };+});++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ publicIp: async () => ({ success: true }),+ oracleFollowIp: async () => ({ success: true }),+ oracleTelegramTestIp: async () => ({ success: true }),+ },+ clientIp: () => '1.2.3.4',+}));++const USER_ID = 'ab2aabd2-39f7-493b-8191-c9f174af62ab';+const AGENT_ID = '5e05f68f-eead-4ef9-b6b4-fc85ea73bbe9';+let sessionUser = { id: USER_ID };+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: async () => sessionUser,+ authenticateBearer: async () => null,+ extractBearer: () => null,+}));++const queries = [];+let linkedSubject = '555';+vi.mock('../../api/_lib/db.js', () => ({+ sql: (strings) => {+ const q = strings.join('?');+ queries.push(q);+ if (q.includes('user_identities')) return Promise.resolve(linkedSubject ? [{ subject: linkedSubject }] : []);+ if (q.includes('agent_identities') && q.includes('name')) return Promise.resolve([{ name: '<a href="https://evil.example">Click</a>' }]);+ if (q.includes('agent_identities')) return Promise.resolve([{ id: AGENT_ID }]);+ return Promise.resolve([]);+ },+ isDbUnavailableError: () => false,+}));++const sent = [];+vi.mock('../../api/_lib/upstream-fetch.js', () => ({+ fetchUpstream: async (url, init) => {+ sent.push(JSON.parse(init.body));+ return { json: async () => ({ ok: true }) };+ },+}));++import follow from '../../api/oracle/follow.js';+import testAlert from '../../api/oracle/test-alert.js';++const res0 = () => ({ statusCode: 200, _headers: {}, setHeader() {}, getHeader() {}, end() {} });+const req = (method, body, url = '/api/oracle/follow') => ({+ method, url, headers: { host: 'three.ws' }, _rawBody: JSON.stringify(body || {}), on() {},+});++beforeEach(() => {+ queries.length = 0; sent.length = 0;+ sessionUser = { id: USER_ID };+ linkedSubject = '555';+ process.env.TELEGRAM_BOT_TOKEN = 't';+});++describe('oracle follow proof of chat control', () => {+ it('rejects an anonymous subscribe', async () => {+ sessionUser = null;+ const res = res0();+ await follow(req('POST', { agent_id: AGENT_ID, chat_id: '999' }), res);+ expect(res._json.status).toBe(401);+ expect(queries.some((q) => q.includes('insert into oracle_followers'))).toBe(false);+ });+ it('rejects an anonymous unsubscribe', async () => {+ sessionUser = null;+ const res = res0();+ await follow(req('DELETE', { agent_id: AGENT_ID, chat_id: '999' }), res);+ expect(res._json.status).toBe(401);+ expect(queries.some((q) => q.includes('delete from oracle_followers'))).toBe(false);+ });+ it('rejects a chat_id other than the caller verified chat', async () => {+ const res = res0();+ await follow(req('DELETE', { agent_id: AGENT_ID, chat_id: '999' }), res);+ expect(res._json.status).toBe(403);+ expect(queries.some((q) => q.includes('delete from oracle_followers'))).toBe(false);+ });+ it('allows the verified chat', async () => {+ const res = res0();+ await follow(req('POST', { agent_id: AGENT_ID, chat_id: '555' }), res);+ expect(res._json.status).toBe(201);+ });+});++describe('oracle test-alert', () => {+ it('refuses a chat_id the caller has not verified', async () => {+ const res = res0();+ await testAlert(req('POST', { agent_id: AGENT_ID, chat_id: '999' }, '/api/oracle/test-alert'), res);+ expect(res._json.status).toBe(403);+ expect(sent.length).toBe(0);+ });+ it('escapes the agent name in the HTML message', async () => {+ const res = res0();+ await testAlert(req('POST', { agent_id: AGENT_ID, chat_id: '555' }, '/api/oracle/test-alert'), res);+ expect(sent.length).toBe(1);+ expect(sent[0].text).not.toContain('<a href="https://evil.example">');+ expect(sent[0].text).toContain('<a href="https://evil.example">');+ });+});