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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: require operator authority for agent-backed A1111 generation (#11138)
Adam Eivy9d4a30becccd
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex 1f4258af92..70c1b50610 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -43,6 +43,10 @@* caller text to a caller-chosen provider, so they gate per request* instead: a provider that cannot run tool-free (`toolFreeOneShotArgs` in* lib/providerVendors.js) needs host control.+ * - A1111 compatibility (#11138): POST /sdapi/v1/txt2img gates in-handler+ * when the resolved backend is Codex, Grok or Antigravity. External/local/+ * Fal inference and discovery/progress retain their exposure/auth policy.+ * The checked mode is pinned into dispatch; unclassified modes are refused.* - pipeline and FableLoom: autopilot start is gated — with gap filing or* self-improvement on it queues CoS agents — and so are the Pipeline* text/visual generation operations listed under "Pipeline authoring"diff --git a/server/routes/sdapi.js b/server/routes/sdapi.jsindex d4eca8d8ee..6b82c235e4 100644--- a/server/routes/sdapi.js+++ b/server/routes/sdapi.js@@ -23,6 +23,7 @@ import { sdapiTxt2imgBodySchema } from '../lib/apiContractSchemas.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { PATHS, tryReadFile } from '../lib/fileUtils.js';import { getSettings } from '../services/settings.js';+import { assertHostControl } from '../services/authGate.js';import { generateImage, getMode, getActiveJob, IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES } from '../services/imageGen/index.js';import { local as localImage } from '../services/imageGen/index.js';import { createImageGenWaiter } from '../services/imageGenWaiter.js';@@ -30,6 +31,12 @@ import { listVideoModels, defaultVideoModelId, warmByovLoraCapabilities } from 'const router = Router();+// Cloud/queue classification is not authority: Fal is an API-only backend.+// Keep both lists explicit so a new backend cannot silently inherit inference+// authority before its execution path has been audited.+const AGENT_IMAGE_MODES = [IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY];+const INFERENCE_IMAGE_MODES = [IMAGE_GEN_MODE.EXTERNAL, IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.FAL];+// `onTimeout` + `onFailed` map the shared waiter's rejections onto the// ServerError shape sdapi routes need; centralized middleware surfaces the// status + code on the HTTP response.@@ -175,6 +182,11 @@ router.post('/txt2img', asyncHandler(async (req, res) => {// file is on disk by the time generateImage resolves, so the wait is a// no-op there.const mode = await getMode();+ if (AGENT_IMAGE_MODES.includes(mode)) {+ assertHostControl(req);+ } else if (!INFERENCE_IMAGE_MODES.includes(mode)) {+ throw new ServerError('Unsupported image generation mode', { status: 400, code: 'IMAGE_GEN_UNKNOWN_MODE' });+ }const isAsyncMode = mode === IMAGE_GEN_MODE.LOCAL || CLOUD_IMAGE_GEN_MODES.includes(mode);// Allocate the correlation ID up front and register it BEFORE dispatch: a// job-based provider can emit completed/failed while generateImage is still@@ -189,6 +201,8 @@ router.post('/txt2img', asyncHandler(async (req, res) => {let result;try {result = await generateImage({+ // Pin the authorized backend even if saved settings change during dispatch.+ mode,...(jobId ? { jobId } : {}),prompt,negativePrompt: negative_prompt,diff --git a/server/routes/sdapi.test.js b/server/routes/sdapi.test.jsindex 68f2194eec..cb91427b53 100644--- a/server/routes/sdapi.test.js+++ b/server/routes/sdapi.test.js@@ -1,17 +1,31 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { afterAll, describe, it, expect, vi, beforeEach } from 'vitest';+import { EventEmitter } from 'node:events';+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+import { errorMiddleware } from '../lib/errorHandler.js';import express from 'express';import { request } from '../lib/testHelper.js';vi.mock('../services/settings.js', () => ({- getSettings: vi.fn(),+ getSettings: vi.fn(), settingsEvents: new EventEmitter(),}));+const auth = vi.hoisted(() => ({ enabled: false }));+vi.mock('../services/auth.js', () => ({+ isAuthEnabled: vi.fn(async () => auth.enabled),+ verifyRequestSession: vi.fn(async (req) => ['Bearer example-session', 'Bearer example-agent-session'].includes(req.headers.authorization)),+ verifyPassword: vi.fn(async () => true),+}));+vi.mock('../services/instanceIdentity.js', () => ({ loadData: vi.fn(async () => ({ peers: [] })) }));+vi.mock('../lib/paths.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-sdapi-') }));+afterAll(cleanupTempDataRoots);vi.mock('../services/imageGen/index.js', () => ({generateImage: vi.fn(),getMode: vi.fn(),getActiveJob: vi.fn(),- IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex', GROK: 'grok' },- CLOUD_IMAGE_GEN_MODES: ['codex', 'grok'],+ IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex', GROK: 'grok', AGY: 'agy', FAL: 'fal' },+ CLOUD_IMAGE_GEN_MODES: ['codex', 'grok', 'agy', 'fal'],local: { listImageModels: vi.fn(() => [{ id: 'dev', name: 'Flux 1 Dev' }]) },}));@@ -29,10 +43,10 @@ vi.mock('../services/videoGen/local.js', () => ({warmByovLoraCapabilities: vi.fn(async () => {}),}));-vi.mock('../lib/fileUtils.js', () => ({- tryReadFile: vi.fn(),- PATHS: { images: '/mock/images' },-}));+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const proxy = makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-sdapi-') });+ return { ...proxy, tryReadFile: vi.fn() };+});import { getSettings } from '../services/settings.js';import * as imageGen from '../services/imageGen/index.js';@@ -40,6 +54,8 @@ import { imageGenEvents as realEmitter } from '../services/imageGenEvents.js';import { tryReadFile } from '../lib/fileUtils.js';import * as videoGenService from '../services/videoGen/local.js';import sdapiRoutes from './sdapi.js';+import { authGate, hostControlRouteGate } from '../services/authGate.js';+import * as waiter from '../services/imageGenWaiter.js';const enabled = () => getSettings.mockResolvedValue({ imageGen: { expose: { a1111: true } } });const disabled = () => getSettings.mockResolvedValue({ imageGen: { expose: { a1111: false } } });@@ -260,3 +276,151 @@ describe('sdapi routes — A1111-compatible surface', () => {});});});+++// The mounted boundary uniquely catches the passwordless exposure exemption,+// dev-proxy address handling, and backend authorization/dispatch race together.+describe('A1111 generation caller authority (#11138)', () => {+ 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());+ app.use('/sdapi/v1', sdapiRoutes);+ app.use(errorMiddleware);+ return app;+ };+ const generate = (mode, { address, headers = {}, path = '/sdapi/v1/txt2img' } = {}) => {+ imageGen.getMode.mockResolvedValue(mode);+ const pending = request(appFor(address)).post(path);+ for (const [name, value] of Object.entries(headers)) pending.set(name, value);+ return pending.send({ prompt: 'Example scene' });+ };+ const useEarlyCompletion = () => {+ imageGen.generateImage.mockImplementation(async ({ mode, jobId }) => {+ if (jobId) realEmitter.emit('completed', { generationId: jobId, seed: 777 });+ return { generationId: jobId, filename: 'example.png', mode, seed: 1 };+ });+ };++ beforeEach(() => {+ vi.clearAllMocks();+ auth.enabled = false;+ enabled();+ tryReadFile.mockResolvedValue(Buffer.from('png'));+ useEarlyCompletion();+ });++ it('refuses agent modes before waiter or generation effects for every non-operator', async () => {+ const waitSpy = vi.spyOn(waiter, 'createImageGenWaiter');+ try {+ for (const mode of ['codex', 'grok', 'agy']) {+ for (const [password, address, headers] of [+ [false, '192.0.2.10', {}],+ [false, '127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' }],+ [false, '192.0.2.10', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '127.0.0.1' }],+ [true, '192.0.2.10', {}],+ [true, '192.0.2.10', { Authorization: 'Bearer invalid-session' }],+ [true, '192.0.2.10', { Authorization: 'Basic ' + Buffer.from(':example-password').toString('base64') }],+ ]) {+ auth.enabled = password;+ getSettings.mockResolvedValue({ imageGen: { expose: { a1111: true } }, apiAccess: { sdapi: { exposed: true, requireAuth: false } } });+ for (const path of ['/sdapi/v1/txt2img', '/SDAPI/V1/TXT2IMG/']) {+ const response = await generate(mode, { address, headers, path });+ expect([response.status, response.body.code], `${mode} ${path}`).toEqual([403, 'HOST_CONTROL_FORBIDDEN']);+ }+ }+ }+ expect(waitSpy).not.toHaveBeenCalled();+ expect(imageGen.generateImage).not.toHaveBeenCalled();+ expect(tryReadFile).not.toHaveBeenCalled();+ } finally {+ waitSpy.mockRestore();+ }+ });++ it('preserves operator, delegated-agent and genuine local generation with early completion', async () => {+ for (const mode of ['codex', 'grok', 'agy']) {+ for (const [password, address, headers] of [+ [false, '127.0.0.1', {}],+ [false, '127.0.0.1', { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '::ffff:127.0.0.1' }],+ [true, '192.0.2.10', { Authorization: 'Bearer example-session' }],+ [true, '127.0.0.1', { Authorization: 'Bearer example-agent-session' }],+ ]) {+ auth.enabled = password;+ getSettings.mockResolvedValue({ imageGen: { expose: { a1111: true } }, apiAccess: { sdapi: { exposed: true, requireAuth: false } } });+ const response = await generate(mode, { address, headers });+ expect(response.status, `${mode}: ${JSON.stringify(response.body)}`).toBe(200);+ expect(JSON.parse(response.body.info).seed).toBe(777);+ expect(imageGen.generateImage).toHaveBeenLastCalledWith(expect.objectContaining({ mode, jobId: expect.any(String) }));+ expect(realEmitter.listenerCount('completed') + realEmitter.listenerCount('failed')).toBe(0);+ }+ }+ });++ it('keeps remote inference and discovery/progress under existing exposure and auth policy', async () => {+ for (const password of [false, true]) {+ auth.enabled = password;+ getSettings.mockResolvedValue({ imageGen: { expose: { a1111: true } }, apiAccess: { sdapi: { exposed: true, requireAuth: false } } });+ for (const mode of ['external', 'local', 'fal']) {+ const response = await generate(mode);+ expect(response.status, mode).toBe(200);+ expect(imageGen.generateImage).toHaveBeenLastCalledWith(expect.objectContaining({ mode }));+ }+ imageGen.getMode.mockResolvedValue('grok');+ imageGen.getActiveJob.mockResolvedValue(null);+ for (const endpoint of ['options', 'sd-models', 'samplers', 'progress']) {+ expect((await request(appFor()).get(`/sdapi/v1/${endpoint}`)).status).toBe(200);+ }+ }+ auth.enabled = true;+ enabled(); // No passwordless registry exemption.+ const response = await generate('external');+ expect([response.status, response.body.code]).toEqual([401, 'AUTH_REQUIRED']);+ });++ it('pins the inference mode when saved settings change before dispatch', async () => {+ imageGen.generateImage.mockImplementation(async ({ mode, jobId }) => {+ // A fresh saved-mode lookup would now select a host agent.+ imageGen.getMode.mockResolvedValue('grok');+ expect(mode).toBe('local');+ realEmitter.emit('completed', { generationId: jobId });+ return { generationId: jobId, filename: 'example.png', mode };+ });+ const response = await generate('local');+ expect(response.status).toBe(200);+ expect(imageGen.getMode).toHaveBeenCalledTimes(1);+ expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ mode: 'local' }));+ });++ it('refuses unclassified backends and disabled exposure without dispatch or waiters', async () => {+ const waitSpy = vi.spyOn(waiter, 'createImageGenWaiter');+ try {+ for (const mode of ['future-agent', undefined, null, '']) {+ const response = await generate(mode);+ expect([response.status, response.body.code]).toEqual([400, 'IMAGE_GEN_UNKNOWN_MODE']);+ }+ disabled();+ const response = await generate('grok');+ expect(response.status).toBe(403);+ expect(response.body.error).toMatch(/disabled/i);+ expect(waitSpy).not.toHaveBeenCalled();+ expect(imageGen.generateImage).not.toHaveBeenCalled();+ } finally {+ waitSpy.mockRestore();+ }+ });++ it('surfaces authorized agent failure and cleans up its completion listeners', async () => {+ imageGen.generateImage.mockImplementation(async ({ jobId }) => {+ realEmitter.emit('failed', { generationId: jobId, error: 'Example provider failure' });+ return { generationId: jobId, filename: 'example.png', mode: 'grok' };+ });+ const response = await generate('grok', { address: '127.0.0.1' });+ expect([response.status, response.body.code]).toEqual([500, 'GEN_FAILED']);+ expect(realEmitter.listenerCount('completed') + realEmitter.listenerCount('failed')).toBe(0);+ expect(tryReadFile).not.toHaveBeenCalled();+ });+});diff --git a/server/services/authGate.js b/server/services/authGate.jsindex b1cae21597..6a4df10bcf 100644--- a/server/services/authGate.js+++ b/server/services/authGate.js@@ -180,12 +180,14 @@ export const authGate = async (req, res, next) => {// CSRF guard above (a public API is still not a CSRF bypass) and after the// static public-path set. `getSettings()` is a cheap file read; no cache is// introduced here so a Settings toggle takes effect on the very next request.- const settings = await getSettings();- if (isRegistryPublic(settings, path)) return next();+ // A passwordless API exemption must not discard a supplied operator/agent+ // session: conditional host-control handlers still need that identity.if (await verifyRequestSession(req)) {req.portosAuthContext = { enabled: true, authenticated: true, method: 'session' };return next();}+ const settings = await getSettings();+ if (isRegistryPublic(settings, path)) return next();// A paired peer's scoped credential. Checked before Basic so a sender that// presents both during the upgrade handshake is identified as the peer.// Its authority ends at the federation surface (#8387): operator routesdiff --git a/server/services/authGate.test.js b/server/services/authGate.test.jsindex 49aadc5a33..c1da2eb087 100644--- a/server/services/authGate.test.js+++ b/server/services/authGate.test.js@@ -452,6 +452,20 @@ describe('authGate per-API public registry (apiAccess)', () => {expect(result.called).toBe(true);});+ it('retains verified human and delegated agent sessions on a passwordless API', async () => {+ const auth = await import('./auth.js');+ await auth.setPassword({ newPassword: 'example-password' });+ await writeApiAccess({ sdapi: { exposed: true, requireAuth: false } });+ const { authGate, requestHasHostControl } = await import('./authGate.js');+ for (const label of [null, 'agent']) {+ const { token } = await auth.createSession({ label });+ const req = { path: '/sdapi/v1/txt2img', headers: { authorization: `Bearer ${token}` }, socket: { remoteAddress: '192.0.2.10' } };+ expect((await runGate(authGate, req)).called).toBe(true);+ expect(req.portosAuthContext).toEqual({ enabled: true, authenticated: true, method: 'session' });+ expect(requestHasHostControl(req)).toBe(true);+ }+ });+it('still applies the CSRF cross-origin guard to an exposed public path', async () => {const auth = await import('./auth.js');await auth.setPassword({ newPassword: 'correct-horse' });