From 757ce6d08ada508f9420e544e0469007e4de5013 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 22 Oct 2026 13:19:35 +0300 Subject: [PATCH] fix(iot-hub): limit the host field to DIRECT_MQTT and reduce input to a bare host Review follow-up for the device install host field: - Only DIRECT_MQTT packages that use ${mqtt.host} get the field. ChirpStack packages build the ThingsBoard URL from ${mqtt.host} and gateway packages put it into docker-compose; they keep the resolved value until handled separately. - The input is reduced to the bare host: any scheme, port and path are dropped, so a pasted http://192.168.1.10:8080 no longer ends up in the sketch with the port, and http://localhost:8080 is rejected as loopback. - The field is labelled "MQTT host"; the MQTT host can differ from the address of the ThingsBoard web UI. - The loopback check comment says what is checked instead of claiming to mirror DeviceConnectivityUtil.isLocalhost. --- .../device-install-dialog.component.ts | 126 ++++++++++-------- .../assets/locale/locale.constant-en_US.json | 10 +- 2 files changed, 75 insertions(+), 61 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index c5b69db9ea..825db7461a 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -36,6 +36,7 @@ import { FormFieldType, installMethodIcons as INSTALL_METHOD_ICONS, installMethodLabels as INSTALL_METHOD_LABELS, + InstallMethod, InstallStepType, peOnlyInstallMethods, stepTypeAliasMap @@ -71,20 +72,45 @@ export interface WizardStep { const ENTITY_STEP_MIN_DELAY = 2000; const DEFAULT_RANDOM_SIZE = 20; -const SERVER_HOST_FIELD_KEY = 'tbServerHost'; -const TRANSPORT_HOST_VARIABLE = /\$\{([a-z]+)\.host}/g; - -const normalizeHost = (host: string): string => - host.trim().replace(/^https?:\/\//i, '').replace(/\/+$/, ''); +const TRANSPORT_HOST_FIELD_KEY = 'tbTransportHost'; + +// Install methods whose packages get a transport host field, and the transport whose +// ${.host} it fills. Other methods use the host differently (a ChirpStack package +// builds the ThingsBoard URL from it, a gateway puts it into docker-compose) and keep the +// resolved value until they are handled separately. +const HOST_FIELD_TRANSPORTS = new Map([ + [InstallMethod.DIRECT_MQTT, 'mqtt'] +]); + +/** + * Reduces what a user may paste (a URL, host:port, [IPv6]:port) to the bare host: the port is + * a separate setting, and the scheme or path would end up in the firmware as part of the host. + */ +const toBareHost = (value: string): string => { + const hostPort = value.trim().replace(/^[a-z][a-z\d+.-]*:\/\//i, '').replace(/[/?#].*$/, ''); + const bracketed = hostPort.match(/^\[([^\]]*)](:\d*)?$/); + if (bracketed) { + return bracketed[1]; + } + // A bare IPv6 address has several colons; a single one separates the port. + return hostPort.split(':').length === 2 ? hostPort.split(':')[0] : hostPort; +}; -// Mirrors DeviceConnectivityUtil.isLocalhost: a device can't reach the server at such an address. +// localhost, 127.0.0.0/8, ::1 and 0.0.0.0: a device can't reach the server at any of them. +// Unlike DeviceConnectivityUtil.isLocalhost this doesn't resolve hostnames, and it also +// rejects 0.0.0.0, which isn't a loopback address but is just as unreachable. const isLoopbackHost = (host: string): boolean => { - const h = normalizeHost(host).toLowerCase().replace(/^\[(.*)]$/, '$1'); + const h = toBareHost(host).toLowerCase(); return h === 'localhost' || h === '::1' || h === '0.0.0.0' || /^127(\.\d{1,3}){3}$/.test(h); }; -const serverHostValidator = (control: AbstractControl): ValidationErrors | null => - control.value && isLoopbackHost(control.value) ? { pattern: true } : null; +const transportHostValidator = (control: AbstractControl): ValidationErrors | null => { + if (!control.value) { + return null; + } + const host = toBareHost(control.value); + return !host || /\s/.test(host) || isLoopbackHost(host) ? { pattern: true } : null; +}; @Component({ selector: 'tb-device-install-dialog', @@ -126,8 +152,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); - // Transports whose ${.host} the server host field overrides - private serverHostProtocols: string[] = []; + // Transport whose ${.host} the transport host field overrides + private hostFieldProtocol: string | null = null; gatewayDockerComposeContent: string | null = null; resolveMarkdownVariable: (key: string) => string | undefined = this._resolveMarkdownVariable.bind(this); @@ -507,10 +533,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent key === `${p}.host`)) { - const serverHost = normalizeHost(String(this.formValues[SERVER_HOST_FIELD_KEY] ?? '')); - if (serverHost) { - return serverHost; + if (this.hostFieldProtocol && key === `${this.hostFieldProtocol}.host`) { + const host = toBareHost(String(this.formValues[TRANSPORT_HOST_FIELD_KEY] ?? '')); + if (host) { + return host; } } if (key in this.transportVars) { @@ -695,7 +721,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent.host} into sketches and templates. Ask for that address in the - * last form before its first use, so the user can correct it — and must, when the server - * resolved it to localhost, which on the device is the device itself. + * Packages write ${.host} into sketches and templates. Ask for that host in the last + * form before its first use, so the user can correct it — and must, when the server resolved it + * to localhost, which on the device is the device itself. */ - private addServerHostField(fromIndex: number): void { - this.serverHostProtocols = []; - const steps = this.wizardSteps.slice(fromIndex); - const firstUse = steps.findIndex(ws => this.hostProtocols(ws).length > 0); - if (firstUse < 0) { + private addTransportHostField(fromIndex: number): void { + this.hostFieldProtocol = null; + const protocol = HOST_FIELD_TRANSPORTS.get(this.selectedInstallMethod); + const resolvedHost = protocol ? this.transportVars[`${protocol}.host`] : undefined; + if (resolvedHost === undefined) { return; } - const protocols = [...new Set(steps.flatMap(ws => this.hostProtocols(ws)))]; - const reachableHosts = new Set(protocols.map(p => this.transportVars[`${p}.host`]) - .filter(host => host && !isLoopbackHost(host))); - if (reachableHosts.size > 1) { - // Transports are configured with different hosts; one field can't stand for all of them. + const steps = this.wizardSteps.slice(fromIndex); + const firstUse = steps.findIndex(ws => this.usesHost(ws, protocol)); + if (firstUse < 0) { return; } - const resolvedHost = this.transportVars[`${protocols[0]}.host`]; - const defaultHost: string = reachableHosts.values().next().value ?? ''; + const defaultHost = resolvedHost && !isLoopbackHost(resolvedHost) ? resolvedHost : ''; let formStep = steps.slice(0, firstUse).reverse().find(ws => ws.type === 'form'); if (!formStep) { formStep = { type: 'form', - label: this.translate.instant('iot-hub.device-install-server-host-step'), + label: this.translate.instant('iot-hub.device-install-transport-host-step'), rawSteps: [], completed: this.reviewMode }; this.wizardSteps.splice(fromIndex + firstUse, 0, formStep); } - const errorMessage = this.translate.instant('iot-hub.device-install-server-host-error'); + const errorMessage = this.translate.instant('iot-hub.device-install-transport-host-error'); formStep.extraFormFields = [{ - key: SERVER_HOST_FIELD_KEY, - label: this.translate.instant('iot-hub.device-install-server-host'), + key: TRANSPORT_HOST_FIELD_KEY, + label: this.translate.instant('iot-hub.device-install-mqtt-host'), type: FormFieldType.STRING, defaultValue: defaultHost, required: true, helpText: defaultHost || this.reviewMode - ? this.translate.instant('iot-hub.device-install-server-host-hint') - : this.translate.instant('iot-hub.device-install-server-host-loopback-hint', { host: resolvedHost }), - validators: [{ pattern: '\\S+', message: errorMessage }] + ? this.translate.instant('iot-hub.device-install-mqtt-host-hint') + : this.translate.instant('iot-hub.device-install-mqtt-host-loopback-hint', { host: resolvedHost }), + // transportHostValidator does the check; the entry carries the message the renderer shows + validators: [{ pattern: '.*', message: errorMessage }] }]; - this.serverHostProtocols = protocols; + this.hostFieldProtocol = protocol; } - private hostProtocols(ws: WizardStep): string[] { - const protocols: string[] = []; - for (const step of ws.rawSteps) { - const files = [step.file, step.template, step.serverAttributes, step.sharedAttributes, - step.credentials, step.dockerCompose]; - for (const file of files) { - const content = file ? this.zipFiles.get(file) : undefined; - for (const [, protocol] of content?.matchAll(TRANSPORT_HOST_VARIABLE) ?? []) { - if (`${protocol}.host` in this.transportVars) { - protocols.push(protocol); - } - } - } - } - return protocols; + private usesHost(ws: WizardStep, protocol: string): boolean { + const placeholder = `\${${protocol}.host}`; + return ws.rawSteps.some(step => + [step.file, step.template, step.serverAttributes, step.sharedAttributes, step.credentials, step.dockerCompose] + .some(file => file && this.zipFiles.get(file)?.includes(placeholder))); } private initFormStep(ws: WizardStep): void { @@ -782,8 +796,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent 0) { validators.push(Validators.pattern(field.validators[0].pattern)); } - if (field.key === SERVER_HOST_FIELD_KEY) { - validators.push(serverHostValidator); + if (field.key === TRANSPORT_HOST_FIELD_KEY) { + validators.push(transportHostValidator); } const initialValue = this.resolveInitialFieldValue(field, storedValues?.[field.key]); controls[field.key] = new UntypedFormControl(initialValue, validators); diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 7f4e1f656b..7bf4b364e3 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3920,11 +3920,11 @@ "device-install-step-type-RULE_CHAIN": "Rule Chain", "device-install-conflict-exists": "{{type}} with this name already exists", "device-install-use-existing": "Use existing", - "device-install-server-host-step": "Server address", - "device-install-server-host": "ThingsBoard server address", - "device-install-server-host-hint": "IP address or hostname the device uses to reach ThingsBoard", - "device-install-server-host-loopback-hint": "The server address resolved to {{host}}, which on the device means the device itself. Enter the IP address or hostname of your ThingsBoard server.", - "device-install-server-host-error": "Enter an IP address or hostname the device can reach, without spaces and not localhost", + "device-install-transport-host-step": "Connection", + "device-install-mqtt-host": "MQTT host", + "device-install-mqtt-host-hint": "Host the device connects to over MQTT. It may differ from the ThingsBoard web address.", + "device-install-mqtt-host-loopback-hint": "The MQTT host resolved to {{host}}, which on the device means the device itself. Enter the IP address or hostname the device can reach ThingsBoard's MQTT transport at.", + "device-install-transport-host-error": "Enter a host name or IP address the device can reach (not localhost)", "device-install-overwrite": "Overwrite", "device-install-create-copy": "Create copy", "device-install-resolution-created": "Created",