Skip to content

🤯 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.

✨ feat(gateway): optionally advertise a public Device Gateway URL (#20721)

Bryanbe16179c7383
diff --git a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
index 31ee738f489..cdc8334a0ef 100644
--- a/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
+++ b/apps/server/src/globalConfig/getServerGlobalConfig.test.ts
@@ -146,6 +146,7 @@ const loadServerConfig = async (
describe('getServerGlobalConfig', () => {
afterEach(() => {
vi.restoreAllMocks();
+ vi.unstubAllEnvs();
});
it('should only enable LobeHub by default in business feature mode', async () => {
@@ -266,4 +267,15 @@ describe('getServerGlobalConfig', () => {
});
}
});
+
+ it('should expose DEVICE_GATEWAY_PUBLIC_URL without a device gateway service token', async () => {
+ vi.stubEnv('DEVICE_GATEWAY_PUBLIC_URL', 'https://device-gateway.example.com');
+ vi.stubEnv('DEVICE_GATEWAY_SERVICE_TOKEN', undefined);
+ vi.stubEnv('DEVICE_GATEWAY_URL', undefined);
+
+ await expect(loadServerConfig(false)).resolves.toHaveProperty(
+ 'deviceGatewayUrl',
+ 'https://device-gateway.example.com',
+ );
+ });
});
diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.ts
index fbd5b90ace3..6479a967f97 100644
--- a/apps/server/src/globalConfig/index.ts
+++ b/apps/server/src/globalConfig/index.ts
@@ -7,6 +7,7 @@ import { isDesktop } from '@/const/version';
import { appEnv, getAppConfig } from '@/envs/app';
import { authEnv } from '@/envs/auth';
import { fileEnv } from '@/envs/file';
+import { gatewayEnv } from '@/envs/gateway';
import { imageEnv } from '@/envs/image';
import { knowledgeEnv } from '@/envs/knowledge';
import { langfuseEnv } from '@/envs/langfuse';
@@ -124,6 +125,10 @@ export const getServerGlobalConfig = async () => {
defaultAgent: {
config: parseAgentConfig(DEFAULT_AGENT_CONFIG),
},
+ // Never fall back to the server-internal DEVICE_GATEWAY_URL.
+ ...(gatewayEnv.DEVICE_GATEWAY_PUBLIC_URL
+ ? { deviceGatewayUrl: gatewayEnv.DEVICE_GATEWAY_PUBLIC_URL }
+ : undefined),
disableEmailPassword: authEnv.AUTH_DISABLE_EMAIL_PASSWORD,
enableBusinessFeatures: ENABLE_BUSINESS_FEATURES,
enableEmailVerification: authEnv.AUTH_EMAIL_VERIFICATION,
diff --git a/apps/server/src/routers/lambda/config/index.test.ts b/apps/server/src/routers/lambda/config/index.test.ts
index 529d5c16abb..21336732232 100644
--- a/apps/server/src/routers/lambda/config/index.test.ts
+++ b/apps/server/src/routers/lambda/config/index.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import superjson from 'superjson';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* This file contains the root router of your tRPC-backend
@@ -162,6 +163,62 @@ describe('configRouter', () => {
}
});
});
+
+ // Asserted on the superjson payload, where an `undefined` key would still appear in meta.
+ describe('Device Gateway discovery', () => {
+ const PUBLIC_URL = 'https://device-gateway.example.com';
+ const INTERNAL_URL = 'http://gateway:8788';
+ const SERVICE_TOKEN = 'synthetic-device-gateway-service-token';
+
+ const getSerializedGlobalConfig = async (env: Record<string, string | undefined>) => {
+ for (const [name, value] of Object.entries(env)) vi.stubEnv(name, value);
+ // Env modules parse at import time.
+ vi.resetModules();
+
+ const [{ createCallerFactory }, { createContextInner }, { configRouter }] =
+ await Promise.all([
+ import('@/libs/trpc/lambda'),
+ import('@/libs/trpc/lambda/context'),
+ import('./index'),
+ ]);
+ const caller = createCallerFactory(configRouter)(await createContextInner());
+ const serialized = superjson.serialize(await caller.getGlobalConfig());
+
+ return {
+ serverConfig: (serialized.json as { serverConfig: Record<string, unknown> }).serverConfig,
+ wire: JSON.stringify(serialized),
+ };
+ };
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('omits deviceGatewayUrl from the response when no public address is configured', async () => {
+ const { serverConfig, wire } = await getSerializedGlobalConfig({
+ DEVICE_GATEWAY_PUBLIC_URL: undefined,
+ DEVICE_GATEWAY_SERVICE_TOKEN: SERVICE_TOKEN,
+ DEVICE_GATEWAY_URL: INTERNAL_URL,
+ });
+
+ expect(serverConfig).not.toHaveProperty('deviceGatewayUrl');
+ expect(wire).not.toContain('deviceGatewayUrl');
+ expect(wire).not.toContain(INTERNAL_URL);
+ expect(wire).not.toContain(SERVICE_TOKEN);
+ });
+
+ it('returns only the public address and no gateway credentials when configured', async () => {
+ const { serverConfig, wire } = await getSerializedGlobalConfig({
+ DEVICE_GATEWAY_PUBLIC_URL: PUBLIC_URL,
+ DEVICE_GATEWAY_SERVICE_TOKEN: SERVICE_TOKEN,
+ DEVICE_GATEWAY_URL: INTERNAL_URL,
+ });
+
+ expect(serverConfig.deviceGatewayUrl).toBe(PUBLIC_URL);
+ expect(wire).not.toContain(INTERNAL_URL);
+ expect(wire).not.toContain(SERVICE_TOKEN);
+ });
+ });
});
describe('getDefaultAgentConfig', () => {
diff --git a/docker-compose/deploy/.env.example b/docker-compose/deploy/.env.example
index 794e6bd48ba..6697d0db1aa 100644
--- a/docker-compose/deploy/.env.example
+++ b/docker-compose/deploy/.env.example
@@ -59,6 +59,9 @@ 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: device gateway address for desktop/CLI clients to discover from this server.
+# Leave unset to configure each client yourself (`lh connect --gateway <url>`).
+# DEVICE_GATEWAY_PUBLIC_URL=
# ===========================
# == Optional Elasticsearch ==
diff --git a/docker-compose/deploy/.env.zh-CN.example b/docker-compose/deploy/.env.zh-CN.example
index 5c1baad40c2..43b42745c35 100644
--- a/docker-compose/deploy/.env.zh-CN.example
+++ b/docker-compose/deploy/.env.zh-CN.example
@@ -54,6 +54,9 @@ DEVICE_GATEWAY_PORT=8788
AGENT_GATEWAY_URL=http://localhost:8787
# LobeHub 服务端在 Compose 网络内访问设备网关的地址
DEVICE_GATEWAY_URL=http://gateway:8788
+# 可选:供桌面端和 CLI 客户端从当前服务端发现的设备网关地址。
+# 不配置则由各客户端自行指定(`lh connect --gateway <url>`)。
+# DEVICE_GATEWAY_PUBLIC_URL=
# ===========================
# ===== 可选 Elasticsearch =====
diff --git a/docs/self-hosting/environment-variables/basic.mdx b/docs/self-hosting/environment-variables/basic.mdx
index 286ee479563..f61e6bd36cf 100644
--- a/docs/self-hosting/environment-variables/basic.mdx
+++ b/docs/self-hosting/environment-variables/basic.mdx
@@ -150,6 +150,20 @@ Business builds enable Gateway Mode automatically. Self-hosted deployments can s
- Default: -
- Example: `dev-secret`
+### `DEVICE_GATEWAY_URL`
+
+- Type: Optional
+- Description: Device Gateway endpoint for server-to-gateway requests, such as the Docker Compose service name. LobeHub uses it to reach connected devices. It stays on the server and is never sent to clients.
+- Default: -
+- Example: `http://gateway:8788`
+
+### `DEVICE_GATEWAY_PUBLIC_URL`
+
+- Type: Optional
+- Description: Device Gateway address as reached by desktop and CLI clients. When set, LobeHub publishes it in the server config (`deviceGatewayUrl`) so clients that support discovery can get the address from this server. When unset, nothing is published and clients keep the address configured on each of them, for example with `lh connect --gateway <url>`. Both ways work, and you can leave it unset permanently. Use the base address without a path such as `/ws`; a value with credentials, a query string or a fragment fails environment validation, and a trailing slash is removed. `DEVICE_GATEWAY_URL` is never published in its place.
+- Default: -
+- Example: `https://device-gateway.example.com` or `http://your_server_ip:8788`
+
### `PROXY_URL`
- Type: Optional
diff --git a/docs/self-hosting/environment-variables/basic.zh-CN.mdx b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
index 7c3693a4787..02256708f0f 100644
--- a/docs/self-hosting/environment-variables/basic.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
@@ -52,7 +52,7 @@ LobeHub 在部署时提供了一些额外的配置项,你可以使用环境变
| 配置项类型 | 示例 | 解释 |
| ----- | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| 基本键值对 | `model=gpt-4` | 设置模型为 `gpt-4`。 |
-| 嵌套字段 | `tts.voice.openai=nova` | 设置 OpenAI 文本转语音的默认音色为 `nova`。 |
+| 嵌套字段 | `tts.voice.openai=nova` | 设置 OpenAI 文本转语音的默认音色为 `nova`。 |
| 数组 | `plugins=search-engine,lobe-image-designer` | 启用 `search-engine` 和 `lobe-image-designer` 插件。 |
| 中文逗号 | `plugins=search-engine,lobe-image-designer` | 同上,演示支持中文逗号分隔。 |
| 多个配置项 | `model=glm-4;provider=zhipu` | 设置模型为 `glm-4` 且模型服务商为 `zhipu`。 |
@@ -146,6 +146,20 @@ LobeHub 在部署时提供了一些额外的配置项,你可以使用环境变
- 默认值:-
- 示例:`dev-secret`
+### `DEVICE_GATEWAY_URL`
+
+- 类型:可选
+- 描述:服务端访问 Device Gateway 使用的地址,例如 Docker Compose 服务名。LobeHub 通过它访问已连接的设备。该地址只在服务端使用,不会下发给客户端。
+- 默认值:-
+- 示例:`http://gateway:8788`
+
+### `DEVICE_GATEWAY_PUBLIC_URL`
+
+- 类型:可选
+- 描述:桌面端和 CLI 客户端访问 Device Gateway 使用的地址。配置后,LobeHub 会在服务端配置中下发该地址(`deviceGatewayUrl`),支持自动发现的客户端可以从当前服务端获取它。不配置时不下发任何地址,客户端继续使用各自配置的地址,例如 `lh connect --gateway <url>`。两种方式都可以使用,也可以一直不配置。请填写不带 `/ws` 等路径的基础地址;包含账号密码、查询参数或片段(`#`)的地址无法通过环境变量校验,末尾的 `/` 会被去掉。`DEVICE_GATEWAY_URL` 不会被用来代替它下发。
+- 默认值:-
+- 示例:`https://device-gateway.example.com` 或 `http://your_server_ip:8788`
+
### `PROXY_URL`
- 类型:可选
diff --git a/docs/self-hosting/platform/docker-compose.mdx b/docs/self-hosting/platform/docker-compose.mdx
index 44a6f9cf59e..80e24ab32b7 100644
--- a/docs/self-hosting/platform/docker-compose.mdx
+++ b/docs/self-hosting/platform/docker-compose.mdx
@@ -363,6 +363,8 @@ docker run --rm --entrypoint /bin/node lobehub/lobehub -e 'const c=require("cryp
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>
+`DEVICE_GATEWAY_PUBLIC_URL` is optional. Set it in `.env` to the device gateway address as reached by desktop and CLI clients, such as `http://your_server_ip:8788` or a domain you reverse proxy to port `8788` with WebSocket upgrades enabled. LobeHub then publishes it so clients that support discovery get the address from this server. Leave it unset to keep passing the address to each client yourself, as with `--gateway` above; both ways keep working, and existing deployments need no change. Don't copy the `DEVICE_GATEWAY_URL` value into it: `http://gateway:8788` only resolves inside the Compose network.
+
## Upgrading an Existing Deployment
<Callout type="warning">
diff --git a/docs/self-hosting/platform/docker-compose.zh-CN.mdx b/docs/self-hosting/platform/docker-compose.zh-CN.mdx
index 8d4d3444f0e..4c7298aa653 100644
--- a/docs/self-hosting/platform/docker-compose.zh-CN.mdx
+++ b/docs/self-hosting/platform/docker-compose.zh-CN.mdx
@@ -357,6 +357,8 @@ docker run --rm --entrypoint /bin/node lobehub/lobehub -e 'const c=require("cryp
通过 `lh connect --gateway http://your_server_ip:8788` 接入的设备,可以经由 `8788` 端口的设备网关为该部署执行本地工具。
</Callout>
+`DEVICE_GATEWAY_PUBLIC_URL` 为可选项。在 `.env` 中将其设置为桌面端和 CLI 客户端访问设备网关的地址,例如 `http://your_server_ip:8788`,或反向代理到 `8788` 端口并开启 WebSocket 升级的域名。配置后,LobeHub 会下发该地址,支持自动发现的客户端可以从当前服务端获取它。不配置时,继续像上面的 `--gateway` 一样为每个客户端自行指定地址;两种方式都可以使用,已有部署无需修改。不要直接复用 `DEVICE_GATEWAY_URL` 的值:`http://gateway:8788` 只能在 Compose 网络内解析。
+
## 升级已有部署
<Callout type="warning">
diff --git a/packages/env/src/__tests__/gateway.test.ts b/packages/env/src/__tests__/gateway.test.ts
new file mode 100644
index 00000000000..8dbd1ada171
--- /dev/null
+++ b/packages/env/src/__tests__/gateway.test.ts
@@ -0,0 +1,44 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { getGatewayConfig } from '../gateway';
+
+describe('DEVICE_GATEWAY_PUBLIC_URL', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it.each([undefined, '', ' '])('treats %j as not configured', (value) => {
+ vi.stubEnv('DEVICE_GATEWAY_PUBLIC_URL', value);
+
+ expect(getGatewayConfig().DEVICE_GATEWAY_PUBLIC_URL).toBeUndefined();
+ });
+
+ it.each([
+ ['https://device-gateway.example.com', 'https://device-gateway.example.com'],
+ ['http://192.168.1.10:8788', 'http://192.168.1.10:8788'],
+ ['https://example.com/device-gateway', 'https://example.com/device-gateway'],
+ ['https://device-gateway.example.com/', 'https://device-gateway.example.com'],
+ ])('accepts the http(s) base URL %j', (value, expected) => {
+ vi.stubEnv('DEVICE_GATEWAY_PUBLIC_URL', value);
+
+ expect(getGatewayConfig().DEVICE_GATEWAY_PUBLIC_URL).toBe(expected);
+ });
+
+ it.each([
+ 'not a url',
+ 'ftp://device-gateway.example.com',
+ 'https://user:[email protected]',
+ 'https://device-gateway.example.com/?token=synthetic-secret',
+ 'https://device-gateway.example.com/#synthetic-secret',
+ ])('fails validation for the non-empty invalid value %j', (value) => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.stubEnv('DEVICE_GATEWAY_PUBLIC_URL', value);
+
+ expect(() => getGatewayConfig()).toThrow('Invalid environment variables');
+ const report = JSON.stringify(consoleError.mock.calls);
+ expect(report).toContain('DEVICE_GATEWAY_PUBLIC_URL');
+ expect(report).not.toContain('synthetic-secret');
+ });
+});
diff --git a/packages/env/src/gateway.ts b/packages/env/src/gateway.ts
index aa772d76c26..0d3352e54b1 100644
--- a/packages/env/src/gateway.ts
+++ b/packages/env/src/gateway.ts
@@ -1,9 +1,25 @@
import { createEnv } from '@t3-oss/env-core';
import { z } from 'zod';
+// Compose forwards an unset `${VAR:-}` as `''`; blank means not configured.
+const blankToUndefined = (value: unknown) =>
+ typeof value === 'string' && value.trim() === '' ? undefined : value;
+
+// Public base URL clients append `/ws` to: nothing secret, no trailing slash.
+const publicBaseUrl = z
+ // `abort` skips the refine on unparseable input.
+ .url({ abort: true, protocol: /^https?$/ })
+ .refine((value) => {
+ const { password, username } = new URL(value);
+
+ return !username && !password && !/[?#]/.test(value);
+ }, 'Expected an http(s) base URL without credentials, query or fragment')
+ .transform((value) => value.replace(/\/+$/, ''));
+
export const getGatewayConfig = () => {
return createEnv({
runtimeEnv: {
+ DEVICE_GATEWAY_PUBLIC_URL: process.env.DEVICE_GATEWAY_PUBLIC_URL,
DEVICE_GATEWAY_SERVICE_TOKEN: process.env.DEVICE_GATEWAY_SERVICE_TOKEN,
DEVICE_GATEWAY_URL: process.env.DEVICE_GATEWAY_URL,
MESSAGE_GATEWAY_ENABLED: process.env.MESSAGE_GATEWAY_ENABLED,
@@ -15,6 +31,8 @@ export const getGatewayConfig = () => {
},
server: {
+ /** Optional client-facing address, published as `deviceGatewayUrl` in the global config. */
+ DEVICE_GATEWAY_PUBLIC_URL: z.preprocess(blankToUndefined, publicBaseUrl.optional()),
DEVICE_GATEWAY_SERVICE_TOKEN: z.string().optional(),
DEVICE_GATEWAY_URL: z.string().url().optional(),
MESSAGE_GATEWAY_ENABLED: z.string().optional(),
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 56414b1fb5d..e175688ecfd 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -122,6 +122,11 @@ export interface GlobalServerConfig {
agentGatewayUrl?: string;
aiProvider: ServerLanguageModel;
defaultAgent?: PartialDeep<UserDefaultAgent>;
+ /**
+ * Public Device Gateway base URL (`DEVICE_GATEWAY_PUBLIC_URL`). Absent when not
+ * configured; clients then keep the address they manage themselves.
+ */
+ deviceGatewayUrl?: string;
disableEmailPassword?: boolean;
enableBusinessFeatures?: boolean;
enableComposio?: boolean;