feat(web): make the device enrollment command address configurable (#2742)

The console derived the config-server address in the enrollment command from the host the dashboard was opened with, which is wrong behind a reverse proxy, a port mapping or NAT.

Add --config-server-host (ET_CONFIG_SERVER_HOST) to easytier-web. It accepts a host, host:port or a full URL such as udp://et.example.com:22020, and is returned by /api/v1/console-info as config_server_host. The dashboard prefers it and falls back to the browser origin when it is unset, so existing deployments keep their behavior.

Both enrollment command displays (dashboard popover and empty device list) now share modules/enroll.ts instead of computing the host separately.

---------

Co-authored-by: 225284228a-droid <239500008+225284228a-droid@users.noreply.github.com>
Co-authored-by: KKRainbow <5665404+KKRainbow@users.noreply.github.com>
This commit is contained in:
刚刚
2026-11-16 21:45:31 +08:00
committed by GitHub
co-authored by 225284228a-droid KKRainbow
parent 0d9c52b169
commit 175a1c79a3
9 changed files with 77 additions and 14 deletions
@@ -7,6 +7,7 @@ import { Utils } from 'easytier-frontend-lib';
import DeviceDetails from './DeviceDetails.vue';
import { useI18n } from 'vue-i18n'
import ApiClient from '../modules/api';
import { enrollCommand as buildEnrollCommand } from '../modules/enroll';
const { t } = useI18n()
@@ -42,12 +43,7 @@ watch(viewMode, (mode) => localStorage.setItem('deviceList.viewMode', mode));
// Zero-device state is where users look for "how do I add one": surface
// the enrollment command right there.
const enrollInfo = ref<Awaited<ReturnType<ApiClient['get_console_info']>> | null>(null);
const enrollCommand = computed(() => {
if (!enrollInfo.value) return '';
const host = window.location.hostname;
const { config_server_protocol: proto, config_server_port: port, username } = enrollInfo.value;
return `easytier-core --config-server ${proto}://${host}:${port}/${username}`;
});
const enrollCommand = computed(() => enrollInfo.value ? buildEnrollCommand(enrollInfo.value) : '');
const copyEnrollCommand = async () => {
try {
@@ -25,6 +25,7 @@ import Icon from '../assets/easytier.png'
import { useI18n } from 'vue-i18n'
import ApiClient, { type BlockedDevice, type CentralNetworkSummary } from '../modules/api';
import { getApiBase } from '../modules/api-host';
import { enrollCommand as buildEnrollCommand } from '../modules/enroll';
const { t } = useI18n()
const router = useRouter();
@@ -107,12 +108,7 @@ watch([() => enrollInfo.value?.webhook_auth, () => route.name], ([external, name
}
});
const enrollCommand = computed(() => {
if (!enrollInfo.value) return '';
const host = new URL(getApiBase(), window.location.href).hostname;
const { config_server_protocol: proto, config_server_port: port, username } = enrollInfo.value;
return `easytier-core --config-server ${proto}://${host}:${port}/${username}`;
});
const enrollCommand = computed(() => enrollInfo.value ? buildEnrollCommand(enrollInfo.value) : '');
const toggleEnrollBell = async (event: Event) => {
enrollBell.value.toggle(event);
+3
View File
@@ -175,6 +175,9 @@ export interface ConsoleInfo {
username: string;
config_server_protocol: string;
config_server_port: number;
/// Operator-configured address for the enrollment command; absent when the
/// dashboard should use the browser origin.
config_server_host?: string | null;
webhook_auth: boolean;
}
@@ -0,0 +1,31 @@
import type { ConsoleInfo } from './api';
import { getApiBase } from './api-host';
// Devices reach the console through whatever address the deployment exposes,
// which is not necessarily the host the dashboard is opened with (reverse
// proxy, port mapping, NAT). Operators can pin that address with
// --config-server-host, given as host, host:port or a full URL such as
// udp://et.example.com:22020. Without it the browser origin stands in.
const configuredHost = (info: ConsoleInfo): string => info.config_server_host?.trim() ?? '';
// An authority already carrying a port wins over --config-server-port, so
// host:443 keeps working when the console itself listens on 22020.
const hasExplicitPort = (authority: string): boolean =>
authority.startsWith('[') ? /^\[[^\]]*\]:\d+$/.test(authority) : /^[^:]+:\d+$/.test(authority);
// The config-server URL embedded in the enrollment command.
export const enrollEndpoint = (info: ConsoleInfo): string => {
const configured = configuredHost(info);
if (configured) {
const scheme = configured.match(/^([a-z][a-z0-9+.-]*):\/\/(.*)$/i);
const protocol = scheme ? scheme[1].toLowerCase() : info.config_server_protocol;
const host = (scheme ? scheme[2] : configured).split('/')[0];
return `${protocol}://${hasExplicitPort(host) ? host : `${host}:${info.config_server_port}`}`;
}
const host = new URL(getApiBase(), window.location.href).hostname;
return `${info.config_server_protocol}://${host}:${info.config_server_port}`;
};
// The command a device runs to enroll into this console.
export const enrollCommand = (info: ConsoleInfo): string =>
`easytier-core --config-server ${enrollEndpoint(info)}/${info.username}`;
+15 -2
View File
@@ -43,7 +43,7 @@ function fixture() {
online_member_count: 1, member_count: 2, network_secret: 'test-secret', peer_urls: i === 0 ? [] : ['tcp://192.0.2.1:11010'],
}));
const members = [{ member_id: id(101), device_id: id(1), hostname: 'Amsterdam gateway', hostname_override: null, virtual_ipv4: '10.126.126.1', online: true, running: true, version: '2.4.5', error_msg: null, runtime_virtual_ipv4: '10.126.126.1' }];
return { machines, networks, members, memberConfig: {}, aclPolicy: { default_action: 'allow', rules: [] }, credentials: [], temporaryPeers: [], nodeRoutes: [], nodePeers: [], nodeAclStats: [], loggerConfig: { level: 'INFO' }, writes: [], requests: [], failures: new Set(), gatewayDelay: 0, gatewayEnabled: true };
return { machines, networks, members, memberConfig: {}, aclPolicy: { default_action: 'allow', rules: [] }, credentials: [], temporaryPeers: [], nodeRoutes: [], nodePeers: [], nodeAclStats: [], loggerConfig: { level: 'INFO' }, writes: [], requests: [], failures: new Set(), gatewayDelay: 0, gatewayEnabled: true, configServerHost: null };
}
async function open(t, route = '/h', options = {}, configure = () => {}) {
@@ -83,7 +83,7 @@ async function open(t, route = '/h', options = {}, configure = () => {}) {
if (state.failures.has(path)) return route.fulfill({ status: 503, json: { message: 'Test unavailable' } });
let result = {};
if (path === '/summary') result = { device_count: state.machines.length };
else if (path === '/console-info') result = { username: 'test-user', config_server_protocol: 'udp', config_server_port: 22020, webhook_auth: state.externalConsole ?? false };
else if (path === '/console-info') result = { username: 'test-user', config_server_protocol: 'udp', config_server_port: 22020, config_server_host: state.configServerHost, webhook_auth: state.externalConsole ?? false };
else if (path === '/machines') result = { machines: state.machines };
else if (path === '/networks/gateway-info') {
await delay(state.gatewayDelay);
@@ -178,6 +178,19 @@ for (const [apiHost, hostname] of [
});
}
for (const [configured, expected] of [
['et.example.com', 'udp://et.example.com:22020'],
['et.example.com:8443', 'udp://et.example.com:8443'],
['udp://et.example.com', 'udp://et.example.com:22020'],
['tcp://et.example.com:11010', 'tcp://et.example.com:11010'],
]) {
test(`enrollment command advertises the configured config server address ${configured}`, async t => {
const { page } = await open(t, '/h', {}, state => { state.configServerHost = configured; });
await page.getByRole('button', { name: 'Device Enrollment', exact: true }).click();
await page.getByText(`easytier-core --config-server ${expected}/test-user`).waitFor();
});
}
test('device search, sort, expansion and routed drawer survive reload and history', async t => {
const { page } = await open(t, '/h/deviceList');
const table = page.locator('.desktop-list');
+3
View File
@@ -19,6 +19,9 @@ cli:
config_server_protocol:
en: "The protocol to listen for the config server, used by the easytier-core to connect to, possible values: udp, tcp, ws"
zh-CN: "配置服务器的监听协议,用于被 easytier-core 连接, 可能的值:udp, tcp, ws"
config_server_host:
en: "The address advertised in the device enrollment command shown by the web console, as host, host:port or URL (e.g. udp://et.example.com:22020). Defaults to the host the browser used to reach the console"
zh-CN: "web 控制台展示的“设备接入命令”中使用的地址,可写成 host、host:port 或 URL(例如 udp://et.example.com:22020)。默认使用浏览器访问控制台时的地址"
api_server_port:
en: "The port to listen for the restful server, acting as ApiHost and used by the web frontend"
zh-CN: "restful 服务器的监听端口,作为 ApiHost 并被 web 前端使用"
+8
View File
@@ -93,6 +93,13 @@ struct Cli {
)]
config_server_protocol: String,
#[arg(
long,
env = "ET_CONFIG_SERVER_HOST",
help = t!("cli.config_server_host").to_string(),
)]
config_server_host: Option<String>,
#[arg(
long,
short='a',
@@ -466,6 +473,7 @@ async fn main() {
webhook_config,
cli.config_server_protocol.clone(),
cli.config_server_port,
cli.config_server_host.clone(),
)
.await
.unwrap()
+12
View File
@@ -50,6 +50,9 @@ pub struct RestfulServer {
webhook_config: SharedWebhookConfig,
config_server_protocol: String,
config_server_port: u16,
/// Address advertised in the device enrollment command. When unset the
/// dashboard falls back to the origin the browser used.
config_server_host: Option<String>,
db: Db,
oidc_config: oidc::OidcConfig,
web_router: Option<Router>,
@@ -70,6 +73,7 @@ struct GetSummaryJsonResp {
struct ConsoleInfoConfig {
config_server_protocol: String,
config_server_port: u16,
config_server_host: Option<String>,
webhook_auth: bool,
}
@@ -78,6 +82,8 @@ struct GetConsoleInfoJsonResp {
username: String,
config_server_protocol: String,
config_server_port: u16,
#[serde(skip_serializing_if = "Option::is_none")]
config_server_host: Option<String>,
webhook_auth: bool,
}
@@ -155,6 +161,7 @@ impl RestfulServer {
webhook_config: SharedWebhookConfig,
config_server_protocol: String,
config_server_port: u16,
config_server_host: Option<String>,
) -> anyhow::Result<Self> {
assert!(client_mgr.is_running());
@@ -166,6 +173,9 @@ impl RestfulServer {
webhook_config,
config_server_protocol,
config_server_port,
config_server_host: config_server_host
.map(|host| host.trim().to_string())
.filter(|host| !host.is_empty()),
db,
oidc_config,
web_router,
@@ -222,6 +232,7 @@ impl RestfulServer {
username: user.db_user.username,
config_server_protocol: config.config_server_protocol,
config_server_port: config.config_server_port,
config_server_host: config.config_server_host,
webhook_auth: config.webhook_auth,
}
.into())
@@ -361,6 +372,7 @@ impl RestfulServer {
.layer(Extension(ConsoleInfoConfig {
config_server_protocol: self.config_server_protocol.clone(),
config_server_port: self.config_server_port,
config_server_host: self.config_server_host.clone(),
webhook_auth: self.webhook_config.has_external_endpoint(),
}))
.layer(MessagesManagerLayer)
+1
View File
@@ -1061,6 +1061,7 @@ mod tests {
let config = super::super::ConsoleInfoConfig {
config_server_protocol: "tcp".into(),
config_server_port: 22020,
config_server_host: None,
webhook_auth: true,
};
let machines = NetworkApi::handle_list_machines(