Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(security): require operator authority for Telegram config and bridge lifecycle

Adam Eivy751bb67e4ae2
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 7a7ff9d22e..c82b4f63b5 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -188,6 +188,16 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
'POST /api/x/accounts/:id/open',
'POST /api/x/accounts/:id/sync',
+ // Telegram bot configuration, testing and bridge lifecycle execute host
+ // processes, register bots, or authorize remote command execution and
+ // notification forwarding (#11431). Reads remain open.
+ 'PUT /api/telegram/config',
+ 'DELETE /api/telegram/config',
+ 'PUT /api/telegram/method',
+ 'POST /api/telegram/test',
+ 'PUT /api/telegram/forward-types',
+ 'POST /api/telegram/bridge/reload',
+
// Sending a draft performs an external mail side effect as the operator (#11273).
'POST /api/messages/drafts/:id/send',
@@ -960,6 +970,7 @@ export const HOST_CONTROL_SETTINGS_SLICES = Object.freeze([
'credentialBootstraps',
'harnesses',
'seriesAutopilot',
+ 'telegram',
'untrustedContent',
'voice',
]);
diff --git a/server/lib/hostControlRoutes.test.js b/server/lib/hostControlRoutes.test.js
index 5389233bcc..8de4b9eafb 100644
--- a/server/lib/hostControlRoutes.test.js
+++ b/server/lib/hostControlRoutes.test.js
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { getApiRouteCatalog } from './apiRouteGraph.js';
import {
- HOST_CONTROL_ROUTES, changedVoiceConfigHostControlPaths, hostControlBodyKeys, hostControlSettingsPathsIn,
+ HOST_CONTROL_ROUTES, HOST_CONTROL_SETTINGS_SLICES, changedVoiceConfigHostControlPaths, hostControlBodyKeys, hostControlSettingsPathsIn,
hostControlRouteFor, isHostControlRoute, voiceConfigHostControlPathsIn,
} from './hostControlRoutes.js';
import { LLM_DRILL_TYPES } from './postDrillTypes.js';
@@ -1023,3 +1023,19 @@ describe('Media process execution policy', () => {
]) expect(isHostControlRoute(method, path), `${method} ${path}`).toBe(false);
});
});
+
+describe('Telegram bot and bridge authority policy (#11431)', () => {
+ it('gates every mutating Telegram route while keeping status open', () => {
+ const mutations = getApiRouteCatalog().routes.filter(({ method, path }) =>
+ /^(POST|PUT|PATCH|DELETE)$/.test(method) && /^\/api\/telegram(\/|$)/.test(path));
+ expect(mutations.length).toBe(6);
+ for (const { method, path } of mutations) {
+ expect(isHostControlRoute(method, path), `${method} ${path} should be gated`).toBe(true);
+ }
+ expect(isHostControlRoute('GET', '/api/telegram/status')).toBe(false);
+ });
+
+ it('includes telegram in HOST_CONTROL_SETTINGS_SLICES', () => {
+ expect(HOST_CONTROL_SETTINGS_SLICES).toContain('telegram');
+ });
+});
diff --git a/server/routes/hostControlTelegram.test.js b/server/routes/hostControlTelegram.test.js
new file mode 100644
index 0000000000..2b36df715f
--- /dev/null
+++ b/server/routes/hostControlTelegram.test.js
@@ -0,0 +1,241 @@
+import { EventEmitter } from 'node:events';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';
+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-telegram-authority-') }));
+afterAll(cleanupTempDataRoots);
+
+const auth = vi.hoisted(() => ({ enabled: false }));
+vi.mock('../services/auth.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ isAuthEnabled: vi.fn(async () => auth.enabled),
+ verifyPassword: vi.fn(async () => true),
+}));
+
+let currentSettings = {
+ telegram: { method: 'manual', chatId: '12345678', forwardTypes: ['health_issue'] },
+ secrets: { telegram: { token: 'existing-secret-token' } },
+};
+
+vi.mock('../services/settings.js', () => ({
+ settingsEvents: new EventEmitter(),
+ getSettings: vi.fn(async () => currentSettings),
+ updateSettingsWith: vi.fn(async (updater) => {
+ currentSettings = updater(currentSettings);
+ return currentSettings;
+ }),
+}));
+
+vi.mock('../services/instanceIdentity.js', () => ({
+ loadData: vi.fn(async () => ({ peers: [{
+ id: 'example-peer', instanceId: 'example-instance', enabled: true, syncSecret: 'a'.repeat(32),
+ }] })),
+}));
+
+const telegramEffects = vi.hoisted(() => ({
+ init: vi.fn(async () => {}),
+ getStatus: vi.fn(() => ({ connected: true, botUsername: 'PortOS_bot' })),
+ cleanup: vi.fn(async () => {}),
+ sendMessage: vi.fn(async () => ({ success: true })),
+ updateCachedForwardTypes: vi.fn(),
+}));
+vi.mock('../services/telegram.js', () => telegramEffects);
+
+const bridgeEffects = vi.hoisted(() => ({
+ init: vi.fn(async () => true),
+ getStatus: vi.fn(() => ({ connected: true, hasBotToken: true, hasChatId: true, bridgeStatus: 'connected' })),
+ cleanup: vi.fn(async () => {}),
+ sendMessage: vi.fn(async () => ({ success: true })),
+ updateCachedForwardTypes: vi.fn(),
+ reload: vi.fn(async () => {}),
+}));
+vi.mock('../services/telegramBridge.js', () => bridgeEffects);
+
+import { authGate, hostControlRouteGate, hostControlBodyGate } from '../services/authGate.js';
+import { createSession } from '../services/auth.js';
+import telegramRoutes from './telegram.js';
+
+const appFor = (address = '192.0.2.10') => {
+ const app = express();
+ app.use((req, _res, next) => {
+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });
+ next();
+ });
+ app.use(authGate, hostControlRouteGate, express.json(), hostControlBodyGate);
+ app.use('/api/telegram', telegramRoutes);
+ const settingsRouter = express.Router();
+ settingsRouter.put('/', (req, res) => {
+ currentSettings = { ...currentSettings, ...req.body };
+ res.json({ saved: true });
+ });
+ settingsRouter.patch('/slice', (req, res) => {
+ if (req.body?.slicePath) {
+ currentSettings = { ...currentSettings, [req.body.slicePath]: req.body.partial };
+ }
+ res.json({ saved: true });
+ });
+ app.use('/api/settings', settingsRouter);
+ app.use(errorMiddleware);
+ return app;
+};
+
+const call = (app, [method, path, body = {}], headers = {}) => {
+ const pending = request(app)[method.toLowerCase()](`/api/telegram${path}`);
+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);
+ return pending.send(body);
+};
+
+const mutatingOperations = [
+ ['PUT', '/config', { token: 'new-token', chatId: '87654321' }],
+ ['DELETE', '/config', {}],
+ ['PUT', '/method', { method: 'mcp-bridge' }],
+ ['POST', '/test', { message: 'Test message' }],
+ ['PUT', '/forward-types', { forwardTypes: ['agent_warning'] }],
+ ['POST', '/bridge/reload', {}],
+];
+
+describe('Telegram bot, bridge and settings operator authority (#11431)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ auth.enabled = false;
+ currentSettings = {
+ telegram: { method: 'manual', chatId: '12345678', forwardTypes: ['health_issue'] },
+ secrets: { telegram: { token: 'existing-secret-token' } },
+ };
+ });
+
+ it.each([
+ ['remote without auth', false, '192.0.2.10', {}, 403, 'HOST_CONTROL_FORBIDDEN'],
+ ['forwarded remote without auth', false, '127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }, 403, 'HOST_CONTROL_FORBIDDEN'],
+ ['anonymous with auth', true, '192.0.2.10', {}, 401, 'AUTH_REQUIRED'],
+ ['Basic password', true, '192.0.2.10', { Authorization: `Basic ${Buffer.from(':example-password').toString('base64')}` }, 403, 'HOST_CONTROL_FORBIDDEN'],
+ ['scoped peer', true, '192.0.2.10', {
+ [PEER_AUTH_HEADER]: derivePeerAuthToken('a'.repeat(32), 'example-instance'),
+ [PEER_INSTANCE_HEADER]: 'example-instance',
+ }, 403, 'PEER_SCOPE_FORBIDDEN'],
+ ])('refuses %s for all mutating Telegram routes', async (_name, enabled, address, headers, status, code) => {
+ auth.enabled = enabled;
+ const app = appFor(address);
+
+ for (const op of mutatingOperations) {
+ const response = await call(app, op, headers);
+ expect(response.status, `${op[0]} ${op[1]}: ${JSON.stringify(response.body)}`).toBe(status);
+ expect(response.body.code).toBe(code);
+ }
+
+ expect(telegramEffects.init).not.toHaveBeenCalled();
+ expect(telegramEffects.cleanup).not.toHaveBeenCalled();
+ expect(telegramEffects.sendMessage).not.toHaveBeenCalled();
+ expect(bridgeEffects.init).not.toHaveBeenCalled();
+ expect(bridgeEffects.cleanup).not.toHaveBeenCalled();
+ expect(bridgeEffects.sendMessage).not.toHaveBeenCalled();
+ expect(bridgeEffects.reload).not.toHaveBeenCalled();
+ });
+
+ it('protects Express case and trailing-slash aliases', async () => {
+ const app = appFor();
+
+ const config = await request(app).put('/API/TELEGRAM/CONFIG/').send({ token: 'new-token', chatId: '87654321' });
+ const del = await request(app).delete('/API/TELEGRAM/CONFIG/');
+ const method = await request(app).put('/API/TELEGRAM/METHOD/').send({ method: 'mcp-bridge' });
+ const test = await request(app).post('/API/TELEGRAM/TEST/').send({ message: 'test' });
+ const forward = await request(app).put('/API/TELEGRAM/FORWARD-TYPES/').send({ forwardTypes: ['agent_warning'] });
+ const reload = await request(app).post('/API/TELEGRAM/BRIDGE/RELOAD/');
+
+ expect(config.status).toBe(403);
+ expect(del.status).toBe(403);
+ expect(method.status).toBe(403);
+ expect(test.status).toBe(403);
+ expect(forward.status).toBe(403);
+ expect(reload.status).toBe(403);
+
+ expect(telegramEffects.init).not.toHaveBeenCalled();
+ expect(telegramEffects.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['local', '127.0.0.1'],
+ ['operator session', '192.0.2.10'],
+ ['delegated agent', '127.0.0.1'],
+ ])('preserves %s Telegram operations', async (principal, address) => {
+ const headers = {};
+ if (principal !== 'local') {
+ const session = await createSession({ label: principal === 'delegated agent' ? 'agent' : 'operator' });
+ auth.enabled = true;
+ if (principal === 'delegated agent') headers.Authorization = `Bearer ${session.token}`;
+ else headers.Cookie = `portos_auth=${session.token}`;
+ }
+ const app = appFor(address);
+
+ const configRes = await call(app, ['PUT', '/config', { token: 'new-token', chatId: '87654321' }], headers);
+ expect(configRes.status).toBe(200);
+ expect(telegramEffects.init).toHaveBeenCalled();
+
+ const testRes = await call(app, ['POST', '/test', { message: 'Hello from test' }], headers);
+ expect(testRes.status).toBe(200);
+ expect(telegramEffects.sendMessage).toHaveBeenCalledWith('Hello from test');
+
+ const forwardRes = await call(app, ['PUT', '/forward-types', { forwardTypes: ['agent_warning'] }], headers);
+ expect(forwardRes.status).toBe(200);
+
+ const methodRes = await call(app, ['PUT', '/method', { method: 'mcp-bridge' }], headers);
+ expect(methodRes.status).toBe(200);
+ expect(bridgeEffects.init).toHaveBeenCalled();
+
+ const reloadRes = await call(app, ['POST', '/bridge/reload', {}], headers);
+ expect(reloadRes.status).toBe(200);
+ expect(bridgeEffects.reload).toHaveBeenCalled();
+
+ const deleteRes = await call(app, ['DELETE', '/config', {}], headers);
+ expect(deleteRes.status).toBe(200);
+ expect(bridgeEffects.cleanup).toHaveBeenCalled();
+ });
+
+ it('keeps remote reads available without granting execution or config mutation', async () => {
+ const app = appFor();
+
+ const status = await request(app).get('/api/telegram/status');
+ expect(status.status).toBe(200);
+ expect(status.body.hasToken).toBe(true);
+ expect(status.body.hasChatId).toBe(true);
+ expect(status.body.method).toBe('manual');
+
+ expect(telegramEffects.init).not.toHaveBeenCalled();
+ expect(telegramEffects.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('gates the telegram slice on PUT /api/settings and PATCH /api/settings/slice', async () => {
+ const remoteApp = appFor('192.0.2.10');
+
+ const putRemote = await request(remoteApp).put('/api/settings').send({ telegram: { chatId: 'attacker-chat' } });
+ expect(putRemote.status).toBe(403);
+ expect(putRemote.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+
+ const patchRemote = await request(remoteApp).patch('/api/settings/slice').send({
+ slicePath: 'telegram',
+ partial: { chatId: 'attacker-chat' },
+ });
+ expect(patchRemote.status).toBe(403);
+ expect(patchRemote.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+
+ // Safe / non-host-control slice stays open to remote callers
+ const safePut = await request(remoteApp).put('/api/settings').send({ location: { city: 'Test' } });
+ expect(safePut.status).toBe(200);
+
+ const localApp = appFor('127.0.0.1');
+ const putLocal = await request(localApp).put('/api/settings').send({ telegram: { chatId: 'local-chat' } });
+ expect(putLocal.status).toBe(200);
+
+ const patchLocal = await request(localApp).patch('/api/settings/slice').send({
+ slicePath: 'telegram',
+ partial: { chatId: 'local-chat-2' },
+ });
+ expect(patchLocal.status).toBe(200);
+ });
+});
diff --git a/server/routes/telegram.js b/server/routes/telegram.js
index f9e9df9e58..3fc6eaf4c2 100644
--- a/server/routes/telegram.js
+++ b/server/routes/telegram.js
@@ -46,6 +46,10 @@ router.get('/status', asyncHandler(async (req, res) => {
}
}));
+// Telegram bot configuration, testing and bridge lifecycle execute host
+// processes, register bots, or authorize remote command execution and
+// notification forwarding. All mutating routes require operator authority via
+// the central host-control gate.
// PUT /api/telegram/method
router.put('/method', asyncHandler(async (req, res) => {
const { method } = validateRequest(telegramMethodSchema, req.body);