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: require operator authority for Quota Burn and shell images (#9030)

[._.]/ Adam Eivyba5cbf9f59b5
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index d3420a1945..f048f37226 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -171,6 +171,24 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
'POST /api/cos/schedule/maintenance-runs/:id/resume',
'POST /api/cos/tools/call',
+ // Quota Burn (#9030): PUT accepts the legacy agent-prompt compatibility shape
+ // and converts it into an enabled, autonomyLevel-yolo custom CoS job — the
+ // same "arbitrary prompt becomes unattended work" shape as `POST /api/cos/jobs`
+ // above, just reached through a different entry point. `run` dispatches a
+ // family or a named job immediately, past the master switch and (with
+ // `force`) the family's own quota gates. `rearm` re-arms an already-configured
+ // one-shot step for another cycle — it queues no new prompt, but it puts spent
+ // work back into rotation the operator meant to run once.
+ 'PUT /api/quota-burn',
+ 'POST /api/quota-burn/run',
+ 'POST /api/quota-burn/rearm',
+
+ // Shell image drop (#9030): the HTTP twin of the gated `shell:input` socket
+ // event (HOST_CONTROL_SOCKET_EVENTS in services/socket.js) — it pastes the
+ // caller's message into a live PTY and submits it, driving whatever agent or
+ // shell that session is running.
+ 'POST /api/shell/sessions/:sessionId/image',
+
// Git in a caller-named directory. Every POST is gated, reads included: git
// runs repository-configured programs (hooks, fsmonitor) even for `status`.
'POST /api/git/*rest',
diff --git a/server/routes/quotaBurn.test.js b/server/routes/quotaBurn.test.js
index 6686b4d708..ef79a97146 100644
--- a/server/routes/quotaBurn.test.js
+++ b/server/routes/quotaBurn.test.js
@@ -1,8 +1,35 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
+import { EventEmitter } from 'node:events';
+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';
+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';
+import { authGate, hostControlRouteGate, hostControlBodyGate } from '../services/authGate.js';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
+// Real authorization middleware; only credential/settings stores are synthetic.
+const auth = vi.hoisted(() => ({
+ isAuthEnabled: vi.fn(),
+ verifyPassword: vi.fn(async password => password === 'example-password'),
+ verifyRequestSession: vi.fn(async req => req.headers.authorization === 'Bearer example-session'),
+}));
+vi.mock('../services/auth.js', () => auth);
+vi.mock('../services/settings.js', () => ({
+ settingsEvents: new EventEmitter(),
+ getSettings: vi.fn(async () => ({})),
+}));
+vi.mock('../services/instanceIdentity.js', () => ({
+ loadData: vi.fn(async () => ({ peers: [{
+ id: 'example-peer', instanceId: 'example-instance', enabled: true,
+ syncSecret: 'example-pair-secret-for-tests-only-123456',
+ }] })),
+}));
+
+const peerHeaders = {
+ [PEER_INSTANCE_HEADER]: 'example-instance',
+ [PEER_AUTH_HEADER]: derivePeerAuthToken('example-pair-secret-for-tests-only-123456', 'example-instance'),
+};
+
vi.mock('../services/quotaBurnStore.js', () => ({
getQuotaBurnConfig: vi.fn(),
saveQuotaBurnConfig: vi.fn(),
@@ -12,7 +39,17 @@ vi.mock('../services/quotaBurnRunner.js', () => ({
runQuotaBurnCycle: vi.fn(),
}));
vi.mock('../services/quotaBurnCompletions.js', () => ({ clearQuotaBurnJobCompletion: vi.fn() }));
-vi.mock('../services/quotaBurnConversion.js', () => ({ convertLegacyQuotaBurnPatch: vi.fn(async (patch) => patch) }));
+vi.mock('../services/quotaBurnConversion.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, convertLegacyQuotaBurnPatch: vi.fn(actual.convertLegacyQuotaBurnPatch) };
+});
+const jobsStore = vi.hoisted(() => ({ data: { version: 1, jobs: [] } }));
+vi.mock('../services/autonomousJobs/store.js', () => ({
+ loadJobs: vi.fn(async () => jobsStore.data),
+ saveJobs: vi.fn(async data => { jobsStore.data = data; }),
+ initJobs: vi.fn(async () => jobsStore.data),
+ syncSkillTemplatesFromSample: vi.fn(async () => {}),
+}));
vi.mock('../services/apps.js', () => ({ getActiveApps: vi.fn() }));
vi.mock('../services/providers.js', () => ({ listProviders: vi.fn() }));
@@ -24,9 +61,16 @@ import { getActiveApps } from '../services/apps.js';
import { listProviders } from '../services/providers.js';
import quotaBurnRoutes from './quotaBurn.js';
-const buildApp = () => {
+const buildApp = (address = '127.0.0.1') => {
const app = express();
+ app.use((req, _res, next) => {
+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });
+ next();
+ });
+ app.use(authGate);
+ app.use(hostControlRouteGate);
app.use(express.json());
+ app.use(hostControlBodyGate);
app.use('/api/quota-burn', quotaBurnRoutes);
app.use(errorMiddleware);
return app;
@@ -34,6 +78,8 @@ const buildApp = () => {
beforeEach(() => {
vi.clearAllMocks();
+ auth.isAuthEnabled.mockResolvedValue(false);
+ jobsStore.data = { version: 1, jobs: [] };
getQuotaBurnStatus.mockResolvedValue({
config: { enabled: false, checkIntervalMinutes: 30, families: {} },
status: { running: false, families: [], runs: [] },
@@ -97,22 +143,6 @@ describe('PUT /api/quota-burn', () => {
expect(saveQuotaBurnConfig).toHaveBeenCalledWith({ families: { grok: { enabled: true, jobs } } });
});
- it('runs a legacy body through the conversion service before it reaches disk', async () => {
- // The compat door: an old client can still PUT a `jobType` step, and it must
- // be converted through the SAME service the migration used rather than
- // persisted as an un-migrated step the runner can only refuse.
- saveQuotaBurnConfig.mockResolvedValue({ enabled: true });
- const legacy = { families: { grok: { enabled: true, jobs: [{ jobType: 'agent-prompt', params: { appId: 'a1' } }] } } };
- const converted = { families: { grok: { enabled: true, jobs: [{ taskRef: { kind: 'custom', jobId: 'job-burn-grok-job-1' } }] } } };
- convertLegacyQuotaBurnPatch.mockResolvedValueOnce(converted);
-
- const res = await request(buildApp()).put('/api/quota-burn').send(legacy);
-
- expect(res.status).toBe(200);
- expect(convertLegacyQuotaBurnPatch).toHaveBeenCalledWith(legacy);
- expect(saveQuotaBurnConfig).toHaveBeenCalledWith(converted);
- });
-
it('accepts the unlimited dispatch cap, which sits below the field\'s own minimum', async () => {
saveQuotaBurnConfig.mockResolvedValue({ enabled: true });
const res = await request(buildApp()).put('/api/quota-burn')
@@ -245,3 +275,90 @@ it('accepts a strict claim-drain sequence and rejects non-drainable or repeating
job.taskRef.taskType = 'documentation';
expect((await request(buildApp()).put('/api/quota-burn').send(body)).status).toBe(400);
});
+
+describe('Quota Burn operator authority (#9030)', () => {
+ const legacy = { families: { grok: { enabled: true, jobs: [{
+ id: 'example-step', jobType: 'agent-prompt',
+ params: { appId: 'example-app', prompt: 'Review the example app.' },
+ }] } } };
+ const writes = [
+ ['put', '/api/quota-burn', legacy],
+ ['post', '/api/quota-burn/run', { familyId: 'grok', jobId: 'example-step', force: true }],
+ ['post', '/api/quota-burn/rearm', { familyId: 'grok', jobId: 'example-step' }],
+ ];
+ const call = (app, [method, path, body], headers = {}) => {
+ const req = request(app)[method](path);
+ for (const [key, value] of Object.entries(headers)) req.set(key, value);
+ return req.send(body);
+ };
+ const expectNoEffects = () => {
+ expect(convertLegacyQuotaBurnPatch).not.toHaveBeenCalled();
+ expect(saveQuotaBurnConfig).not.toHaveBeenCalled();
+ expect(jobsStore.data.jobs).toEqual([]);
+ expect(clearQuotaBurnJobCompletion).not.toHaveBeenCalled();
+ expect(runQuotaBurnCycle).not.toHaveBeenCalled();
+ };
+
+ it('refuses remote and Vite-relayed callers before conversion or execution in every route spelling', async () => {
+ for (const [address, headers] of [
+ ['192.0.2.10', {}],
+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }],
+ ]) {
+ for (const [method, path, body] of writes) {
+ for (const spelling of [path, path.toUpperCase(), path + '/', path + '//']) {
+ const res = await call(buildApp(address), [method, spelling, body], headers);
+ expect(res.status, spelling).toBe(403);
+ expect(res.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+ expectNoEffects();
+ }
+ }
+ }
+ });
+
+ it('refuses anonymous, valid legacy Basic and scoped peer credentials when a password is set', async () => {
+ auth.isAuthEnabled.mockResolvedValue(true);
+ for (const [headers, status, code] of [
+ [{}, 401, 'AUTH_REQUIRED'],
+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],
+ [peerHeaders, 403, 'PEER_SCOPE_FORBIDDEN'],
+ ]) {
+ for (const write of writes) {
+ const res = await call(buildApp('192.0.2.10'), write, headers);
+ expect(res.status).toBe(status);
+ expect(res.body.code).toBe(code);
+ expectNoEffects();
+ }
+ }
+ });
+
+ it.each(['local', 'operator session'])('preserves legacy conversion, forced dispatch and rearming for %s', async mode => {
+ const session = mode === 'operator session';
+ auth.isAuthEnabled.mockResolvedValue(session);
+ const app = buildApp(session ? '192.0.2.10' : '127.0.0.1');
+ const headers = session ? { Authorization: 'Bearer example-session' } : {};
+ saveQuotaBurnConfig.mockImplementation(async patch => patch);
+ for (const write of writes) expect((await call(app, write, headers)).status).toBe(200);
+ expect(convertLegacyQuotaBurnPatch).toHaveBeenCalledWith(legacy);
+ expect(jobsStore.data.jobs).toEqual([expect.objectContaining({
+ id: 'job-burn-grok-example-step', appId: 'example-app', type: 'agent',
+ enabled: true, autonomyLevel: 'yolo', promptTemplate: 'Review the example app.',
+ })]);
+ expect(saveQuotaBurnConfig).toHaveBeenCalledWith(expect.objectContaining({
+ families: { grok: expect.objectContaining({ jobs: [expect.objectContaining({
+ taskRef: { kind: 'custom', jobId: 'job-burn-grok-example-step' },
+ })] }) },
+ }));
+ expect(runQuotaBurnCycle).toHaveBeenCalledWith({
+ trigger: 'manual', familyId: 'grok', jobId: 'example-step', force: true,
+ });
+ expect(clearQuotaBurnJobCompletion).toHaveBeenCalledWith('grok', 'example-step');
+ });
+
+ it('keeps status and catalog reads available remotely without a password', async () => {
+ const app = buildApp('192.0.2.10');
+ for (const path of ['/api/quota-burn', '/api/quota-burn/catalog']) {
+ expect((await request(app).get(path)).status).toBe(200);
+ }
+ expectNoEffects();
+ });
+});
diff --git a/server/routes/shell.test.js b/server/routes/shell.test.js
index 9b13cac79f..6e0f0e7f9c 100644
--- a/server/routes/shell.test.js
+++ b/server/routes/shell.test.js
@@ -1,10 +1,37 @@
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import express from 'express';
-import { rmSync, readFileSync, readdirSync } from 'fs';
+import { EventEmitter } from 'node:events';
+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';
+import { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } from '../lib/peerHttpClient.js';
+import { authGate, hostControlRouteGate, hostControlBodyGate } from '../services/authGate.js';
+import { rmSync, readFileSync, readdirSync, existsSync } from 'fs';
import { dirname, join } from 'path';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
+// Real authorization middleware; only credential/settings stores are synthetic.
+const auth = vi.hoisted(() => ({
+ isAuthEnabled: vi.fn(),
+ verifyPassword: vi.fn(async password => password === 'example-password'),
+ verifyRequestSession: vi.fn(async req => req.headers.authorization === 'Bearer example-session'),
+}));
+vi.mock('../services/auth.js', () => auth);
+vi.mock('../services/settings.js', () => ({
+ settingsEvents: new EventEmitter(),
+ getSettings: vi.fn(async () => ({})),
+}));
+vi.mock('../services/instanceIdentity.js', () => ({
+ loadData: vi.fn(async () => ({ peers: [{
+ id: 'example-peer', instanceId: 'example-instance', enabled: true,
+ syncSecret: 'example-pair-secret-for-tests-only-123456',
+ }] })),
+}));
+
+const peerHeaders = {
+ [PEER_INSTANCE_HEADER]: 'example-instance',
+ [PEER_AUTH_HEADER]: derivePeerAuthToken('example-pair-secret-for-tests-only-123456', 'example-instance'),
+};
+
// Point the screenshots root at a throwaway temp dir but keep every real helper
// (saveImageUpload, sanitizeFilename, detectImageFormat, ...) so this exercises
// the actual save pipeline, not a mock of it. Created inside the hoisted factory
@@ -29,9 +56,16 @@ import { PATHS } from '../lib/fileUtils.js';
import { getSession, pasteToSession } from '../services/shell.js';
import shellRoutes from './shell.js';
-const buildApp = () => {
+const buildApp = (address = '127.0.0.1') => {
const app = express();
+ app.use((req, _res, next) => {
+ Object.defineProperty(req.socket, 'remoteAddress', { value: address });
+ next();
+ });
+ app.use(authGate);
+ app.use(hostControlRouteGate);
app.use(express.json({ limit: '20mb' }));
+ app.use(hostControlBodyGate);
app.use('/api/shell', shellRoutes);
app.use(errorMiddleware);
return app;
@@ -44,6 +78,7 @@ const post = (body) => request(buildApp()).post(`/api/shell/sessions/${SESSION}/
beforeEach(() => {
vi.clearAllMocks();
+ auth.isAuthEnabled.mockResolvedValue(false);
vi.mocked(getSession).mockReturnValue({ _id: 'sess-abc' });
vi.mocked(pasteToSession).mockReturnValue(true);
});
@@ -129,3 +164,58 @@ describe('POST /api/shell/sessions/:sessionId/image', () => {
expect(res.body.code).toBe('VALIDATION_ERROR');
});
});
+
+describe('shell image operator authority (#9030)', () => {
+ const path = `/api/shell/sessions/${SESSION}/image`;
+ const body = { data: pngBase64, filename: 'example.png', message: 'Describe this example.' };
+ const files = () => existsSync(PATHS.screenshots) ? readdirSync(PATHS.screenshots).sort() : [];
+ const call = (address, headers = {}, spelling = path) => {
+ const req = request(buildApp(address)).post(spelling);
+ for (const [key, value] of Object.entries(headers)) req.set(key, value);
+ return req.send(body);
+ };
+ const expectNoEffects = before => {
+ expect(files()).toEqual(before);
+ expect(getSession).not.toHaveBeenCalled();
+ expect(pasteToSession).not.toHaveBeenCalled();
+ };
+
+ it('refuses remote and Vite-relayed terminal input before writing an image in every route spelling', async () => {
+ const before = files();
+ for (const [address, headers] of [
+ ['192.0.2.10', {}],
+ ['127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }],
+ ]) {
+ for (const spelling of [path, path.toUpperCase(), path + '/']) {
+ const res = await call(address, headers, spelling);
+ expect(res.status, spelling).toBe(403);
+ expect(res.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+ expectNoEffects(before);
+ }
+ }
+ });
+
+ it('does not grant terminal input to anonymous, valid Basic or scoped peer credentials', async () => {
+ auth.isAuthEnabled.mockResolvedValue(true);
+ const before = files();
+ for (const [headers, status, code] of [
+ [{}, 401, 'AUTH_REQUIRED'],
+ [{ Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }, 403, 'HOST_CONTROL_FORBIDDEN'],
+ [peerHeaders, 403, 'PEER_SCOPE_FORBIDDEN'],
+ ]) {
+ const res = await call('192.0.2.10', headers);
+ expect(res.status).toBe(status);
+ expect(res.body.code).toBe(code);
+ expectNoEffects(before);
+ }
+ });
+
+ it('lets an authenticated remote operator save the image and submit its message to the PTY', async () => {
+ auth.isAuthEnabled.mockResolvedValue(true);
+ const res = await call('192.0.2.10', { Authorization: 'Bearer example-session' });
+ expect(res.status).toBe(200);
+ const stored = join(PATHS.screenshots, res.body.filename);
+ expect(readFileSync(stored)).toEqual(PNG_BYTES);
+ expect(pasteToSession).toHaveBeenCalledWith(SESSION, `Describe this example.\n${stored}`, { label: 'image drop' });
+ });
+});