From 09407dfa9029638a00a5398e8261dbb1e63aef2b Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 22 Oct 2026 09:37:40 +0300 Subject: [PATCH] feat(iot-hub): ask for the ThingsBoard server address in the device install form Device packages put ${.host} into firmware sketches and templates. When ThingsBoard is opened via localhost and no device connectivity host is configured, that resolves to "localhost", which on a microcontroller is the device itself, so the flashed device never connects. The install dialog now detects packages that use ${.host} and adds a "ThingsBoard server address" field to the last form before its first use (or a separate "Server address" step if there is no such form). The field is prefilled with the resolved host; when that host is a loopback address it starts empty, is required and rejects loopback values. The entered address (scheme and trailing slash stripped) replaces ${.host} everywhere in the install. Packages that don't use the host get no field. --- .../device-install-dialog.component.ts | 98 ++++++++++++++++++- .../assets/locale/locale.constant-en_US.json | 5 + 2 files changed, 100 insertions(+), 3 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 33f2a6d08a..c5b69db9ea 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 @@ -10,7 +10,7 @@ import { import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { DialogComponent } from '@shared/components/dialog.component'; -import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; +import { AbstractControl, UntypedFormControl, UntypedFormGroup, ValidationErrors, Validators } from '@angular/forms'; import { MatStepper } from '@angular/material/stepper'; import { StepperSelectionEvent } from '@angular/cdk/stepper'; import { firstValueFrom } from 'rxjs'; @@ -60,6 +60,8 @@ export interface WizardStep { markdown?: string; // Form formFields?: FormFieldDefinition[]; + // Fields the dialog adds on top of the package's form file + extraFormFields?: FormFieldDefinition[]; formGroup?: UntypedFormGroup; // Progress entitySteps?: EntityStepProgress[]; @@ -69,6 +71,20 @@ 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(/\/+$/, ''); + +// Mirrors DeviceConnectivityUtil.isLocalhost: a device can't reach the server at such an address. +const isLoopbackHost = (host: string): boolean => { + const h = normalizeHost(host).toLowerCase().replace(/^\[(.*)]$/, '$1'); + 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; @Component({ selector: 'tb-device-install-dialog', @@ -110,6 +126,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); + // Transports whose ${.host} the server host field overrides + private serverHostProtocols: string[] = []; gatewayDockerComposeContent: string | null = null; resolveMarkdownVariable: (key: string) => string | undefined = this._resolveMarkdownVariable.bind(this); @@ -489,6 +507,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent key === `${p}.host`)) { + const serverHost = normalizeHost(String(this.formValues[SERVER_HOST_FIELD_KEY] ?? '')); + if (serverHost) { + return serverHost; + } + } if (key in this.transportVars) { return this.transportVars[key]; } @@ -633,6 +657,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. + */ + 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) { + 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. + return; + } + const resolvedHost = this.transportVars[`${protocols[0]}.host`]; + const defaultHost: string = reachableHosts.values().next().value ?? ''; + 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'), + rawSteps: [], + completed: this.reviewMode + }; + this.wizardSteps.splice(fromIndex + firstUse, 0, formStep); + } + const errorMessage = this.translate.instant('iot-hub.device-install-server-host-error'); + formStep.extraFormFields = [{ + key: SERVER_HOST_FIELD_KEY, + label: this.translate.instant('iot-hub.device-install-server-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.serverHostProtocols = protocols; + } + + 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 initFormStep(ws: WizardStep): void { - const formJson = this.zipFiles.get(ws.rawSteps[0].file) || '[]'; - ws.formFields = JSON.parse(formJson) as FormFieldDefinition[]; + const formJson = (ws.rawSteps[0] && this.zipFiles.get(ws.rawSteps[0].file)) || '[]'; + ws.formFields = [...JSON.parse(formJson) as FormFieldDefinition[], ...(ws.extraFormFields ?? [])]; const controls: Record = {}; // In review mode, use stored values; otherwise use defaults const storedValues = this.reviewMode && this.data.installState?.[ws.label]?.formValues; @@ -693,6 +782,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent 0) { validators.push(Validators.pattern(field.validators[0].pattern)); } + if (field.key === SERVER_HOST_FIELD_KEY) { + validators.push(serverHostValidator); + } 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 7974f825fc..7f4e1f656b 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3920,6 +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-overwrite": "Overwrite", "device-install-create-copy": "Create copy", "device-install-resolution-created": "Created",