🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(docker): run self-hosted Compose chats in Gateway Mode by default (#19583)
Arvin Xuc5ec20abab94
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/factory.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/factory.test.tsindex 10a65f049a4..fa4f7481f2e 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/factory.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/factory.test.ts@@ -26,6 +26,7 @@ const {return { kind: 'redis-stream-event-manager' };}),mockAppEnv: {+ AGENT_GATEWAY_INTERNAL_URL: undefined as string | undefined,AGENT_GATEWAY_SERVICE_TOKEN: undefined as string | undefined,AGENT_GATEWAY_URL: 'https://agent-gateway.lobehub.com',enableQueueAgentRuntime: false,@@ -109,6 +110,7 @@ describe('AgentRuntime factory', () => {describe('createStreamEventManager', () => {beforeEach(() => {+ mockAppEnv.AGENT_GATEWAY_INTERNAL_URL = undefined;mockAppEnv.AGENT_GATEWAY_SERVICE_TOKEN = undefined;mockAppEnv.AGENT_GATEWAY_URL = 'https://agent-gateway.lobehub.com';});@@ -156,6 +158,17 @@ describe('AgentRuntime factory', () => {expect(result.url).toBe('https://custom-gateway.example.com');});+ it('pushes to AGENT_GATEWAY_INTERNAL_URL instead of the browser-facing URL when set', () => {+ mockAppEnv.AGENT_GATEWAY_SERVICE_TOKEN = 'my-token';+ mockAppEnv.AGENT_GATEWAY_URL = 'http://localhost:8787';+ mockAppEnv.AGENT_GATEWAY_INTERNAL_URL = 'http://gateway:8787';++ const result = createStreamEventManager() as any;++ expect(result.kind).toBe('gateway-stream-notifier');+ expect(result.url).toBe('http://gateway:8787');+ });+it('wraps in-memory manager with gateway when no Redis', () => {mockAppEnv.AGENT_GATEWAY_SERVICE_TOKEN = 'my-token';diff --git a/apps/server/src/modules/AgentRuntime/factory.ts b/apps/server/src/modules/AgentRuntime/factory.tsindex e595682af0f..757d732dede 100644--- a/apps/server/src/modules/AgentRuntime/factory.ts+++ b/apps/server/src/modules/AgentRuntime/factory.ts@@ -72,9 +72,11 @@ export const createStreamEventManager = (): IStreamEventManager => {);}- // Wrap with Gateway notifier when configured- if (appEnv.AGENT_GATEWAY_URL && appEnv.AGENT_GATEWAY_SERVICE_TOKEN) {- log('Wrapping with GatewayStreamNotifier (%s)', appEnv.AGENT_GATEWAY_URL);+ // Wrap with Gateway notifier when configured. Server pushes prefer the internal+ // URL: the public one is what browsers open, which a container may not reach.+ const gatewayUrl = appEnv.AGENT_GATEWAY_INTERNAL_URL || appEnv.AGENT_GATEWAY_URL;+ if (gatewayUrl && appEnv.AGENT_GATEWAY_SERVICE_TOKEN) {+ log('Wrapping with GatewayStreamNotifier (%s)', gatewayUrl);// Resolver lets a queue worker (which never ran the member op's init) mirror// its stream events onto the supervisor channel by reading the persisted// `mirrorToOperationId` from op metadata. Shares the same state manager@@ -82,7 +84,7 @@ export const createStreamEventManager = (): IStreamEventManager => {const stateManager = createAgentStateManager();return new GatewayStreamNotifier(manager,- appEnv.AGENT_GATEWAY_URL,+ gatewayUrl,appEnv.AGENT_GATEWAY_SERVICE_TOKEN,async (operationId) => {const meta = await stateManager.getOperationMetadata(operationId);diff --git a/apps/server/src/modules/S3/index.test.ts b/apps/server/src/modules/S3/index.test.tsindex a98e4753ad0..dc98d43f51e 100644--- a/apps/server/src/modules/S3/index.test.ts+++ b/apps/server/src/modules/S3/index.test.ts@@ -135,6 +135,54 @@ describe('S3', () => {);});});++ describe('internal endpoint', () => {+ const createS3 = (internalEndpoint?: string) =>+ new S3('test-access-key', 'test-secret-key', 'http://localhost:9000', {+ bucket: 'test-bucket',+ internalEndpoint,+ });++ beforeEach(() => {+ (S3Client as unknown as ReturnType<typeof vi.fn>).mockImplementation(function (config: {+ endpoint: string;+ }) {+ return { endpoint: config.endpoint, send: vi.fn().mockResolvedValue({}) };+ });+ });++ it('sends server-side requests through the internal endpoint', async () => {+ const s3 = createS3('http://rustfs:9000');++ await s3.getFileMetadata('file.png');++ const clients = (S3Client as unknown as ReturnType<typeof vi.fn>).mock.results.map(+ (result) => result.value,+ );+ const internalClient = clients.find((client) => client.endpoint === 'http://rustfs:9000');+ const publicClient = clients.find((client) => client.endpoint === 'http://localhost:9000');+ expect(internalClient.send).toHaveBeenCalledTimes(1);+ expect(publicClient.send).not.toHaveBeenCalled();+ });++ it('signs URLs for the public endpoint that browsers open', async () => {+ const s3 = createS3('http://rustfs:9000');++ await s3.createPreSignedUrl('file.png');+ await s3.createPreSignedUrlForPreview('file.png');++ for (const [client] of mockGetSignedUrl.mock.calls) {+ expect(client.endpoint).toBe('http://localhost:9000');+ }+ expect(mockGetSignedUrl).toHaveBeenCalledTimes(2);+ });++ it('uses a single client when no internal endpoint is configured', () => {+ createS3();++ expect(S3Client).toHaveBeenCalledTimes(1);+ });+ });});describe('FileS3', () => {diff --git a/apps/server/src/modules/S3/index.ts b/apps/server/src/modules/S3/index.tsindex 5842f5df09d..bdbe7fd1938 100644--- a/apps/server/src/modules/S3/index.ts+++ b/apps/server/src/modules/S3/index.ts@@ -45,8 +45,12 @@ export interface PreSignedUpload {}export class S3 {+ /** Sends requests from this server, through the internal endpoint when one is set. */private readonly client: S3Client;+ /** Signs URLs that browsers and model providers open, so it keeps the public endpoint. */+ private readonly presignClient: S3Client;+private readonly bucket: string;private readonly setAcl: boolean;@@ -58,6 +62,8 @@ export class S3 {options?: {bucket?: string;forcePathStyle?: boolean;+ /** Endpoint this server reaches S3 through, when `endpoint` is only reachable from outside. */+ internalEndpoint?: string;region?: string;setAcl?: boolean;},@@ -69,18 +75,26 @@ export class S3 {this.bucket = options?.bucket;this.setAcl = options?.setAcl || false;- this.client = new S3Client({- credentials: {- accessKeyId,- secretAccessKey,- },- endpoint,- forcePathStyle: options?.forcePathStyle,- region: options?.region || DEFAULT_S3_REGION,- // refs: https://github.com/lobehub/lobe-chat/pull/5479- requestChecksumCalculation: 'WHEN_REQUIRED',- responseChecksumValidation: 'WHEN_REQUIRED',- });+ const createClient = (clientEndpoint: string) =>+ new S3Client({+ credentials: {+ accessKeyId,+ secretAccessKey,+ },+ endpoint: clientEndpoint,+ forcePathStyle: options?.forcePathStyle,+ region: options?.region || DEFAULT_S3_REGION,+ // refs: https://github.com/lobehub/lobe-chat/pull/5479+ requestChecksumCalculation: 'WHEN_REQUIRED',+ responseChecksumValidation: 'WHEN_REQUIRED',+ });++ const internalEndpoint = options?.internalEndpoint;+ this.presignClient = createClient(endpoint);+ this.client =+ internalEndpoint && internalEndpoint !== endpoint+ ? createClient(internalEndpoint)+ : this.presignClient;}public async deleteFile(key: string) {@@ -179,7 +193,7 @@ export class S3 {Key: key,});- const url = await getSignedUrl(this.client, command, { expiresIn: 3600 });+ const url = await getSignedUrl(this.presignClient, command, { expiresIn: 3600 });return {headers: this.setAcl ? { 'x-amz-acl': PUBLIC_READ_ACL_HEADER } : undefined,@@ -216,7 +230,7 @@ export class S3 {UploadId: uploadId,});- return getSignedUrl(this.client, command, { expiresIn: 3600 });+ return getSignedUrl(this.presignClient, command, { expiresIn: 3600 });}public async completeMultipartUpload(@@ -294,7 +308,7 @@ export class S3 {Key: key,});- return getSignedUrl(this.client, command, {+ return getSignedUrl(this.presignClient, command, {expiresIn: expiresIn ?? fileEnv.S3_PREVIEW_URL_EXPIRE_IN,});}@@ -310,7 +324,7 @@ export class S3 {ResponseContentDisposition: `attachment; filename*=UTF-8''${encodeContentDispositionFilename(fileName)}`,});- return getSignedUrl(this.client, command, {+ return getSignedUrl(this.presignClient, command, {expiresIn: expiresIn ?? fileEnv.S3_PREVIEW_URL_EXPIRE_IN,});}@@ -370,6 +384,7 @@ export class FileS3 extends S3 {super(fileEnv.S3_ACCESS_KEY_ID, fileEnv.S3_SECRET_ACCESS_KEY, fileEnv.S3_ENDPOINT, {bucket: fileEnv.S3_BUCKET,forcePathStyle: fileEnv.S3_ENABLE_PATH_STYLE,+ internalEndpoint: fileEnv.S3_INTERNAL_ENDPOINT,region: fileEnv.S3_REGION,setAcl: fileEnv.S3_SET_ACL,});diff --git a/docker-compose/deploy/.env.example b/docker-compose/deploy/.env.exampleindex 08a889d74c5..794e6bd48ba 100644--- a/docker-compose/deploy/.env.example+++ b/docker-compose/deploy/.env.example@@ -27,6 +27,13 @@ INTERNAL_APP_URL=http://localhost:3210# Secrets (auto-generated by setup.sh)KEY_VAULTS_SECRET=YOUR_KEY_VAULTS_SECRETAUTH_SECRET=YOUR_AUTH_SECRET+# Shared token between LobeHub and the gateway service (auto-generated by setup.sh)+GATEWAY_SERVICE_TOKEN=YOUR_GATEWAY_SERVICE_TOKEN+# RS256 key set that signs internal JWTs (auto-generated by setup.sh)+JWKS_KEY=YOUR_JWKS_KEY+# The same key without its private fields; only this one is passed to the gateway,+# which verifies browser sessions with it (auto-generated by setup.sh)+JWKS_PUBLIC_KEY=YOUR_JWKS_PUBLIC_KEY# Postgres related, which are the necessary environment variables for DBLOBE_DB_NAME=lobechat@@ -40,6 +47,19 @@ RUSTFS_SECRET_KEY=YOUR_RUSTFS_PASSWORD# Configure the bucket information of RUSTFSRUSTFS_LOBE_BUCKET=lobe+# ===========================+# ====== Agent Gateway ======+# ===========================+# Gateway Mode runs agents on the server and streams them to the browser through+# the `gateway` service. AGENT_GATEWAY_URL must be the gateway address as seen by+# the browser (auto-configured by setup.sh). Behind a reverse proxy, enable+# WebSocket upgrades for it.+AGENT_GATEWAY_PORT=8787+DEVICE_GATEWAY_PORT=8788+AGENT_GATEWAY_URL=http://localhost:8787+# Device gateway address used by the LobeHub server inside the Compose network+DEVICE_GATEWAY_URL=http://gateway:8788+# ===========================# == Optional Elasticsearch ==# ===========================@@ -65,5 +85,3 @@ RUSTFS_LOBE_BUCKET=lobe# ES_JAVA_OPTS=-Xms1g -Xmx1g# Seconds the sync worker sleeps after a drain that found no more work.# FTS_SEARCH_SYNC_INTERVAL_SECONDS=15--JWKS_KEY={"keys":[{"d":"PVoFyqyrGstB8wU52S7gqqQQdZLtin_thcEM0nrNtqp9U-NlKLlhgEcWp5t89ycgvhsAzmrRbezGj4JBTr3jn7eWdwQpPJNYiipnsgeJn0pwsB0H2dMqtavxinoPVXkMTOuGHMTFhhyguFBw2JbIL0PTQUcUlXjv40OoJpYHZeggSxgfV-TuxjwW8Ll4-n84M5IOi6A53RvioE-Hm1iyIc2XLBCfyOu-SbAQYi8HzrA64kCxobAB0peLQMiAzfZmwPKiGOhnhKrAlYmG02qFnbUYiJu_-AXwsAyGv9S9i6dwK7QXaGGWYyis8LlPpd_JmPrBnrWomwDlI045NUMWZQ","dp":"OSXI2NBBZl2r0Dpf4-1z44A_jC5lOyXtJhXQYnSXy5eIuxTJcEtkUYagGEwnREO4Q3t-4J-lT_6Y71M1ZlgKG1upwfw1O4aE3vGpHOik9iZYYCjA8fe5uBfOpX1ELmOtHNoHRhMtyjuPxSFXLlSp3bgcF1f3F40ClukdvXCx0Mc","dq":"m6hNdfj-F8E_7nUlX2nG95OffkFrhHTo67ML9aPgpvFwBlzg-hk5LwtxMfUzngqWF78TMl0JDm7vS1bz0xlWqXqu8pFPoTUnUoWgYfvuyHLBwR5TgccQkfoKbkSMzYNy8VJPXZeyIjVXsW98tZvj-NZF-M9Pke_EWJm-jjXCu_8","e":"AQAB","kty":"RSA","n":"piffosMS0HOSgsSr_zQkXYaQt1kOCD73VR0b2XJD6UdQCKPbnBOzTIuA_xowX61QVsl5pCZLTw8ERC3r2Nlxj5Rp_H6RuOT7ioUqlbnxSGnfuAn8dFupY3A-sf9HVDOvtJdlS-nO9yA4wWU-A50zZ1Mf0pPZlUZE6dUQfsJFi5yXaNAybyk3U4VpMO_SXAilWEHVhiO0F0ccpJMCkT47AeXmYH9MlWwIGcay0UiAsdrs8J-q1arZ7Mbq0oxHmUXJG0vwRvAL8KnCEi8cJ3e2kKCRcr-BQCujsHUyUl6f_ATwSVuTHdAR1IzIcW37v27h3WQK_v0ffQM1NstamDX5vQ","p":"4myVm2M5cZGvVXsOmWUTUG87VC1GlQcL5tmMNSGSpQCL8yWZ1vANkmCxSMptrKB4dU9DAB3On6_oMhW1pJ3uYNGSW49BcmJoLkiWKeg5zWFnKPQNuThQmY1sCCubtKhBQgaYUr7TVzN9smrDV3zCu9MlRl-XPwnEmWaDII3g-f8","q":"u9v4IOEsb4l2Y3eWKE2bwJh5fJRR4vivaYA7U-1-OpvDwB3A48Rey9IL1ucXqE5G1Du8BtijPm5oSAar5uzrjtg1bZ9gevif6DnBGaIRE7LnSrUsTPfZwzntJ1rTaGiVe_pAdnTKXXaH6DxygXxH4wvGgA44V3TTfBXQUcjzdEM","qi":"lDBnSPKkRnYqQvbqVD1LxzqBPEeqEA3GyCqMj6fIZNgoEaBSLi0TSsUyGZ5mahX3KO35vKAZa5jvGjhvUGUiXycq8KvRZdeGK45vJdwZT2TiXiDwo9IQgJcbFMpxaB9DhjX2x0yqxgUY5ca75jLqbMuKBKBN0PVqIr9jlHkR8_s","use":"sig","kid":"6823046760c5d460","alg":"RS256"}]}diff --git a/docker-compose/deploy/.env.zh-CN.example b/docker-compose/deploy/.env.zh-CN.exampleindex 6d78580823c..5c1baad40c2 100644--- a/docker-compose/deploy/.env.zh-CN.example+++ b/docker-compose/deploy/.env.zh-CN.example@@ -24,6 +24,12 @@ INTERNAL_APP_URL=http://localhost:3210# 密钥配置(由 setup.sh 自动生成)KEY_VAULTS_SECRET=YOUR_KEY_VAULTS_SECRETAUTH_SECRET=YOUR_AUTH_SECRET+# LobeHub 与网关服务之间的共享 Token(由 setup.sh 自动生成)+GATEWAY_SERVICE_TOKEN=YOUR_GATEWAY_SERVICE_TOKEN+# 签发内部 JWT 的 RS256 密钥(由 setup.sh 自动生成)+JWKS_KEY=YOUR_JWKS_KEY+# 同一密钥去掉私钥字段后的公钥,只把它传给网关用于校验浏览器会话(由 setup.sh 自动生成)+JWKS_PUBLIC_KEY=YOUR_JWKS_PUBLIC_KEY# PostgreSQL 配置LOBE_DB_NAME=lobechat@@ -37,6 +43,18 @@ RUSTFS_ACCESS_KEY=adminRUSTFS_SECRET_KEY=YOUR_RUSTFS_PASSWORDRUSTFS_LOBE_BUCKET=lobe+# ===================+# ==== Agent 网关 ====+# ===================+# Gateway 模式下智能体在服务端运行,并通过 `gateway` 服务把执行过程推送给浏览器。+# AGENT_GATEWAY_URL 需要填写浏览器能访问到的网关地址(由 setup.sh 自动配置),+# 使用反向代理时需要为其开启 WebSocket 升级。+AGENT_GATEWAY_PORT=8787+DEVICE_GATEWAY_PORT=8788+AGENT_GATEWAY_URL=http://localhost:8787+# LobeHub 服务端在 Compose 网络内访问设备网关的地址+DEVICE_GATEWAY_URL=http://gateway:8788+# ===========================# ===== 可选 Elasticsearch =====# ===========================@@ -60,5 +78,3 @@ RUSTFS_LOBE_BUCKET=lobe# ES_JAVA_OPTS=-Xms1g -Xmx1g# 增量同步任务在一次没有新任务的消费后等待的秒数。# FTS_SEARCH_SYNC_INTERVAL_SECONDS=15--JWKS_KEY={"keys":[{"d":"PVoFyqyrGstB8wU52S7gqqQQdZLtin_thcEM0nrNtqp9U-NlKLlhgEcWp5t89ycgvhsAzmrRbezGj4JBTr3jn7eWdwQpPJNYiipnsgeJn0pwsB0H2dMqtavxinoPVXkMTOuGHMTFhhyguFBw2JbIL0PTQUcUlXjv40OoJpYHZeggSxgfV-TuxjwW8Ll4-n84M5IOi6A53RvioE-Hm1iyIc2XLBCfyOu-SbAQYi8HzrA64kCxobAB0peLQMiAzfZmwPKiGOhnhKrAlYmG02qFnbUYiJu_-AXwsAyGv9S9i6dwK7QXaGGWYyis8LlPpd_JmPrBnrWomwDlI045NUMWZQ","dp":"OSXI2NBBZl2r0Dpf4-1z44A_jC5lOyXtJhXQYnSXy5eIuxTJcEtkUYagGEwnREO4Q3t-4J-lT_6Y71M1ZlgKG1upwfw1O4aE3vGpHOik9iZYYCjA8fe5uBfOpX1ELmOtHNoHRhMtyjuPxSFXLlSp3bgcF1f3F40ClukdvXCx0Mc","dq":"m6hNdfj-F8E_7nUlX2nG95OffkFrhHTo67ML9aPgpvFwBlzg-hk5LwtxMfUzngqWF78TMl0JDm7vS1bz0xlWqXqu8pFPoTUnUoWgYfvuyHLBwR5TgccQkfoKbkSMzYNy8VJPXZeyIjVXsW98tZvj-NZF-M9Pke_EWJm-jjXCu_8","e":"AQAB","kty":"RSA","n":"piffosMS0HOSgsSr_zQkXYaQt1kOCD73VR0b2XJD6UdQCKPbnBOzTIuA_xowX61QVsl5pCZLTw8ERC3r2Nlxj5Rp_H6RuOT7ioUqlbnxSGnfuAn8dFupY3A-sf9HVDOvtJdlS-nO9yA4wWU-A50zZ1Mf0pPZlUZE6dUQfsJFi5yXaNAybyk3U4VpMO_SXAilWEHVhiO0F0ccpJMCkT47AeXmYH9MlWwIGcay0UiAsdrs8J-q1arZ7Mbq0oxHmUXJG0vwRvAL8KnCEi8cJ3e2kKCRcr-BQCujsHUyUl6f_ATwSVuTHdAR1IzIcW37v27h3WQK_v0ffQM1NstamDX5vQ","p":"4myVm2M5cZGvVXsOmWUTUG87VC1GlQcL5tmMNSGSpQCL8yWZ1vANkmCxSMptrKB4dU9DAB3On6_oMhW1pJ3uYNGSW49BcmJoLkiWKeg5zWFnKPQNuThQmY1sCCubtKhBQgaYUr7TVzN9smrDV3zCu9MlRl-XPwnEmWaDII3g-f8","q":"u9v4IOEsb4l2Y3eWKE2bwJh5fJRR4vivaYA7U-1-OpvDwB3A48Rey9IL1ucXqE5G1Du8BtijPm5oSAar5uzrjtg1bZ9gevif6DnBGaIRE7LnSrUsTPfZwzntJ1rTaGiVe_pAdnTKXXaH6DxygXxH4wvGgA44V3TTfBXQUcjzdEM","qi":"lDBnSPKkRnYqQvbqVD1LxzqBPEeqEA3GyCqMj6fIZNgoEaBSLi0TSsUyGZ5mahX3KO35vKAZa5jvGjhvUGUiXycq8KvRZdeGK45vJdwZT2TiXiDwo9IQgJcbFMpxaB9DhjX2x0yqxgUY5ca75jLqbMuKBKBN0PVqIr9jlHkR8_s","use":"sig","kid":"6823046760c5d460","alg":"RS256"}]}diff --git a/docker-compose/deploy/docker-compose.yml b/docker-compose/deploy/docker-compose.ymlindex 547333bcd8a..3443e8498fd 100644--- a/docker-compose/deploy/docker-compose.yml+++ b/docker-compose/deploy/docker-compose.yml@@ -21,6 +21,8 @@ services:- 'ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex'- 'INTERNAL_APP_URL=http://localhost:3210'- 'S3_ENDPOINT=${S3_ENDPOINT}'+ # S3_ENDPOINT is opened by browsers; server-side S3 requests stay on the Compose network+ - 'S3_INTERNAL_ENDPOINT=http://rustfs:9000'- 'S3_BUCKET=${RUSTFS_LOBE_BUCKET}'- 'S3_ENABLE_PATH_STYLE=1'- 'S3_ACCESS_KEY=${RUSTFS_ACCESS_KEY}'@@ -32,6 +34,13 @@ services:- 'REDIS_URL=redis://redis:6379'- 'REDIS_PREFIX=lobechat'- 'REDIS_TLS=0'+ # Gateway Mode: agent runs execute on the server and stream to the browser+ # through the gateway service below. The browser-facing AGENT_GATEWAY_URL+ # comes from .env; server-to-gateway traffic stays on the Compose network.+ - 'ENABLE_AGENT_GATEWAY=1'+ - 'AGENT_GATEWAY_INTERNAL_URL=http://gateway:8787'+ - 'AGENT_GATEWAY_SERVICE_TOKEN=${GATEWAY_SERVICE_TOKEN:-}'+ - 'DEVICE_GATEWAY_SERVICE_TOKEN=${GATEWAY_SERVICE_TOKEN:-}'env_file:- .envvolumes:@@ -40,6 +49,27 @@ services:networks:- lobe-network+ # Single-instance LobeHub gateway (https://github.com/lobehub/lobehub-gateway):+ # - 8787 agent gateway: relays Gateway Mode runs to browsers over WebSocket,+ # so AGENT_GATEWAY_URL in .env must be reachable from the browser.+ # - 8788 device gateway: routes tool calls to devices joined with+ # `lh connect --gateway <url>`.+ # State is kept in memory: runs in flight are lost when this container restarts.+ gateway:+ image: ghcr.io/lobehub/lobehub-gateway:0.3.2+ container_name: lobe-gateway+ ports:+ - '${AGENT_GATEWAY_PORT:-8787}:8787'+ - '${DEVICE_GATEWAY_PORT:-8788}:8788'+ environment:+ - 'SERVICE_TOKEN=${GATEWAY_SERVICE_TOKEN:-}'+ # Public key only: the private JWKS_KEY stays in the lobe container+ - 'JWKS_PUBLIC_KEY=${JWKS_PUBLIC_KEY:-}'+ - 'LOBE_API_BASE_URL=http://lobe:3210'+ restart: always+ networks:+ - lobe-network+postgresql:image: paradedb/paradedb:latest-pg17container_name: lobe-postgresdiff --git a/docker-compose/setup.sh b/docker-compose/setup.shindex fa120fa642f..67e9a6508cf 100644--- a/docker-compose/setup.sh+++ b/docker-compose/setup.sh@@ -220,13 +220,23 @@ show_message() {;;esac;;- tips_regen_jwks)+ tips_generating_gateway_secrets)case $LANGUAGE inzh_CN)- echo "在完成部署测试后,请前往 https://lobehub.com/zh/docs/self-hosting/environment-variables/auth#jwks_key 生成新的 JWKS_KEY 并替换 .env 中的值,以确保安全性。"+ echo "正在生成 JWKS_KEY 与网关 Token(本机没有 Node.js 时会借助 lobehub/lobehub 镜像生成)...";;*)- echo "After completing the deployment test, please go to https://lobehub.com/docs/self-hosting/environment-variables/auth#jwks_key to generate a new JWKS_KEY and replace the value in .env to ensure security."+ echo "Generating JWKS_KEY and the gateway token (uses the lobehub/lobehub image when Node.js is not installed)..."+ ;;+ esac+ ;;+ tips_generate_jwks_failed)+ case $LANGUAGE in+ zh_CN)+ echo "无法生成 JWKS_KEY,请前往 https://lobehub.com/zh/docs/self-hosting/environment-variables/auth#jwks_key 生成后替换 .env 中的值。"+ ;;+ *)+ echo "Failed to generate JWKS_KEY. Please generate one at https://lobehub.com/docs/self-hosting/environment-variables/auth#jwks_key and replace the value in .env.";;esac;;@@ -277,10 +287,10 @@ show_message() {tips_allow_ports)case $LANGUAGE inzh_CN)- echo "请确保服务器以下端口未被占用且能被访问:3210, 9000, 9001"+ echo "请确保服务器以下端口未被占用且能被访问:3210, 9000, 9001, 8787, 8788";;*)- echo "Please make sure the following ports on the server are not occupied and can be accessed: 3210, 9000, 9001"+ echo "Please make sure the following ports on the server are not occupied and can be accessed: 3210, 9000, 9001, 8787, 8788";;esac;;@@ -516,6 +526,7 @@ ENV_EXAMPLES=(# Default valuesRUSTFS_SECRET_KEY="YOUR_RUSTFS_PASSWORD"RUSTFS_HOST="localhost:9000"+GATEWAY_HOST="localhost:8787"PROTOCOL="http"# If no language is specified, ask the user to choose@@ -583,8 +594,9 @@ section_configurate_host() {PROTOCOL="https"# Replace http with https on variable assignments only (commented ones# included), so explanatory comments keep their wording, and skip the- # in-network Elasticsearch endpoint, which is plain HTTP by design.- sed "${SED_INPLACE_ARGS[@]}" '/^#\{0,1\} \{0,1\}[A-Za-z0-9_]*=/{/ES_URL=/!s|http://|https://|;}' .env+ # in-network Elasticsearch and device gateway endpoints, which are plain+ # HTTP by design.+ sed "${SED_INPLACE_ARGS[@]}" '/^#\{0,1\} \{0,1\}[A-Za-z0-9_]*=/{/ES_URL=/!{/DEVICE_GATEWAY_URL=/!s|http://|https://|;};}' .envfifi@@ -614,6 +626,10 @@ section_configurate_host() {echo "RustFS S3 API" $(show_message "ask_domain" "s3.example.com")ask "(s3.example.com)"RUSTFS_HOST="$ask_result"+ # Gateway Mode streams agent runs to the browser over WebSocket+ echo "Agent Gateway" $(show_message "ask_domain" "gateway.example.com")+ ask "(gateway.example.com)"+ GATEWAY_HOST="$ask_result";;1)DEPLOY_MODE="ip"@@ -624,6 +640,7 @@ section_configurate_host() {# If user use ip mode, append the port to the hostLOBE_HOST="${HOST}:3210"RUSTFS_HOST="${HOST}:9000"+ GATEWAY_HOST="${HOST}:8787";;*)echo "Invalid deploy mode: $ask_result"@@ -635,6 +652,8 @@ section_configurate_host() {sed "${SED_INPLACE_ARGS[@]}" "s#^APP_URL=.*#APP_URL=$PROTOCOL://$LOBE_HOST#" .env# s3 relatedsed "${SED_INPLACE_ARGS[@]}" "s#^S3_ENDPOINT=.*#S3_ENDPOINT=$PROTOCOL://$RUSTFS_HOST#" .env+ # agent gateway, opened by the browser+ sed "${SED_INPLACE_ARGS[@]}" "s#^AGENT_GATEWAY_URL=.*#AGENT_GATEWAY_URL=$PROTOCOL://$GATEWAY_HOST#" .env# Check if env modified success@@ -728,6 +747,51 @@ if [[ "$ask_result" == "y" ]]; thensection_regenerate_secretsfi+# ================================+# === Generate Gateway Secrets ===+# ================================+# The .env template only carries placeholders for these, so they are generated+# regardless of the answer above. JWKS_KEY must be unique per deployment: the+# gateway trusts every browser session JWT signed with it.+generate_jwks_key_pair() {+ # Prints the private key set, then the same key without its private fields for the gateway+ local script='const c=require("crypto");const {privateKey,publicKey}=c.generateKeyPairSync("rsa",{modulusLength:2048});const meta={alg:"RS256",kid:c.randomBytes(8).toString("hex"),use:"sig"};console.log(JSON.stringify({keys:[{...privateKey.export({format:"jwk"}),...meta}]}));console.log(JSON.stringify({keys:[{...publicKey.export({format:"jwk"}),...meta}]}))'+ local keys=""+ if command -v node &> /dev/null ; then+ keys=$(node -e "$script" 2>/dev/null)+ fi+ # Fall back to the Node.js runtime inside the LobeHub image+ if [[ "$keys" != '{"keys":'* ]] && command -v docker &> /dev/null ; then+ keys=$(docker run --rm --entrypoint /bin/node lobehub/lobehub -e "$script" 2>/dev/null)+ fi+ if [[ "$keys" != '{"keys":'*$'\n''{"keys":'* ]]; then+ return 1+ fi+ echo "$keys"+}++section_generate_gateway_secrets() {+ echo $(show_message "tips_generating_gateway_secrets")++ GATEWAY_SERVICE_TOKEN=$(openssl rand -hex 32 2>/dev/null || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')+ if [ -z "$GATEWAY_SERVICE_TOKEN" ]; then+ echo $(show_message "security_secrect_regenerate_failed") "GATEWAY_SERVICE_TOKEN"+ else+ sed "${SED_INPLACE_ARGS[@]}" "s#^GATEWAY_SERVICE_TOKEN=.*#GATEWAY_SERVICE_TOKEN=${GATEWAY_SERVICE_TOKEN}#" .env+ fi++ JWKS_KEYS=$(generate_jwks_key_pair)+ if [ $? -ne 0 ]; then+ echo $(show_message "tips_generate_jwks_failed")+ else+ JWKS_KEY=${JWKS_KEYS%%$'\n'*}+ JWKS_PUBLIC_KEY=${JWKS_KEYS#*$'\n'}+ sed "${SED_INPLACE_ARGS[@]}" "s#^JWKS_KEY=.*#JWKS_KEY=${JWKS_KEY}#" .env+ sed "${SED_INPLACE_ARGS[@]}" "s#^JWKS_PUBLIC_KEY=.*#JWKS_PUBLIC_KEY=${JWKS_PUBLIC_KEY}#" .env+ fi+}+section_generate_gateway_secrets+section_init_database() {if ! command -v docker &> /dev/null ; thenecho "docker" $(show_message "tips_no_executable")@@ -771,13 +835,15 @@ section_display_configurated_report() {echo $(show_message "security_secrect_regenerate_report")echo -e "LobeHub: \n - URL: $PROTOCOL://$LOBE_HOST"- echo -e "RustFS: \n - URL: $PROTOCOL://$RUSTFS_HOST \n - Username: admin\n - Password: ${RUSTFS_SECRET_KEY}\n"+ echo -e "RustFS: \n - URL: $PROTOCOL://$RUSTFS_HOST \n - Username: admin\n - Password: ${RUSTFS_SECRET_KEY}"+ echo -e "Agent Gateway: \n - URL: $PROTOCOL://$GATEWAY_HOST\n"# if user run in domain mode, diplay reverse proxy configurationif [[ "$DEPLOY_MODE" == "domain" ]]; thenecho $(show_message "tips_add_reverse_proxy")printf "\n%s\t->\t%s\n" "$LOBE_HOST" "127.0.0.1:3210"printf "%s\t->\t%s\n" "$RUSTFS_HOST" "127.0.0.1:9000"+ printf "%s\t->\t%s\n" "$GATEWAY_HOST" "127.0.0.1:8787 (WebSocket)"fi# Display final message@@ -785,7 +851,6 @@ section_display_configurated_report() {printf "\n%s\n\n" "$(show_message "tips_run_command")"print_centered "docker compose up --no-attach searxng" "green"printf "\n%s\n" "$(show_message "tips_if_run_normally")"- printf "\n%s\n" "$(show_message "tips_regen_jwks")"printf "\n%s\n\n" "$(show_message "tips_disable_registration")"print_centered "docker compose up -d --no-attach searxng" "green"printf "\n%s\n" "$(show_message "tips_if_want_searxng_logs")"diff --git a/docs/self-hosting/environment-variables/basic.mdx b/docs/self-hosting/environment-variables/basic.mdxindex a2471bff302..3516a5dc268 100644--- a/docs/self-hosting/environment-variables/basic.mdx+++ b/docs/self-hosting/environment-variables/basic.mdx@@ -125,10 +125,17 @@ Business builds enable Gateway Mode automatically. Self-hosted deployments can s### `AGENT_GATEWAY_URL`- Type: Optional-- Description: Agent Gateway endpoint used by Gateway Mode to run supported agent tasks through the backend.+- Description: Agent Gateway endpoint used by Gateway Mode to run supported agent tasks through the backend. Browsers open their WebSocket connection to this address, so it must be reachable from the browser.- Default: -- Example: `https://agent-gateway.example.com`+### `AGENT_GATEWAY_INTERNAL_URL`++- Type: Optional+- Description: Agent Gateway endpoint for server-to-gateway requests. Set it when the LobeHub server cannot reach `AGENT_GATEWAY_URL` directly, for example to use the Docker Compose service name. Falls back to `AGENT_GATEWAY_URL`.+- Default: -+- Example: `http://gateway:8787`+### `AGENT_GATEWAY_SERVICE_TOKEN`- Type: Optionaldiff --git a/docs/self-hosting/environment-variables/basic.zh-CN.mdx b/docs/self-hosting/environment-variables/basic.zh-CN.mdxindex aeedf198d0d..9dc0cf99299 100644--- a/docs/self-hosting/environment-variables/basic.zh-CN.mdx+++ b/docs/self-hosting/environment-variables/basic.zh-CN.mdx@@ -121,10 +121,17 @@ LobeHub 在部署时提供了一些额外的配置项,你可以使用环境变### `AGENT_GATEWAY_URL`- 类型:可选-- 描述:Agent Gateway 端点,用于让 Gateway Mode 通过后端运行支持的助理任务。+- 描述:Agent Gateway 端点,用于让 Gateway Mode 通过后端运行支持的助理任务。浏览器会向该地址建立 WebSocket 连接,因此必须能被浏览器访问。- 默认值:-- 示例:`https://agent-gateway.example.com`+### `AGENT_GATEWAY_INTERNAL_URL`++- 类型:可选+- 描述:服务端访问 Agent Gateway 使用的地址。当 LobeHub 服务端无法直接访问 `AGENT_GATEWAY_URL` 时配置,例如使用 Docker Compose 服务名。未设置时回退到 `AGENT_GATEWAY_URL`。+- 默认值:-+- 示例:`http://gateway:8787`+### `AGENT_GATEWAY_SERVICE_TOKEN`- 类型:可选diff --git a/docs/self-hosting/environment-variables/s3.mdx b/docs/self-hosting/environment-variables/s3.mdxindex f4241aad7bd..391fa7a7110 100644--- a/docs/self-hosting/environment-variables/s3.mdx+++ b/docs/self-hosting/environment-variables/s3.mdx@@ -37,6 +37,13 @@ LobeHub supports multimodal AI sessions, including the ability to upload unstruc- Default: -- Example: `https://cos.ap-chengdu.myqcloud.com`+### `S3_INTERNAL_ENDPOINT`++- Type: Optional+- Description: Endpoint the LobeHub server uses for its own S3 requests (uploads, metadata checks, reads, bucket creation) when `S3_ENDPOINT` is only reachable from browsers, for example the Docker Compose service name. Presigned URLs keep using `S3_ENDPOINT`.+- Default: `-` (uses `S3_ENDPOINT`)+- Example: `http://rustfs:9000`+### `S3_BUCKET`- Type: Requireddiff --git a/docs/self-hosting/environment-variables/s3.zh-CN.mdx b/docs/self-hosting/environment-variables/s3.zh-CN.mdxindex 62449c05243..bd7725b24ab 100644--- a/docs/self-hosting/environment-variables/s3.zh-CN.mdx+++ b/docs/self-hosting/environment-variables/s3.zh-CN.mdx@@ -35,6 +35,13 @@ LobeHub 支持多模态的 AI 会话,包括将图片、文件等非结构化- 默认值:-- 示例:`https://cos.ap-chengdu.myqcloud.com`+### `S3_INTERNAL_ENDPOINT`++- 类型:可选+- 描述:LobeHub 服务端自身发起 S3 请求(上传、元数据校验、读取、创建存储桶)时使用的端点。当 `S3_ENDPOINT` 只能被浏览器访问时配置,例如 Docker Compose 服务名。预签名 URL 仍使用 `S3_ENDPOINT`。+- 默认值:`-`(使用 `S3_ENDPOINT`)+- 示例:`http://rustfs:9000`+### `S3_BUCKET`- 类型:必填diff --git a/docs/self-hosting/platform/docker-compose.mdx b/docs/self-hosting/platform/docker-compose.mdxindex 79067fb3be7..44a6f9cf59e 100644--- a/docs/self-hosting/platform/docker-compose.mdx+++ b/docs/self-hosting/platform/docker-compose.mdx@@ -20,6 +20,10 @@ tags:[![][docker-pulls-shield]][docker-pulls-link]</div>+<Callout type="warning">+ **Upgrading an existing Docker Compose deployment?** The latest `docker-compose.yml` adds a gateway service for Gateway Mode. Update `.env` as described in [Upgrading an Existing Deployment](#upgrading-an-existing-deployment) before starting it. Otherwise the gateway container keeps restarting, agent runs fall back to the browser, and `docker logs lobehub` prints an `ACTION REQUIRED` warning.+</Callout>+## Quick Start<Callout type="info">@@ -31,7 +35,7 @@ tags:- The one-click startup script is only for initial deployment; for subsequent deployments, please refer to the [Custom Deployment](#custom-deployment) section.- - Port occupation check: Ensure that ports `3210`, `9000`, and `9001` are available.+ - Port occupation check: Ensure that ports `3210`, `9000`, `9001`, `8787`, and `8788` are available.</Callout>Execute the following commands to set up the deployment environment; the directory `lobehub` will be used to store your configuration files and subsequent database files.@@ -77,6 +81,8 @@ The script supports the following deployment modes; please choose the appropriat- URL: http://localhost:9000- Username: admin- Password: 8c82ea41+ Agent Gateway:+ - URL: http://localhost:8787```### Start Docker@@ -132,6 +138,8 @@ The script supports the following deployment modes; please choose the appropriat- URL: http://your_server_ip:9000- Username: admin- Password: dbac8440+ Agent Gateway:+ - URL: http://your_server_ip:8787```### Start Docker@@ -171,11 +179,12 @@ The script supports the following deployment modes; please choose the appropriatIn domain mode, you need to complete the reverse proxy configuration and ensure that the LAN/public can access the following services. Please use a reverse proxy to map the following service ports to the domain names:- | Domain | Proxy Port | Required |- | ------------------- | ---------- | -------- |- | `lobe.example.com` | `3210` | Yes |- | `s3.example.com` | `9000` | Yes |- | `s3-ui.example.com` | `9001` | |+ | Domain | Proxy Port | Required |+ | --------------------- | ---------- | -------- |+ | `lobe.example.com` | `3210` | Yes |+ | `s3.example.com` | `9000` | Yes |+ | `gateway.example.com` | `8787` | Yes |+ | `s3-ui.example.com` | `9001` | |### Complete Remaining Configuration in Interactive Script@@ -183,6 +192,7 @@ The script supports the following deployment modes; please choose the appropriat- Domain setup for the LobeHub service: `lobe.example.com`- Domain setup for the S3 service: `s3.example.com`+ - Domain setup for the Agent Gateway: `gateway.example.com` (the reverse proxy must allow WebSocket upgrades)- Choose the access protocol: `http` or `https`- Regenerate secure keys: We highly recommend regenerating the secure keys; if you lack the key generation library required by the script, we suggest referring to the [Custom Deployment](#custom-deployment) section for key modifications.@@ -196,7 +206,7 @@ The script supports the following deployment modes; please choose the appropriat**Port Mode vs Domain Mode:**- - Port Mode: The script automatically uses default ports (3210/9000/9001)+ - Port Mode: The script automatically uses default ports (3210/9000/9001/8787/8788)- Domain Mode: You can customize ports (via reverse proxy configuration)</Callout>@@ -222,6 +232,8 @@ The script supports the following deployment modes; please choose the appropriat- URL: https://s3.example.com- Username: admin- Password: dbac8440+ Agent Gateway:+ - URL: https://gateway.example.com```### Start Docker@@ -297,6 +309,8 @@ LobeHub needs to provide a public access URL for object files for the LLM servicS3_ENDPOINT=https://s3.example.com```+`S3_ENDPOINT` only needs to be reachable from browsers: `docker-compose.yml` sets `S3_INTERNAL_ENDPOINT=http://rustfs:9000`, so the LobeHub server itself reaches RustFS inside the Compose network.+2. PostgreSQLThis configuration is found in the `docker-compose.yml` file, and you will need to configure the database name and password:@@ -325,6 +339,75 @@ INTERNAL_APP_URL=http://localhost:3210For Docker Compose deployments, we recommend using `http://localhost:3210` (container calling itself) or `http://lobe:3210` (using service name for container-to-container communication).</Callout>+4. Agent Gateway (Gateway Mode)++The `gateway` service lets agent runs execute on the LobeHub server instead of in the browser. It needs the following values in `.env`, which `setup.sh` fills in automatically:++- `AGENT_GATEWAY_URL`: the gateway address as reached by the browser, such as `https://gateway.example.com` or `http://your_server_ip:8787`. The browser opens a WebSocket connection to it, so a reverse proxy in front of it must allow WebSocket upgrades and long read timeouts. The LobeHub server reaches the gateway at `http://gateway:8787` inside the Compose network.+- `GATEWAY_SERVICE_TOKEN`: a random token shared by LobeHub and the gateway.+- `JWKS_KEY`: the RS256 key set LobeHub signs internal JWTs with. Every deployment must use its own key, and it stays in the `lobe` container.+- `JWKS_PUBLIC_KEY`: the same key without its private fields. Only this value is passed to the gateway, which verifies browser sessions with it.++```sh+# GATEWAY_SERVICE_TOKEN+openssl rand -hex 32+# JWKS_KEY and JWKS_PUBLIC_KEY (paste both lines into .env)+docker run --rm --entrypoint /bin/node lobehub/lobehub -e 'const c=require("crypto");const {privateKey,publicKey}=c.generateKeyPairSync("rsa",{modulusLength:2048});const meta={alg:"RS256",kid:c.randomBytes(8).toString("hex"),use:"sig"};console.log("JWKS_KEY="+JSON.stringify({keys:[{...privateKey.export({format:"jwk"}),...meta}]}));console.log("JWKS_PUBLIC_KEY="+JSON.stringify({keys:[{...publicKey.export({format:"jwk"}),...meta}]}))'+```++<Callout type="warning">+ Upgrading an existing deployment? Follow [Upgrading an Existing Deployment](#upgrading-an-existing-deployment) first. The gateway keeps its state in memory, so runs in progress are interrupted when it restarts.+</Callout>++<Callout type="tip">+ Devices joined with `lh connect --gateway http://your_server_ip:8788` can run local tools for this deployment through the device gateway on port `8788`.+</Callout>++## Upgrading an Existing Deployment++<Callout type="warning">+ Finish these steps before starting the new `docker-compose.yml`. Until they are done, the `lobe-gateway` container keeps restarting, agent runs fall back to the browser, and `docker logs lobehub` prints an `ACTION REQUIRED` warning at startup.+</Callout>++<Steps>+ ### Back up `.env` and download the new Compose file++ ```sh+ cp .env .env.bak+ curl -O https://raw.githubusercontent.com/lobehub/lobehub/HEAD/docker-compose/deploy/docker-compose.yml+ ```++ ### Add the gateway variables to `.env`++ ```env+ AGENT_GATEWAY_PORT=8787+ DEVICE_GATEWAY_PORT=8788+ # Gateway address as reached by the browser, e.g. https://gateway.example.com+ AGENT_GATEWAY_URL=http://your_server_ip:8787+ DEVICE_GATEWAY_URL=http://gateway:8788+ # Output of: openssl rand -hex 32+ GATEWAY_SERVICE_TOKEN=+ ```++ Then add `JWKS_PUBLIC_KEY`, the public half of your existing `JWKS_KEY`, by running this in the directory that holds `.env` and pasting its output:++ ```sh+ docker run --rm -e JWKS_KEY="$(grep '^JWKS_KEY=' .env | cut -d= -f2-)" --entrypoint /bin/node lobehub/lobehub -e 'const {d,p,q,dp,dq,qi,...pub}=JSON.parse(process.env.JWKS_KEY).keys[0];console.log("JWKS_PUBLIC_KEY="+JSON.stringify({keys:[pub]}))'+ ```++ In domain mode, also reverse proxy the gateway domain to port `8787` with WebSocket upgrades enabled.++ ### Replace the example `JWKS_KEY`++ If `JWKS_KEY` in `.env` is still the value shipped in the old `.env.example` (its `kid` is `6823046760c5d460`), anyone can forge tokens your deployment accepts. Generate a new key pair with the command in [Necessary Configuration](#necessary-configuration) and replace both `JWKS_KEY` and `JWKS_PUBLIC_KEY`. Desktop and CLI clients may need to sign in again afterwards.++ ### Recreate the stack++ ```sh+ docker compose up -d --force-recreate+ ```+</Steps>+## FAQ#### Database Migration Issuesdiff --git a/docs/self-hosting/platform/docker-compose.zh-CN.mdx b/docs/self-hosting/platform/docker-compose.zh-CN.mdxindex eb4af9679b3..8d4d3444f0e 100644--- a/docs/self-hosting/platform/docker-compose.zh-CN.mdx+++ b/docs/self-hosting/platform/docker-compose.zh-CN.mdx@@ -18,6 +18,10 @@ tags:[![][docker-pulls-shield]][docker-pulls-link]</div>+<Callout type="warning">+ **正在升级已有的 Docker Compose 部署?** 最新的 `docker-compose.yml` 新增了 Gateway 模式所需的网关服务。启动前请先按 [升级已有部署](#升级已有部署) 更新 `.env`,否则网关容器会反复重启、智能体退回浏览器中运行,`docker logs lobehub` 也会打印 `ACTION REQUIRED` 告警。+</Callout>+## 快速启动<Callout type="info">@@ -29,7 +33,7 @@ tags:- 一键启动脚本为首次部署专用,非首次部署请参考 [自定义部署](#自定义部署) 章节- - 端口占用检查:确保 `3210`、`9000`、`9001` 端口可用+ - 端口占用检查:确保 `3210`、`9000`、`9001`、`8787`、`8788` 端口可用</Callout>执行以下命令初始化部署环境,目录 `lobehub` 将用于存放你的配置文件和后续的数据库文件。@@ -74,6 +78,8 @@ bash <(curl -fsSL https://lobe.li/setup.sh) -l zh_CN- URL: http://localhost:9000- Username: admin- Password: 8c82ea41+ Agent Gateway:+ - URL: http://localhost:8787```### 启动 Docker@@ -129,6 +135,8 @@ bash <(curl -fsSL https://lobe.li/setup.sh) -l zh_CN- URL: http://your_server_ip:9000- Username: admin- Password: dbac8440+ Agent Gateway:+ - URL: http://your_server_ip:8787```### 启动 Docker@@ -168,11 +176,12 @@ bash <(curl -fsSL https://lobe.li/setup.sh) -l zh_CN在域名模式中,你需要完成反向代理配置,并确保局域网 / 公网能访问到以下服务。请使用反向代理将以下服务端口映射到域名:- | 域名 | 反代端口 | 是否必选 |- | ------------------- | ------ | ---- |- | `lobe.example.com` | `3210` | 必选 |- | `s3.example.com` | `9000` | 必选 |- | `s3-ui.example.com` | `9001` | |+ | 域名 | 反代端口 | 是否必选 |+ | --------------------- | ------ | ---- |+ | `lobe.example.com` | `3210` | 必选 |+ | `s3.example.com` | `9000` | 必选 |+ | `gateway.example.com` | `8787` | 必选 |+ | `s3-ui.example.com` | `9001` | |### 在交互式脚本中完成剩余配置@@ -180,6 +189,7 @@ bash <(curl -fsSL https://lobe.li/setup.sh) -l zh_CN- LobeHub 服务的域名设置:`lobe.example.com`- S3 服务的域名设置:`s3.example.com`+ - Agent 网关的域名设置:`gateway.example.com`(反向代理需要允许 WebSocket 升级)- 选择访问协议:`http` 或 `https`- 安全密钥重新生成:我们强烈建议你重新生成安全密钥,如果你缺少脚本所需的密钥生成库,我们建议你参考 [自定义部署](#自定义部署) 章节对密钥进行修改。@@ -191,7 +201,7 @@ bash <(curl -fsSL https://lobe.li/setup.sh) -l zh_CN- S3 服务的域名设置:`lobe.example.com:${PORT2}`需在反向代理中配置对应端口的转发规则。**端口模式 vs 域名模式:**- - 端口模式:一键安装脚本自动使用默认端口(3210/9000/9001)+ - 端口模式:一键安装脚本自动使用默认端口(3210/9000/9001/8787/8788)- 域名模式:可自定义端口(通过反向代理配置)</Callout>@@ -217,6 +227,8 @@ bash <(curl -fsSL https://lobe.li/setup.sh) -l zh_CN- URL: https://s3.example.com- Username: admin- Password: dbac8440+ Agent Gateway:+ - URL: https://gateway.example.com```### 启动 Docker@@ -291,6 +303,8 @@ LobeHub 需要为 LLM 服务提供商提供文件对象的公网访问地址,S3_ENDPOINT=https://s3.example.com```+`S3_ENDPOINT` 只需要能被浏览器访问:`docker-compose.yml` 设置了 `S3_INTERNAL_ENDPOINT=http://rustfs:9000`,LobeHub 服务端自身会在 Compose 网络内访问 RustFS。+2. PostgreSQL该配置位于 `docker-compose.yml` 文件中,你需要配置数据库的名称和密码:@@ -319,6 +333,75 @@ INTERNAL_APP_URL=http://localhost:3210对于 Docker Compose 部署,推荐使用 `http://localhost:3210`(容器调用自身)或 `http://lobe:3210`(使用服务名称进行容器间通信)。</Callout>+4. Agent 网关(Gateway 模式)++`gateway` 服务让智能体在 LobeHub 服务端运行,而不是在浏览器中运行。它需要在 `.env` 中配置以下变量,`setup.sh` 会自动填写:++- `AGENT_GATEWAY_URL`:浏览器访问网关的地址,例如 `https://gateway.example.com` 或 `http://your_server_ip:8787`。浏览器会向该地址建立 WebSocket 连接,因此其前面的反向代理需要允许 WebSocket 升级并设置较长的读取超时。LobeHub 服务端则在 Compose 网络内通过 `http://gateway:8787` 访问网关。+- `GATEWAY_SERVICE_TOKEN`:LobeHub 与网关共享的随机 Token。+- `JWKS_KEY`:LobeHub 签发内部 JWT 使用的 RS256 密钥。每个部署都必须使用自己的密钥,且只保留在 `lobe` 容器中。+- `JWKS_PUBLIC_KEY`:同一密钥去掉私钥字段后的公钥。只有它会传给网关,用于校验浏览器会话。++```sh+# GATEWAY_SERVICE_TOKEN+openssl rand -hex 32+# JWKS_KEY 与 JWKS_PUBLIC_KEY(把输出的两行都填入 .env)+docker run --rm --entrypoint /bin/node lobehub/lobehub -e 'const c=require("crypto");const {privateKey,publicKey}=c.generateKeyPairSync("rsa",{modulusLength:2048});const meta={alg:"RS256",kid:c.randomBytes(8).toString("hex"),use:"sig"};console.log("JWKS_KEY="+JSON.stringify({keys:[{...privateKey.export({format:"jwk"}),...meta}]}));console.log("JWKS_PUBLIC_KEY="+JSON.stringify({keys:[{...publicKey.export({format:"jwk"}),...meta}]}))'+```++<Callout type="warning">+ 正在升级已有部署?请先完成 [升级已有部署](#升级已有部署) 中的步骤。网关的状态保存在内存中,重启时正在进行的运行会被中断。+</Callout>++<Callout type="tip">+ 通过 `lh connect --gateway http://your_server_ip:8788` 接入的设备,可以经由 `8788` 端口的设备网关为该部署执行本地工具。+</Callout>++## 升级已有部署++<Callout type="warning">+ 请在启动新的 `docker-compose.yml` 之前完成以下步骤。完成之前,`lobe-gateway` 容器会反复重启、智能体退回浏览器中运行,`docker logs lobehub` 启动时会打印 `ACTION REQUIRED` 告警。+</Callout>++<Steps>+ ### 备份 `.env` 并下载新的 Compose 文件++ ```sh+ cp .env .env.bak+ curl -O https://raw.githubusercontent.com/lobehub/lobehub/HEAD/docker-compose/deploy/docker-compose.yml+ ```++ ### 在 `.env` 中补充网关变量++ ```env+ AGENT_GATEWAY_PORT=8787+ DEVICE_GATEWAY_PORT=8788+ # 浏览器访问网关的地址,例如 https://gateway.example.com+ AGENT_GATEWAY_URL=http://your_server_ip:8787+ DEVICE_GATEWAY_URL=http://gateway:8788+ # 填入 openssl rand -hex 32 的输出+ GATEWAY_SERVICE_TOKEN=+ ```++ 然后在 `.env` 所在目录运行下面的命令,从现有 `JWKS_KEY` 导出公钥,并把输出的 `JWKS_PUBLIC_KEY` 填入 `.env`:++ ```sh+ docker run --rm -e JWKS_KEY="$(grep '^JWKS_KEY=' .env | cut -d= -f2-)" --entrypoint /bin/node lobehub/lobehub -e 'const {d,p,q,dp,dq,qi,...pub}=JSON.parse(process.env.JWKS_KEY).keys[0];console.log("JWKS_PUBLIC_KEY="+JSON.stringify({keys:[pub]}))'+ ```++ 域名模式下,还需要为网关域名配置反向代理到 `8787` 端口,并开启 WebSocket 升级。++ ### 替换示例 `JWKS_KEY`++ 如果 `.env` 中的 `JWKS_KEY` 仍是旧版 `.env.example` 自带的值(其 `kid` 为 `6823046760c5d460`),任何人都能伪造你的部署会接受的令牌。请使用 [必要配置](#必要配置) 中的命令生成新的密钥对,同时替换 `JWKS_KEY` 与 `JWKS_PUBLIC_KEY`,替换后桌面端和 CLI 可能需要重新登录。++ ### 重建服务++ ```sh+ docker compose up -d --force-recreate+ ```+</Steps>+## 常见问题#### 数据库迁移问题diff --git a/packages/env/src/app.ts b/packages/env/src/app.tsindex e8141ed3798..7f4c9388831 100644--- a/packages/env/src/app.ts+++ b/packages/env/src/app.ts@@ -77,6 +77,11 @@ export const getAppConfig = () => {AGENT_GATEWAY_SERVICE_TOKEN: z.string().optional(),ENABLE_AGENT_GATEWAY: z.boolean().optional(),+ /**+ * Server-to-server Agent Gateway endpoint, e.g. a Docker Compose service+ * name the browser cannot resolve. Falls back to AGENT_GATEWAY_URL.+ */+ AGENT_GATEWAY_INTERNAL_URL: z.string().url().optional(),AGENT_GATEWAY_URL: z.string().url().optional(),/*** Enable Queue-based Agent Runtime@@ -124,6 +129,7 @@ export const getAppConfig = () => {AGENT_GATEWAY_SERVICE_TOKEN: process.env.AGENT_GATEWAY_SERVICE_TOKEN,ENABLE_AGENT_GATEWAY: process.env.ENABLE_AGENT_GATEWAY === '1',AGENT_GATEWAY_URL: process.env.AGENT_GATEWAY_URL,+ AGENT_GATEWAY_INTERNAL_URL: process.env.AGENT_GATEWAY_INTERNAL_URL || undefined,enableQueueAgentRuntime: process.env.AGENT_RUNTIME_MODE === 'queue',TELEMETRY_DISABLED: process.env.TELEMETRY_DISABLED === '1',},diff --git a/packages/env/src/file.ts b/packages/env/src/file.tsindex cd84dbffe6d..8706a0ba843 100644--- a/packages/env/src/file.ts+++ b/packages/env/src/file.ts@@ -34,6 +34,7 @@ export const getFileConfig = () => {S3_BUCKET: process.env.S3_BUCKET,S3_ENABLE_PATH_STYLE: process.env.S3_ENABLE_PATH_STYLE === '1',S3_ENDPOINT: process.env.S3_ENDPOINT,+ S3_INTERNAL_ENDPOINT: process.env.S3_INTERNAL_ENDPOINT || undefined,S3_PREVIEW_URL_EXPIRE_IN: parseInt(process.env.S3_PREVIEW_URL_EXPIRE_IN || '7200'),S3_PUBLIC_DOMAIN,S3_REGION: process.env.S3_REGION,@@ -52,6 +53,11 @@ export const getFileConfig = () => {S3_ENABLE_PATH_STYLE: z.boolean(),S3_ENDPOINT: z.string().url().optional(),+ /**+ * Endpoint the server uses for S3 requests when S3_ENDPOINT is only reachable from+ * browsers, e.g. a Docker Compose service name. Presigned URLs keep S3_ENDPOINT.+ */+ S3_INTERNAL_ENDPOINT: z.string().url().optional(),S3_PREVIEW_URL_EXPIRE_IN: z.number(),S3_PUBLIC_DOMAIN: z.string().optional(),S3_REGION: z.string().optional(),diff --git a/scripts/_shared/checkGatewayConfig.js b/scripts/_shared/checkGatewayConfig.jsnew file mode 100644index 00000000000..4648b9fb419--- /dev/null+++ b/scripts/_shared/checkGatewayConfig.js@@ -0,0 +1,120 @@+/**+ * Startup check for the Gateway Mode wiring of Docker Compose deployments.+ * Used by startServer.js (Docker runtime). It only warns: an incomplete setup+ * still runs, with agent runs falling back to the browser.+ *+ * IMPORTANT: Keep this file as CommonJS (.js) for compatibility with startServer.js+ */++const UPGRADE_DOC_URL =+ 'https://lobehub.com/docs/self-hosting/platform/docker-compose#upgrading-an-existing-deployment';++/**+ * `kid` of the JWKS key that used to ship in docker-compose/deploy/.env.example.+ * Its private half is public, so anyone can sign tokens a server using it accepts.+ */+const PUBLIC_EXAMPLE_JWKS_KID = '6823046760c5d460';++/** JWK members that only a private RSA key carries. */+const PRIVATE_JWK_FIELDS = ['d', 'p', 'q', 'dp', 'dq', 'qi'];++const isUnset = (value) => !value || value.startsWith('YOUR_');++/** First key of a JWKS JSON string, `null` for valid JSON without keys, `undefined` if unparsable. */+const readFirstJwk = (raw) => {+ try {+ const key = JSON.parse(raw)?.keys?.[0];+ return key && typeof key === 'object' ? key : null;+ } catch {+ return undefined;+ }+};++/**+ * @param {NodeJS.ProcessEnv} [env]+ * @returns {Array<{ name: string; vars: string[]; message: string }>}+ */+function collectGatewayConfigIssues(env = process.env) {+ const issues = [];+ const privateJwk = isUnset(env.JWKS_KEY) ? undefined : readFirstJwk(env.JWKS_KEY);++ if (privateJwk?.kid === PUBLIC_EXAMPLE_JWKS_KID) {+ issues.push({+ message:+ 'JWKS_KEY is the example key that was published in .env.example. Anyone can forge tokens this server and its gateway accept. Generate a new key and replace it in .env.',+ name: 'Public example JWKS_KEY',+ vars: ['JWKS_KEY'],+ });+ }++ // Set by docker-compose.yml; other deployments opt in explicitly.+ if (env.ENABLE_AGENT_GATEWAY !== '1') return issues;++ const missing = [];+ if (isUnset(env.AGENT_GATEWAY_URL)) missing.push('AGENT_GATEWAY_URL');+ if (isUnset(env.AGENT_GATEWAY_SERVICE_TOKEN)) missing.push('GATEWAY_SERVICE_TOKEN');+ if (isUnset(env.JWKS_KEY)) missing.push('JWKS_KEY');+ else if (privateJwk === undefined) missing.push('JWKS_KEY (not valid JWKS JSON)');++ const publicJwk = isUnset(env.JWKS_PUBLIC_KEY) ? undefined : readFirstJwk(env.JWKS_PUBLIC_KEY);+ if (isUnset(env.JWKS_PUBLIC_KEY)) missing.push('JWKS_PUBLIC_KEY');+ else if (publicJwk === undefined) missing.push('JWKS_PUBLIC_KEY (not valid JWKS JSON)');++ if (missing.length > 0) {+ issues.push({+ message:+ 'docker-compose.yml enables Gateway Mode, but .env is missing its settings. The gateway container cannot start and agent runs fall back to the browser. Add the variables to .env, then run `docker compose up -d --force-recreate`.',+ name: 'Gateway Mode is not configured',+ vars: missing,+ });+ }++ if (publicJwk && PRIVATE_JWK_FIELDS.some((field) => field in publicJwk)) {+ issues.push({+ message:+ 'JWKS_PUBLIC_KEY is passed to the gateway container, but it includes the private key. Anyone who can read the gateway environment could forge tokens. Replace it with the public half of JWKS_KEY.',+ name: 'JWKS_PUBLIC_KEY contains the private key',+ vars: ['JWKS_PUBLIC_KEY'],+ });+ }++ if (privateJwk?.n && publicJwk?.n && privateJwk.n !== publicJwk.n) {+ issues.push({+ message:+ 'JWKS_PUBLIC_KEY is not the public half of JWKS_KEY, so the gateway rejects every browser session and agent runs fall back to the browser. Derive it again from JWKS_KEY.',+ name: 'JWKS_PUBLIC_KEY does not match JWKS_KEY',+ vars: ['JWKS_PUBLIC_KEY'],+ });+ }++ return issues;+}++/**+ * Print a prominent warning for every Gateway Mode configuration issue.+ * @param {NodeJS.ProcessEnv} [env]+ */+function checkGatewayConfig(env = process.env) {+ const issues = collectGatewayConfigIssues(env);+ if (issues.length === 0) return issues;++ console.warn('\n' + '═'.repeat(70));+ console.warn('⚠️ ACTION REQUIRED: Gateway Mode configuration needs attention');+ console.warn('═'.repeat(70));++ for (const issue of issues) {+ console.warn(`\n⚠️ ${issue.name}`);+ console.warn('─'.repeat(50));+ for (const envVar of issue.vars) {+ console.warn(` • ${envVar}`);+ }+ console.warn(`\n${issue.message}`);+ }++ console.warn(`\n📖 Upgrade guide: ${UPGRADE_DOC_URL}`);+ console.warn('═'.repeat(70) + '\n');++ return issues;+}++module.exports = { checkGatewayConfig, collectGatewayConfigIssues, PUBLIC_EXAMPLE_JWKS_KID };diff --git a/scripts/_shared/checkGatewayConfig.test.ts b/scripts/_shared/checkGatewayConfig.test.tsnew file mode 100644index 00000000000..d5c7b50a33a--- /dev/null+++ b/scripts/_shared/checkGatewayConfig.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it, vi } from 'vitest';++import {+ checkGatewayConfig,+ collectGatewayConfigIssues,+ PUBLIC_EXAMPLE_JWKS_KID,+} from './checkGatewayConfig.js';++const jwks = (kid: string, fields: Record<string, string> = {}) =>+ JSON.stringify({ keys: [{ alg: 'RS256', e: 'AQAB', kid, kty: 'RSA', n: 'modulus', ...fields }] });++const configured = {+ AGENT_GATEWAY_SERVICE_TOKEN: 'token',+ AGENT_GATEWAY_URL: 'http://localhost:8787',+ ENABLE_AGENT_GATEWAY: '1',+ JWKS_KEY: jwks('fresh-key', { d: 'private-exponent' }),+ JWKS_PUBLIC_KEY: jwks('fresh-key'),+};++describe('collectGatewayConfigIssues', () => {+ it('reports nothing for a fully configured gateway', () => {+ expect(collectGatewayConfigIssues(configured)).toEqual([]);+ });++ it('ignores gateway settings when Gateway Mode is not enabled', () => {+ expect(collectGatewayConfigIssues({ JWKS_KEY: jwks('fresh-key') })).toEqual([]);+ });++ it('lists every missing variable for an upgrade that kept the old .env', () => {+ const issues = collectGatewayConfigIssues({+ AGENT_GATEWAY_SERVICE_TOKEN: '',+ ENABLE_AGENT_GATEWAY: '1',+ });++ expect(issues).toHaveLength(1);+ expect(issues[0].vars).toEqual([+ 'AGENT_GATEWAY_URL',+ 'GATEWAY_SERVICE_TOKEN',+ 'JWKS_KEY',+ 'JWKS_PUBLIC_KEY',+ ]);+ });++ it('treats setup.sh placeholders as missing', () => {+ const issues = collectGatewayConfigIssues({+ ...configured,+ AGENT_GATEWAY_SERVICE_TOKEN: 'YOUR_GATEWAY_SERVICE_TOKEN',+ JWKS_KEY: 'YOUR_JWKS_KEY',+ JWKS_PUBLIC_KEY: 'YOUR_JWKS_PUBLIC_KEY',+ });++ expect(issues[0].vars).toEqual(['GATEWAY_SERVICE_TOKEN', 'JWKS_KEY', 'JWKS_PUBLIC_KEY']);+ });++ it('flags a JWKS_KEY that is not valid JSON', () => {+ const issues = collectGatewayConfigIssues({ ...configured, JWKS_KEY: '{not json' });++ expect(issues[0].vars).toEqual(['JWKS_KEY (not valid JWKS JSON)']);+ });++ it('flags the public example JWKS_KEY even when Gateway Mode is off', () => {+ const issues = collectGatewayConfigIssues({ JWKS_KEY: jwks(PUBLIC_EXAMPLE_JWKS_KID) });++ expect(issues.map((issue) => issue.name)).toEqual(['Public example JWKS_KEY']);+ });++ it('flags an upgrade that still passes the full JWKS_KEY to the gateway', () => {+ const issues = collectGatewayConfigIssues({+ ...configured,+ JWKS_PUBLIC_KEY: configured.JWKS_KEY,+ });++ expect(issues.map((issue) => issue.name)).toEqual(['JWKS_PUBLIC_KEY contains the private key']);+ });++ it('flags a JWKS_PUBLIC_KEY derived from a different key', () => {+ const issues = collectGatewayConfigIssues({+ ...configured,+ JWKS_PUBLIC_KEY: jwks('fresh-key', { n: 'another-modulus' }),+ });++ expect(issues.map((issue) => issue.name)).toEqual(['JWKS_PUBLIC_KEY does not match JWKS_KEY']);+ });+});++describe('checkGatewayConfig', () => {+ it('prints a warning without exiting when configuration is incomplete', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const exit = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never);++ checkGatewayConfig({ ENABLE_AGENT_GATEWAY: '1' });++ expect(warn.mock.calls.flat().join('\n')).toContain('ACTION REQUIRED');+ expect(exit).not.toHaveBeenCalled();++ warn.mockRestore();+ exit.mockRestore();+ });++ it('stays silent when configuration is complete', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ checkGatewayConfig(configured);++ expect(warn).not.toHaveBeenCalled();+ warn.mockRestore();+ });+});diff --git a/scripts/dockerComposeDeploy.test.ts b/scripts/dockerComposeDeploy.test.tsindex 718786ba96c..86f079b69d3 100644--- a/scripts/dockerComposeDeploy.test.ts+++ b/scripts/dockerComposeDeploy.test.ts@@ -207,9 +207,9 @@ describe('deploy docker-compose optional Elasticsearch', () => {}});- it('keeps the in-network Elasticsearch URL on plain HTTP when setup.sh switches to HTTPS', () => {+ it('keeps in-network URLs on plain HTTP when setup.sh switches to HTTPS', () => {const sedExpression =- "'/^#\\{0,1\\} \\{0,1\\}[A-Za-z0-9_]*=/{/ES_URL=/!s|http://|https://|;}' .env";+ "'/^#\\{0,1\\} \\{0,1\\}[A-Za-z0-9_]*=/{/ES_URL=/!{/DEVICE_GATEWAY_URL=/!s|http://|https://|;};}' .env";expect(setupScript).toContain(sedExpression);// The rewrite must only touch assignments: the warning comment that tells operators not to// pair ES_API_KEY with an http:// URL has to keep saying http://.@@ -217,12 +217,17 @@ describe('deploy docker-compose optional Elasticsearch', () => {const rewritten = envExample.split('\n').map((line) =>- /^#? ?\w*=/.test(line) && !line.includes('ES_URL=')+ /^#? ?\w*=/.test(line) &&+ !line.includes('ES_URL=') &&+ !line.includes('DEVICE_GATEWAY_URL=')? line.replace('http://', 'https://'): line,).join('\n');expect(rewritten).toContain('# ES_URL=http://elasticsearch:9200\n');+ // The device gateway is reached by the server over the Compose network, never through TLS.+ expect(rewritten).toContain('DEVICE_GATEWAY_URL=http://gateway:8788\n');+ expect(rewritten).toContain('AGENT_GATEWAY_URL=https://localhost:8787\n');expect(rewritten).toContain('http:// ');expect(rewritten).not.toContain('https:// ');}@@ -327,4 +332,37 @@ describe('setup.sh one-click install', () => {const wgetOnly = createStubPath({ wget: 'echo wget > "$3"' });expect(runInBash(script, wgetOnly)).toBe('wget');});++ it('generates a matching key pair whose public half carries no private key fields', () => {+ const bin = createStubPath({});+ symlinkSync(process.execPath, path.join(bin, 'node'));++ const output = runInBash(+ `${extractFunction('generate_jwks_key_pair')}\ngenerate_jwks_key_pair`,+ bin,+ );+ const [privateKey, publicKey] = output.split('\n').map((line) => JSON.parse(line).keys[0]);++ expect(privateKey).toMatchObject({ alg: 'RS256', kty: 'RSA' });+ expect(privateKey.d).toBeTruthy();+ for (const field of ['d', 'p', 'q', 'dp', 'dq', 'qi']) {+ expect(publicKey).not.toHaveProperty(field);+ }+ expect(publicKey).toMatchObject({+ alg: 'RS256',+ kid: privateKey.kid,+ kty: 'RSA',+ n: privateKey.n,+ });+ });++ it('passes only the public key to the gateway container', () => {+ const { gateway } = compose.services;++ expect(gateway.environment).toContain('JWKS_PUBLIC_KEY=${JWKS_PUBLIC_KEY:-}');+ expect(gateway.environment?.join('\n')).not.toMatch(/\$\{JWKS_KEY\b/);+ for (const envExample of envExamples) {+ expect(envExample).toContain('JWKS_PUBLIC_KEY=YOUR_JWKS_PUBLIC_KEY\n');+ }+ });});diff --git a/scripts/serverLauncher/startServer.js b/scripts/serverLauncher/startServer.jsindex e0618d3d007..8d40f1cb4e1 100644--- a/scripts/serverLauncher/startServer.js+++ b/scripts/serverLauncher/startServer.js@@ -12,6 +12,11 @@ const dockerPath = '/app/scripts/_shared/checkDeprecatedAuth.js';const sharedModulePath = existsSync(localPath) ? localPath : dockerPath;const { checkDeprecatedAuth } = require(sharedModulePath);+const gatewayCheckLocalPath = path.join(__dirname, '..', '_shared', 'checkGatewayConfig.js');+const gatewayCheckDockerPath = '/app/scripts/_shared/checkGatewayConfig.js';+const { checkGatewayConfig } = require(+ existsSync(gatewayCheckLocalPath) ? gatewayCheckLocalPath : gatewayCheckDockerPath,+);// Set file pathsconst DB_MIGRATION_SCRIPT_PATH = '/app/docker.cjs';@@ -241,6 +246,8 @@ const runServer = async () => {(async () => {// Check for deprecated auth env vars first - fail fast if foundcheckDeprecatedAuth({ action: 'restart' });+ // Warn loudly when an upgraded Compose stack enables Gateway Mode without its .env settings+ checkGatewayConfig();console.log('🌐 DNS Server:', dns.getServers());console.log('-------------------------------------');diff --git a/scripts/serverLauncher/startServer.test.ts b/scripts/serverLauncher/startServer.test.tsindex 78e701f4a5a..a58ad94c2cc 100644--- a/scripts/serverLauncher/startServer.test.ts+++ b/scripts/serverLauncher/startServer.test.ts@@ -36,7 +36,8 @@ const launch = async (env: Record<string, string>, failure?: { code: number; scrthrow new Error('launcher exited');},},- require: (name: string) => modules[name] ?? { checkDeprecatedAuth: () => undefined },+ require: (name: string) =>+ modules[name] ?? { checkDeprecatedAuth: () => undefined, checkGatewayConfig: () => [] },}).catch((error: Error) => {if (error.message !== 'launcher exited') throw error;