diff --git a/.gitignore b/.gitignore index abfbb67..c87a6ec 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ work/ Thumbs.db console.config.json +console.config.json.* station-locations.json station-locations.json.tmp diff --git a/Enable-LAN.ps1 b/Enable-LAN.ps1 index 0246043..bcfdf75 100644 --- a/Enable-LAN.ps1 +++ b/Enable-LAN.ps1 @@ -1,5 +1,12 @@ $ErrorActionPreference='Stop' -$config=Get-Content -LiteralPath (Join-Path $PSScriptRoot 'console.config.json') -Raw | ConvertFrom-Json +$identity=[Security.Principal.WindowsIdentity]::GetCurrent() +if(!([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){throw 'Per creare la regola firewall aprire PowerShell come amministratore.'} +$configPath=if($env:BPQ_CONSOLE_CONFIG){$env:BPQ_CONSOLE_CONFIG}else{Join-Path $PSScriptRoot 'console.config.json'} +$config=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json +$port=if($env:BPQ_CONSOLE_PORT){[int]$env:BPQ_CONSOLE_PORT}else{[int]$config.port} +if($port -lt 1024 -or $port -gt 65535){throw 'Porta pannello non valida.'} $nodeExe=if($config.nodeExe -and (Test-Path -LiteralPath $config.nodeExe)){$config.nodeExe}else{(Get-Command node.exe -ErrorAction Stop).Source} -Get-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -ErrorAction SilentlyContinue | Remove-NetFirewallRule -New-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -Direction Inbound -Action Allow -Protocol TCP -LocalPort $config.port -RemoteAddress LocalSubnet -Program $nodeExe -Profile Private | Out-Null +# Create the replacement before removing the previous rule, so failure keeps it intact. +$rule=New-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -Direction Inbound -Action Allow -Protocol TCP -LocalPort $port -RemoteAddress LocalSubnet -Program $nodeExe -Profile Private -ErrorAction Stop +Get-NetFirewallRule -DisplayName 'BPQ Web Console LAN' -ErrorAction SilentlyContinue | Where-Object {$_.Name -ne $rule.Name} | Remove-NetFirewallRule +Write-Host "Accesso LAN abilitato sulla porta $port (rete Privata, sottorete locale)." diff --git a/Install.ps1 b/Install.ps1 index 7154819..d8c9afc 100644 --- a/Install.ps1 +++ b/Install.ps1 @@ -1,28 +1,53 @@ -param([string]$BpqRoot,[int]$Port=8090,[int]$HttpPort,[int]$RadioPort,[string]$SysopUser,[string]$ForwardPeer,[switch]$CheckOnly,[switch]$AutoStart,[switch]$EnableLAN) +param([string]$BpqRoot,[int]$Port,[int]$HttpPort,[int]$RadioPort,[string]$SysopUser,[string]$ForwardPeer,[string]$CmsPeer,[string]$VaraLogPath,[string]$NodeExe,[switch]$EnableRadioCAT,[switch]$DisableRadioCAT,[switch]$CheckOnly,[switch]$AutoStart,[switch]$EnableLAN,[switch]$Restart) $ErrorActionPreference='Stop' -$nodeExe=(Get-Command node.exe -ErrorAction Stop).Source -$major=[int]((& $nodeExe --version).TrimStart('v').Split('.')[0]) -if($major -lt 20){throw 'Serve Node.js 20 o successivo nel PATH.'} +if($EnableRadioCAT -and $DisableRadioCAT){throw 'Scegliere una sola opzione CAT.'} +if($AutoStart -and !$CheckOnly -and ($env:BPQ_CONSOLE_CONFIG -or $env:BPQ_ROOT -or $env:BPQ_CONSOLE_PORT)){throw 'Per -AutoStart usare console.config.json nella cartella del progetto, senza override BPQ_* temporanei.'} +$configPath=if($env:BPQ_CONSOLE_CONFIG){$env:BPQ_CONSOLE_CONFIG}else{Join-Path $PSScriptRoot 'console.config.json'} +$saved=$null +if(Test-Path -LiteralPath $configPath){try{$saved=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json}catch{throw 'Configurazione locale non leggibile: correggere il JSON prima di reinstallare.'}} +if(!$NodeExe){$NodeExe=if($saved.nodeExe -and (Test-Path -LiteralPath $saved.nodeExe)){$saved.nodeExe}else{(Get-Command node.exe -ErrorAction SilentlyContinue).Source}} +if(!$NodeExe -or !(Test-Path -LiteralPath $NodeExe)){throw 'Installare Node.js 20 o successivo, oppure specificare -NodeExe con il percorso di node.exe.'} +$version=& $NodeExe --version +if($LASTEXITCODE -ne 0 -or $version -notmatch '^v(\d+)\.' -or [int]$Matches[1] -lt 20){throw 'Serve Node.js 20 o successivo.'} if(!$BpqRoot){ - $candidates=@((Join-Path $env:APPDATA 'BPQ32')) - $running=Get-CimInstance Win32_Process | Where-Object {$_.Name -match '^(BPQTerminal|BPQMail|BPQChat|bpq32)\.exe$'} - foreach($proc in $running){if($proc.ExecutablePath){$candidates+=Split-Path $proc.ExecutablePath}} - $BpqRoot=$candidates | Where-Object {Test-Path -LiteralPath (Join-Path $_ 'BPQ32.cfg')} | Select-Object -First 1 + if($env:BPQ_ROOT){$BpqRoot=$env:BPQ_ROOT} + elseif($saved.bpqRoot){$BpqRoot=$saved.bpqRoot} + else{ + $candidates=@((Join-Path $env:APPDATA 'BPQ32')) + $running=Get-CimInstance Win32_Process | Where-Object {$_.Name -match '^(BPQTerminal|BPQMail|BPQChat|bpq32)\.exe$'} + foreach($proc in $running){if($proc.ExecutablePath){$candidates+=Split-Path $proc.ExecutablePath}} + $BpqRoot=$candidates | Where-Object {Test-Path -LiteralPath (Join-Path $_ 'BPQ32.cfg')} | Select-Object -First 1 + } if(!$BpqRoot){throw 'BPQ32.cfg non trovato. Usare -BpqRoot con la cartella dati BPQ.'} } -$arguments=@((Join-Path $PSScriptRoot 'install.mjs'),'--bpq-root',$BpqRoot,'--port',"$Port") -foreach($option in @(@('http-port',$HttpPort),@('radio-port',$RadioPort),@('sysop-user',$SysopUser),@('forward-peer',$ForwardPeer))){if($option[1]){$arguments+=@('--'+$option[0],"$($option[1])")}} -$vara=Get-Process -Name VARA -ErrorAction SilentlyContinue | Select-Object -First 1 -if($vara.Path){$varaLog=Join-Path (Split-Path $vara.Path) 'VARAHF.log';if(Test-Path -LiteralPath $varaLog){$arguments+=@('--vara-log',$varaLog)}} -if($CheckOnly){$arguments+='--check-only'} -& $nodeExe @arguments +if(!$CheckOnly -and $Restart){ + $pending=Join-Path $PSScriptRoot 'winlink-radio.session.json' + if((Test-Path -LiteralPath $pending) -and (Get-Content -LiteralPath $pending -Raw | ConvertFrom-Json).restoring){throw 'Attendere il ripristino della sessione Winlink radio prima di reinstallare e riavviare.'} +} +$targetPort=if($PSBoundParameters.ContainsKey('Port')){$Port}elseif($env:BPQ_CONSOLE_PORT){[int]$env:BPQ_CONSOLE_PORT}elseif($saved.port){[int]$saved.port}else{8090} +if($targetPort -ge 1024 -and $targetPort -le 65535){ + $listener=Get-NetTCPConnection -LocalPort $targetPort -State Listen -ErrorAction SilentlyContinue + if($listener){$owner=Get-CimInstance Win32_Process -Filter "ProcessId=$($listener[0].OwningProcess)";if($owner.Name -ne 'node.exe' -or !$owner.CommandLine -or $owner.CommandLine.IndexOf((Join-Path $PSScriptRoot 'server.mjs'),[StringComparison]::OrdinalIgnoreCase) -lt 0){throw "Porta $targetPort occupata da un altro processo. Specificare -Port con una porta libera."}} +} +$nodeArgs=@((Join-Path $PSScriptRoot 'install.mjs'),'--bpq-root',$BpqRoot,'--config-path',$configPath) +$mapping=@{Port='port';HttpPort='http-port';RadioPort='radio-port';SysopUser='sysop-user';ForwardPeer='forward-peer';CmsPeer='cms-peer';VaraLogPath='vara-log'} +foreach($name in $mapping.Keys){if($PSBoundParameters.ContainsKey($name)){$nodeArgs+=@('--'+$mapping[$name],[string](Get-Variable -Name $name -ValueOnly))}} +if(!$VaraLogPath){$vara=Get-Process -Name VARA -ErrorAction SilentlyContinue | Select-Object -First 1;if($vara.Path){$varaLog=Join-Path (Split-Path $vara.Path) 'VARAHF.log';if(Test-Path -LiteralPath $varaLog){$nodeArgs+=@('--vara-log',$varaLog)}}} +if($EnableRadioCAT){$nodeArgs+='--enable-radio-cat'} +if($DisableRadioCAT){$nodeArgs+='--disable-radio-cat'} +if($CheckOnly){$nodeArgs+='--check-only'} +& $NodeExe @nodeArgs if($LASTEXITCODE -ne 0){throw 'Installazione interrotta: verifica BPQ fallita.'} if($CheckOnly){return} if($AutoStart){ - $action=New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ('-NoProfile -WindowStyle Hidden -File "'+(Join-Path $PSScriptRoot 'Start-Console.ps1')+'"') -WorkingDirectory $PSScriptRoot - $trigger=New-ScheduledTaskTrigger -AtLogOn -User ([Security.Principal.WindowsIdentity]::GetCurrent().Name) - Register-ScheduledTask -TaskName 'BPQ-WebConsole' -Action $action -Trigger $trigger -Description 'BPQ web console locale' -Force | Out-Null + $identity=[Security.Principal.WindowsIdentity]::GetCurrent().Name + $action=New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe') -Argument ('-NoProfile -ExecutionPolicy RemoteSigned -WindowStyle Hidden -File "'+(Join-Path $PSScriptRoot 'Start-Console.ps1')+'"') -WorkingDirectory $PSScriptRoot + $trigger=New-ScheduledTaskTrigger -AtLogOn -User $identity + $principal=New-ScheduledTaskPrincipal -UserId $identity -LogonType Interactive -RunLevel Limited + Register-ScheduledTask -TaskName 'BPQ-WebConsole' -Action $action -Trigger $trigger -Principal $principal -Description 'BPQ web console locale' -Force | Out-Null } +& (Join-Path $PSScriptRoot 'Start-Console.ps1') -Restart:$Restart if($EnableLAN){& (Join-Path $PSScriptRoot 'Enable-LAN.ps1')} -& (Join-Path $PSScriptRoot 'Start-Console.ps1') -Write-Host "Pannello: http://127.0.0.1:$Port" +$current=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json +$displayPort=if($env:BPQ_CONSOLE_PORT){$env:BPQ_CONSOLE_PORT}else{$current.port} +Write-Host "Pannello: http://127.0.0.1:$displayPort" diff --git a/README.md b/README.md index 3206092..c4b3711 100644 --- a/README.md +++ b/README.md @@ -1,136 +1,173 @@ # BPQ Console -Pannello web per una stazione BPQ32, con dashboard, BBS, Winlink, chat, monitor e telemetria modem. Backend Node.js senza dipendenze esterne; interfaccia HTML/CSS/JavaScript. Il nominativo, gli alias, il locator e le porte sono letti dalla configurazione della stazione. +A local web dashboard for BPQ32: node status, BBS, Winlink, forwarding, chat, traffic monitor, contact journal, station map and an amber Telnet terminal. Callsigns, aliases, locator and ports come from your station configuration. Node.js backend with no external npm dependencies; HTML/CSS/JavaScript frontend. -## Requisiti +## Requirements -- Windows con PowerShell e Node.js 20 o successivo disponibile nel PATH. -- BPQ32 installato e già in esecuzione, con HTTPPORT configurata nel driver Telnet. -- Almeno un USER Telnet con ruolo sysop. Le credenziali rimangono in BPQ32.cfg. -- BPQMail per la BBS e Winlink; BPQChat e TCPPORT per la chat; FBBPORT per il monitor. Questi servizi sono opzionali. +- Windows and Windows PowerShell 5.1 or later. +- Node.js 20 or later. A portable `node.exe` can be selected with `-NodeExe`. +- BPQ32 installed and running, with `HTTPPORT` configured in its Telnet driver. +- A Telnet `USER` with the `sysop` role. The panel accepts the selected sysop account; its password stays in `BPQ32.cfg`. +- Optional: BPQMail for BBS/Winlink, BPQChat and `TCPPORT` for chat, `FBBPORT` for the monitor. The terminal only needs `TCPPORT`. -## Installazione +Service detection recognises the `BBS` and `CHAT` application command names, case-insensitively. Those applications must actually be running to use their pages. The installer does not install BPQ, configure a modem, change radio frequencies or create forwarding partners. -Scaricare o clonare il repository, aprire PowerShell nella cartella del progetto e avviare BPQ. Verificare prima il rilevamento senza modificare nulla: +## Install + +Clone or download and extract the project into a writable folder. Start BPQ first. Open PowerShell in the project folder and run a read-only check: ```powershell .\Install.ps1 -CheckOnly ``` -L'installer cerca BPQ32.cfg in %APPDATA%\BPQ32 e nelle cartelle dei processi BPQ attivi. Verifica che l'interfaccia HTTP BPQ risponda e mostra porte, applicazioni e profili forwarding rilevati. Se BPQ non risponde, interrompe l'installazione senza creare la configurazione. +If your normal PowerShell policy blocks local scripts, after reviewing the files you can run them with a policy limited to that process: -Installazione e avvio del pannello: +```powershell +powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\Install.ps1 -CheckOnly +``` + +This does not change your user or machine execution policy. Downloaded files may still require unblocking after review; organisation Group Policy remains authoritative. + +Install and start: ```powershell .\Install.ps1 ``` -Aprire http://127.0.0.1:8090 e accedere con l'utente Telnet sysop selezionato. Il primo sysop è scelto automaticamente; usare -SysopUser quando ce ne sono diversi. Non servono npm install o una compilazione. +Open **http://127.0.0.1:8090** and sign in with the selected BPQ Telnet sysop account. No `npm install` or build step is required. -Per percorsi o porte diversi e per selezionare il modem e il profilo BBS: +Detection uses an explicit `-BpqRoot`, `BPQ_ROOT`, the previously saved data folder, `%APPDATA%\BPQ32`, or the folders of running BPQ processes. The HTTP check must identify BPQ before any configuration is written. `-CheckOnly` never saves configuration, starts the panel, registers a task or changes the firewall, even if other switches are present. + +Explicit settings: ```powershell -.\Install.ps1 -BpqRoot 'D:\BPQ' -Port 8090 -HttpPort 8080 -RadioPort 3 -SysopUser 'sysop' -ForwardPeer 'N1TEST' +.\Install.ps1 -BpqRoot 'D:\Radio\BPQ data' -Port 8095 -HttpPort 8080 -RadioPort 3 -SysopUser 'admin' -ForwardPeer 'N1TEST' ``` --RadioPort seleziona una porta modem rilevata; in assenza dell'opzione viene scelta la prima. -ForwardPeer deve corrispondere a un profilo esistente nella BBS. Senza un profilo selezionato il pulsante di forwarding manuale è disabilitato. L'installer non crea profili radio o modifica la configurazione BPQ. +| Option | Purpose | +| --- | --- | +| `-BpqRoot` | Folder containing `BPQ32.cfg`, not necessarily the program installation folder. | +| `-Port` | Web panel port, 1024–65535; default 8090 on first install. | +| `-HttpPort` | BPQ HTTP port; defaults to the Telnet driver setting. Must differ from the panel port. | +| `-RadioPort` | Existing BPQ radio port number. The first is selected initially; multiple modems produce a warning. | +| `-SysopUser` | Existing sysop user; defaults to the first on initial installation. | +| `-ForwardPeer` | Existing BBS forwarding partner for the dashboard shortcut. No partner is created automatically. | +| `-CmsPeer` | Existing CMS forwarding profile; defaults to `RMS`. | +| `-NodeExe` | Full path to a Node.js 20+ `node.exe`. Saved for future startup. | +| `-VaraLogPath` | Optional local `VARAHF.log` used by the journal. A running local VARA log is detected when available. | +| `-EnableRadioCAT` / `-DisableRadioCAT` | Explicitly enable/disable Winlink radio tuning through BPQ. No tuning test or transmission is performed. | +| `-Restart` | Restart this project's web panel after installation/update. Does not restart BPQ or VARA. | -Opzioni aggiuntive: +Without a selected forwarding partner the dashboard shortcut is disabled. The Forwarding page can still show and start other configured partners. + +## Updates and local settings + +Reinstalling for the same BPQ data folder preserves custom settings, including the panel port, CMS profile, VARA options and Winlink CAT opt-in. Changed configuration is backed up as `console.config.json..backup`, then saved atomically. An unchanged configuration is not rewritten. Invalid JSON, missing selected ports/users or invalid explicit profiles stop installation with an error. + +If you select a different station folder, station-specific selections are detected again. If the selected modem changes, CAT opt-in is cleared unless explicitly enabled. Use a separate project folder for each station so journals, caches and recovery state remain separate. + +After updating the project: ```powershell -# Avvio automatico al login Windows +.\Install.ps1 -CheckOnly +.\Install.ps1 -Restart +``` + +For a normal start or restart without rerunning detection: + +```powershell +.\Start-Console.ps1 +.\Start-Console.ps1 -Restart +``` + +Startup checks the port, Node version and the new server's `/health` response. It reports failures instead of claiming success when Node exits. An existing panel on another port is not duplicated. Changed settings require a restart. A Winlink radio session awaiting profile restoration blocks `-Restart`; let that session finish first. Restarting the panel closes its browser/Telnet sessions. + +Environment overrides: `BPQ_ROOT` selects the BPQ data folder; `BPQ_CONSOLE_PORT` selects the panel port; `BPQ_CONSOLE_CONFIG` selects a different local JSON configuration file. Install and startup scripts respect these overrides. Use the standard `console.config.json` without temporary environment overrides when registering automatic startup. + +Station greetings, ASCII banners, radio schedules, routing and Winlink availability reports remain local BPQ settings. The installer does not overwrite them. Personal BPQ configuration and credentials are not part of this repository. + +## Automatic startup and LAN + +```powershell +# Start at this Windows user's logon .\Install.ps1 -AutoStart -# Accesso dalla sottorete locale, su profilo rete Privato -# Eseguire PowerShell come amministratore per la regola firewall +# Optional access from the local subnet; requires an administrator shell .\Install.ps1 -EnableLAN ``` --AutoStart registra la task BPQ-WebConsole. -EnableLAN apre soltanto la porta del pannello alla sottorete locale. Per usare entrambe le opzioni: .\Install.ps1 -AutoStart -EnableLAN. Se PowerShell blocca gli script scaricati, sbloccare i file dopo averne verificato il contenuto, secondo le policy del proprio PC. +`-AutoStart` registers **BPQ-WebConsole** for the current user, with interactive logon and limited privileges. It uses the saved Node path and process-scoped `RemoteSigned` execution policy. Windows policy may restrict task registration. Remove the task to disable automatic startup. BPQ must have its own startup arrangement. -La configurazione generata console.config.json contiene percorsi, porte e selezioni, senza password, ed è esclusa da Git. Il percorso Node rilevato viene salvato per l'avvio automatico. È possibile modificare il file e riavviare il solo pannello. BPQ_ROOT e BPQ_CONSOLE_PORT permettono di sovrascrivere cartella dati e porta HTTP del pannello. +`-EnableLAN` creates a firewall rule for the selected Node executable and panel port, restricted to the **Private** profile and **LocalSubnet**. Existing rules are replaced only after the new rule is created successfully. From another computer use the BPQ PC's private IPv4 address and panel port. The panel accepts loopback and private IPv4 hosts, not arbitrary DNS hostnames or public addresses. -## Modem e servizi opzionali +This is an administrative panel for a trusted PC/LAN, using HTTP. Do not expose it directly to the Internet. Authentication uses HttpOnly/SameSite cookies and writes require Origin/CSRF checks. Configuration, logs, mail files, station locations and runtime caches are excluded from Git. -Il progetto non richiede VARA. Con PACTOR o altri driver BPQ mostra la porta selezionata e i dati disponibili nell'interfaccia BPQ. Le informazioni non esposte dal driver restano non disponibili: non vengono simulate. Non vengono inviati comandi CAT specifici per una radio. +## Modems and telemetry -Il grafico TRAFFICO BPQ mostra TX/RX in bit/s calcolati dalla variazione dei contatori byte BPQ nel tempo; indica traffico utile effettivo, non il bitrate negoziato dal modem. È disponibile per le porte radio, anche senza VARA. Il grafico CPU VARA è abilitato soltanto quando la porta selezionata usa il driver VARA. La ricezione syslog del bitrate VARA resta disponibile nel backend come diagnostica, ma non alimenta il KPI principale. Per il bitrate, configurare il syslog VARA verso 127.0.0.1 UDP 18514, con CommandsLog attivo; varaSyslogPort nel file locale permette di cambiarne la porta. Non viene aperta una seconda connessione TCP al modem. Per un VARA remoto la CPU locale non è disponibile. Il bitrate deve essere emesso dalla versione VARA utilizzata. +VARA is optional. PACTOR, ARDOP, KISS and other BPQ ports show the information their driver exposes; missing data remains unavailable. VARA-specific controls are disabled for other drivers. -BBS, chat, monitor e Winlink vengono abilitati in base alle applicazioni e alle porte BPQ rilevate. Le API dei servizi assenti sono disabilitate. Winlink richiede CMS=1 e una BBS configurata; Aggiorna mail avvia il profilo RMS via Internet. cmsPeer consente di specificare un nome diverso nel file locale. Non viene installato o configurato automaticamente un gateway Winlink. +**TRAFFICO BPQ** derives TX/RX bit/s from BPQ byte-counter changes, rather than claiming to show the negotiated modem bitrate. The VARA CPU chart only applies to a local VARA process. Remote VARA CPU usage cannot be measured locally. Optional VARA bitrate diagnostics listen on loopback UDP 18514; change `varaSyslogPort` in local configuration if needed. The VARA version must emit bitrate records with CommandsLog enabled. The panel does not open a second VARA TCP control connection. -## Funzioni e dati +## BBS, mail and attachments -Dashboard scura, schermo intero, stato modem, chiamante/chiamato quando esposti, CPU di sistema, rotte NET/ROM e attività forwarding. BBS e Winlink hanno elenco sopra e lettura sotto, ricerca, composizione, risposta, cancellazione e allegati B2. Anteprime immagini, PDF e testo; HTML/SVG mostrati come testo. I messaggi 7plus multipart vengono ricostruiti automaticamente quando tutte le parti sono disponibili e i controlli CRC sono validi. +BBS and Winlink provide folders, search, composition, replies, deletion and B2 attachments, with the message list above the reader. Delete marks a message `K` in BPQ and does not recall mail already delivered elsewhere. The panel uses BPQ's interfaces for writes, never edits `DIRMES.SYS` or `.mes` files directly. -Chat nativa con sessione condivisa dell'account sysop selezionato, utenti, stanze, collegamenti e messaggi privati; fino a 300 eventi in memoria. Monitor BPQTermTCP con filtri e download TXT; fino a 1000 frame in memoria. Disconnessione dopo due minuti senza polling. +Image, PDF and text attachments have previews and downloads. HTML/SVG are treated as text. Multipart 7plus files are reconstructed from the original message bytes when all parts and CRC checks are valid. Matching uses sender, filename, size, part count, block size and 7plus timestamp, not just the subject. Missing/damaged parts prevent downloading a false result. COR/ERR repair is not implemented. Limits: 32 MB per reconstructed file, 255 parts, 2 MB per scanned message and a 64 MB memory cache. Reference format: [7PLUS 2.25 source](https://ponce.cc/slackware/sources/repo/7pl225sr.zip). -Date e ore nella timezone del browser. Notifiche per nuovi bollettini e posta mentre il sito è aperto; il suono richiede un gesto nel browser. Lettura e scrittura tramite BPQ, senza modifiche dirette a DIRMES.SYS o ai file .mes. Elimina marca il messaggio K localmente e non richiama email già consegnate al CMS. +Concurrent readers share in-flight BPQ requests. Dashboard counters and Winlink avoid loading timestamp metadata for every bulletin. The first full BBS listing can take longer on a large archive while exact BPQ timestamps are loaded; subsequent reads reuse the timestamp cache. -## Sicurezza e verifica +Dates use the browser timezone. Arrival notifications distinguish downloaded bulletins and incoming mail from messages you composed; the first load does not announce old messages as new. Sound requires a browser gesture. -Pannello amministrativo per PC e LAN fidata, in HTTP. Non esporre direttamente su Internet. Sessioni HttpOnly/SameSite, controlli Origin/CSRF e host limitati a loopback e indirizzi LAN privati. I log, la configurazione locale e i dati BBS sono esclusi dal repository. PDF.js e font/CMap mantengono le licenze in public/vendor/pdfjs. +## Winlink Internet and radio + +Winlink requires `CMS=1`, the BBS application and a configured CMS forwarding profile. **Sync Internet** starts that profile; it does not create a gateway or forwarding configuration. + +**Sync Radio** opens the [official public Winlink gateway directory](https://cms.winlink.org:444/GatewayChannels.aspx), without an API key. Search callsign/locator/location, filter by band and opening hours, and sort by distance, callsign or frequency. The modem family selects the directory mode. Cache: 15 minutes; manual refresh is throttled to once per minute. Calls require a directory no older than 30 minutes, an open UTC schedule and a report within six hours. A report does not guarantee reachability or a clear channel. Distance is geographical, not a propagation prediction; VOACAP is not required. + +Displayed frequencies are **USB dial**, calculated as the published centre frequency minus 1500 Hz. Verify this offset against your modem setup. Scheduling is UTC; report timestamps use the browser timezone. + +Radio connection requires a supported HF modem, available telemetry and working BPQ `RADIO` CAT control. Enable this deliberately: ```powershell -node --test test.mjs +.\Install.ps1 -EnableRadioCAT -Restart ``` -Per riavviare, arrestare soltanto il processo Node di questo pannello ed eseguire Start-Console.ps1. Per rimuovere l'avvio automatico, eliminare la task BPQ-WebConsole. BPQ e il modem continuano a funzionare indipendentemente dal pannello. +Selecting a row does not transmit. **Connetti e sincronizza** explicitly starts the selected gateway. Busy modem/BBS sessions block startup and the panel does not override a busy channel. The CMS profile must normally use `RMS` or `C port CMS` as its Internet script. +Before changing that profile, the panel backs up `BPQMail.cfg` under `BPQMailChat/Backup-winlink-radio-*`. It temporarily disables the profile timer, sets an ATTACH/RADIO/CONNECT script and enables compressed B2 personal mail. Once BPQ streams are idle, it restores the original profile. `winlink-radio.session.json` retains recovery state across panel restarts. Concurrent manual profile edits suspend automatic restoration and expose a restore button. Keep the panel running during the exchange. The initial status confirms a request to BPQ; results and counts come from logs. -## Diario e mappa delle stazioni +## Forwarding, chat and terminal -Le sezioni Diario e Mappa ricostruiscono fino a 30 giorni dai log BPQ BBS, Chat e CMSAccess, con un massimo di 5000 sessioni. Il diario distingue servizio, direzione, trasporto, esito, frequenza quando registrata, durata del collegamento, SNR, tentativi, contatori TX/RX ed eventi. Filtri per periodo, nominativo, servizio, direzione ed esito; esportazione CSV delle righe filtrate. Si aggiorna ogni 30 secondi quando la sezione è aperta. +**Forwarding** shows configured partners in a compact table. Click a row (or Enter/Space) to expand routing rules, scripts, schedules, queue counts and recent exchanges. Only one row opens at a time; focus survives refresh. Sync buttons are authenticated, serialised and protected against duplicate requests, active sessions and modem use. The next attempt is a log-based estimate; BPQ owns the real timer. Sensitive script commands are masked. Rules remain editable in BPQ. -I log VARA possono arricchire le sessioni con byte effettivi e picchi TX/RX. Install.ps1 rileva VARAHF.log dal processo VARA locale quando disponibile; in alternativa impostare varaLogPath nel file locale console.config.json. Non è necessario usare VARA: i servizi presenti nei log BPQ rimangono disponibili. I contatori della connessione CMS e quelli radio sono distinti. Messaggi e conteggi sono quelli esplicitamente registrati: dati mancanti rimangono non disponibili. File ruotati, mancanti o incompleti possono impedire di ricostruire l'intera sessione; un esito non registrato non viene considerato riuscito. Per file oltre 16 MB viene letta la parte finale e mostrato un avviso. +**Chat** uses the selected sysop's shared session, with rooms, connected users, peer links and private messages. **Monitor** uses BPQTermTCP, with port/direction filters and TXT export. They retain up to 300 chat events and 1000 monitor frames, and disconnect after two minutes without polling. -La mappa è locale, senza servizi di tile, API key o invio dei log a terzi. Usa i poligoni pubblici [Natural Earth](https://www.naturalearthdata.com/about/terms-of-use/), inclusi nel progetto. Posizione locale da LOCATOR BPQ; per le stazioni remote selezionare un nominativo e salvare il locator Maidenhead comunicato dalla stazione (4, 6 o 8 caratteri). I locator vengono salvati nel file locale station-locations.json, escluso da Git. I punti rappresentano il centro del locator. Stazioni con lo stesso centro del locator condividono il punto, senza spostamenti artificiali. Il riquadro dettagli permette di selezionarle; non viene disegnata una traccia di distanza zero. +**Terminale** opens a real Telnet session to the local BPQ `TCPPORT`, automatically authenticating without returning login credentials to the browser. It has amber phosphor styling, scanlines, selectable text and a cursor that respects reduced-motion settings. Enter sends one command; Up/Down browse history. Pulisci clears the screen, Salva testo downloads it, and Disconnetti closes the socket. Scrolling upwards pauses following; the bottom button resumes it. -Punti e tracce sono cliccabili, con nominativo, ultimo collegamento nel periodo, servizio, orario e accesso al dettaglio di ogni sessione. Zoom con rotellina del mouse centrato sul cursore, pulsanti zoom e Inquadra rete; trascinamento della mappa e filtro per servizio/periodo. Mostra collegamenti permette di attivare o nascondere le tracce. Le tracce uniscono stazioni e non descrivono il percorso fisico radio o gli hop NET/ROM. Le stazioni senza locator rimangono nell'elenco, senza coordinate inventate. +Each web login has its own terminal/socket and in-memory transcript. Logout/expiry closes it; so do 90 seconds without terminal polling or 15 minutes without commands. Limits: 1000 characters per command, 200,000 output characters and 100 history entries. It is a BPQ line terminal, not a full-screen VT100 or binary YAPP client. Remote HTML and ANSI controls are not executed. -Il diario espone eventi strutturati, non i log grezzi: password, challenge CMS, contenuto delle email e conversazioni chat non sono restituiti dall'API. +## Journal and map -Il tipo di collegamento viene ricostruito anche dai comandi CONNECT con porta numerata e dagli accessi accettati nei log Telnet (orari locali Windows, convertiti in UTC). La correlazione usa nominativo e orario entro 20 secondi ed è indicata nei dettagli. Gli accessi locali sono distinti come Locale / Telnet. Se i log storici non archiviano il mezzo di ingresso, il diario mostra Nodo BPQ oppure Gateway Winlink e spiega il limite nei dettagli; non presume un collegamento radio o Internet. Sulla mappa tali mezzi sono distinti dal colore delle tracce radio e di rete. +The journal reconstructs up to 30 days and 5000 sessions from BPQ BBS, Chat and CMSAccess logs, with optional VARA log enrichment. It shows service, direction, transport, outcome, recorded frequency, duration, SNR, attempts, counters and events; filters and CSV export apply to the visible records. Missing/rotated/incomplete logs may prevent reconstructing older contacts. Data is not invented; unknown transport is explained in details. Credential challenges, mail bodies and chat conversations are not exposed in journal events. -## Immagini multipart 7plus +The local map uses [Natural Earth](https://www.naturalearthdata.com/about/terms-of-use/) geometry without external tiles or API keys. Your position comes from BPQ's locator. Save remote Maidenhead locators supplied by stations in `station-locations.json` (4, 6 or 8 characters). Points represent locator centres; stations sharing a locator share the point, without artificial displacement. Click a point or trace for callsign, time and contact details. Wheel zoom, drag, zoom buttons and fit-to-network are supported. Traces join stations, not propagation paths or NET/ROM hops. Stations without known locators remain unplotted. -Il lettore individua i blocchi 7plus nei file .mes originali, preservando i byte a 8 bit, e raggruppa le parti per mittente, nome, dimensione, numero di parti, dimensione del blocco e timestamp 7plus. Non usa soltanto il titolo del bollettino: file diversi con lo stesso nome non vengono uniti automaticamente. La decodifica JavaScript verifica CRC primario, CRC secondario, sequenza delle righe, intestazioni e chiusure. Il riferimento di interoperabilità è il formato 7PLUS di Axel Bauda DG1BBQ ([sorgenti originali 2.25](https://ponce.cc/slackware/sources/repo/7pl225sr.zip)); non viene eseguito o distribuito un decoder esterno. +## Verification and troubleshooting -Aprendo una qualsiasi parte completa, il file ricostruito appare fra gli allegati, con anteprima e download; le immagini vengono mostrate direttamente nel lettore e il testo codificato resta espandibile. Sono elencati i messaggi che compongono il gruppo. Parti mancanti o danneggiate bloccano il download del risultato e vengono indicate. Copie valide della stessa parte possono completare righe mancanti; righe discordanti non vengono accettate. Non è implementata la riparazione tramite file COR/ERR. +```powershell +npm test +# Or, without npm: +node --test +``` -Sono considerate soltanto le parti attualmente visibili nella BBS. Nessun messaggio viene modificato, scritto o cancellato; i risultati sono conservati in memoria (cache fino a 64 MB). Limite file ricostruito 32 MB, fino a 255 parti, scansione di messaggi fino a 2 MB ciascuno. Il download usa gli stessi controlli di sessione e autorizzazione degli altri allegati. +Tests cover protocol parsing, mail/attachments, journal, gateway validation, profile restoration, generic station detection and installer behaviour. Windows tests exercise the PowerShell wrappers in temporary folders, including paths with spaces/apostrophes, duplicate starts, restart and startup failure. They do not create scheduled tasks or firewall rules. -### Forwarding +- **BPQ unreachable:** start BPQ and check its Telnet `HTTPPORT`; rerun `-CheckOnly`. +- **Missing service:** check the matching application/port and that BPQMail/BPQChat is running. +- **Wrong modem/sysop after BPQ changes:** rerun installation with the appropriate selection. +- **Port already in use:** choose a different `-Port`; do not reuse BPQ's HTTP port. +- **Changed settings:** use `Start-Console.ps1 -Restart` when no radio profile restoration is pending. +- **Startup fails:** inspect local `server-error.log`. A failed start is not reported as success. +- **Script/task policy blocks execution:** review the files and your Windows policy; organisation restrictions cannot be overridden by the installer. -La pagina Forwarding presenta i partner in una tabella compatta con sync nella riga. Un click sulla riga (oppure Invio/Spazio da tastiera) apre il dettaglio con regole, script e storico: un solo partner alla volta. Il dettaglio e il focus vengono conservati durante gli aggiornamenti automatici. - -La pagina Forwarding legge i profili BBS nativi, le code aggiornate tramite BPQ, le regole TO/AT e gerarchiche, le fasce UTC (oppure locali se abilitate in BPQ), gli intervalli e gli ultimi scambi dai sette file di log BBS più recenti. Radio e Internet sono distinti usando percorso e porte configurate. Il prossimo tentativo è una stima basata sui log e non il timer interno BPQ. I comandi di connessione riservati sono oscurati. - -Ogni partner con script dispone di Sincronizza ora, anche se il timer automatico è disabilitato. Le richieste sono autenticate, protette da CSRF, limitate ai partner configurati e serializzate per evitare conflitti nella sessione amministrativa BPQ; sono bloccate durante una sessione rilevata, con modem impegnato o per 30 secondi dopo una richiesta. La conferma iniziale indica una richiesta a BPQ, mentre l’esito viene aggiornato dai log. Le regole restano modificabili in BPQ. I riquadri Arrivati nella BBS e Attività forwarding sono stati rimossi dalla home. - -Verifica: `node --test test.mjs forwarding.test.mjs`. - -## Winlink via radio - -In Winlink, **Sync Internet** conserva lo scambio CMS esistente. **Sync Radio** apre il selettore dei gateway ufficiali PUBLIC: ricerca per nominativo, locator o località, filtro banda e orario, ordinamento per distanza, nominativo o frequenza. L’elenco viene scaricato dal [CSV pubblico Winlink](https://cms.winlink.org:444/GatewayChannels.aspx), senza chiave API, con cache di 15 minuti e aggiornamento manuale. La distanza deriva dai locator e non è una previsione di propagazione; VOACAP non è richiesto. - -I canali sono filtrati per il modem HF rilevato (VARA, Pactor o ARDOP). Le frequenze mostrate sono dial USB, calcolate dalla frequenza centrale pubblicata meno 1500 Hz. Prima dell’uso verificare questo offset nella configurazione del modem. Gli orari dichiarati sono UTC; il timestamp del report usa il fuso del browser. Un report recente non garantisce che il gateway sia raggiungibile o il canale libero. - -Per abilitare il pulsante di connessione, il controllo CAT deve già funzionare tramite il comando BPQ RADIO. Aggiungere nel file locale console.config.json `"winlinkRadio": {"catControl": true}` e riavviare il pannello. In assenza di CAT abilitato l’elenco resta consultabile. La selezione non trasmette: **Connetti e sincronizza** avvia esplicitamente la chiamata. Sono accettati solo canali dell’elenco aggiornato, in orario e con report entro sei ore; le richieste sono autenticate e protette da CSRF. - -Il profilo cmsPeer (RMS per impostazione predefinita) deve avere script Internet RMS oppure C porta CMS. Prima della chiamata viene salvato un backup di BPQMail.cfg in BPQMailChat/Backup-winlink-radio-*. Il pannello sostituisce temporaneamente lo script con ATTACH / RADIO / CONNECT, disabilita il timer del profilo e usa B2 compresso. Al termine, con gli stream BBS inattivi, ripristina i campi originali e riabilita il sync Internet. Modem e BBS impegnati bloccano l’avvio; non viene forzato il canale occupato. - -Lo stato di recupero è nel file locale winlink-radio.session.json, escluso da Git. Dopo un riavvio il pannello riprende il ripristino; una modifica manuale concorrente del profilo sospende il ripristino automatico e richiede verifica tramite il pulsante dedicato. Lasciare il pannello in esecuzione durante lo scambio. Lo stato iniziale conferma la richiesta a BPQ; l’esito e i conteggi provengono dai log, senza presumere la consegna della posta. - -Verifica: `node --test test.mjs forwarding.test.mjs winlink-radio.test.mjs`. - -## Terminale Telnet - -La sezione **Terminale** apre una sessione Telnet reale verso BPQ sullo stesso PC, usando TCPPORT rilevata in BPQ32.cfg. **Collega** esegue l’accesso automatico con l’utente sysop configurato; le credenziali di accesso non vengono incluse nel testo restituito al browser. Non richiede VARA o un modem specifico. Se manca TCPPORT, il pulsante di navigazione viene nascosto. - -Il terminale usa fosfori giallo ambra, scanline leggere, bagliore e cursore lampeggiante (fermo quando il sistema richiede movimento ridotto). Invio invia il comando; ↑ e ↓ richiamano la cronologia della pagina. Il testo è selezionabile e copiabile. Pulisci svuota solo la schermata; Salva testo scarica quanto visualizzato; Disconnetti chiude il socket. Lo scorrimento automatico si sospende risalendo nel testo e riprende con Torna al fondo. - -Ogni sessione web ha un proprio collegamento e buffer in memoria, senza condivisione del terminale fra accessi. Le API richiedono autenticazione e CSRF per i comandi. Il server si collega soltanto al Telnet BPQ locale: non accetta host o porte forniti dal browser. Logout e scadenza dell’accesso chiudono la sessione; il socket viene chiuso anche dopo 90 secondi senza consultazione del terminale oppure 15 minuti senza comandi. Nessun registro viene salvato automaticamente su disco. - -È una console a righe per il nodo BPQ e le sue applicazioni: non emula applicazioni a schermo intero VT100. Il testo remoto viene visualizzato come testo, senza eseguire HTML o sequenze di controllo ANSI. Limiti: 1000 caratteri per comando, 200.000 caratteri di output in memoria e 100 comandi nella cronologia del browser. - -Verifica: `node --test test.mjs forwarding.test.mjs winlink-radio.test.mjs terminal.test.mjs`. +Third-party PDF.js, font and CMap licences are retained under `public/vendor/pdfjs`; map attribution is in `public/WORLD-MAP-LICENSE.txt`. diff --git a/Start-Console.ps1 b/Start-Console.ps1 index 025d8fd..d287aeb 100644 --- a/Start-Console.ps1 +++ b/Start-Console.ps1 @@ -1,9 +1,39 @@ +param([switch]$Restart) $ErrorActionPreference='Stop' -$configPath=Join-Path $PSScriptRoot 'console.config.json' -$port=8090 -if(Test-Path -LiteralPath $configPath){$settings=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json;if($settings.port){$port=$settings.port}} -if($env:BPQ_CONSOLE_PORT){$port=[int]$env:BPQ_CONSOLE_PORT} +$configPath=if($env:BPQ_CONSOLE_CONFIG){$env:BPQ_CONSOLE_CONFIG}else{Join-Path $PSScriptRoot 'console.config.json'} +if(!(Test-Path -LiteralPath $configPath)){throw 'Configurazione assente: eseguire Install.ps1 prima di avviare il pannello.'} +$settings=Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json +$port=if($env:BPQ_CONSOLE_PORT){[int]$env:BPQ_CONSOLE_PORT}elseif($settings.port){[int]$settings.port}else{8090} +if($port -lt 1024 -or $port -gt 65535){throw 'Porta pannello non valida.'} +$nodeExe=if($settings.nodeExe -and (Test-Path -LiteralPath $settings.nodeExe)){$settings.nodeExe}else{(Get-Command node.exe -ErrorAction SilentlyContinue).Source} +if(!$nodeExe){throw 'Node.js non trovato. Eseguire Install.ps1 -NodeExe con il percorso corretto.'} +$version=& $nodeExe --version +if($LASTEXITCODE -ne 0 -or $version -notmatch '^v(\d+)\.' -or [int]$Matches[1] -lt 20){throw 'Serve Node.js 20 o successivo.'} +$serverPath=Join-Path $PSScriptRoot 'server.mjs' +$owned=@(Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object {$_.CommandLine -and $_.CommandLine.IndexOf($serverPath,[StringComparison]::OrdinalIgnoreCase) -ge 0}) +$target=Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue +if($target -and @($owned.ProcessId) -notcontains $target[0].OwningProcess){throw "Porta $port occupata da un altro processo: scegliere un'altra porta con Install.ps1 -Port."} +if($Restart -and $owned.Count){ + $pending=Join-Path $PSScriptRoot 'winlink-radio.session.json' + if((Test-Path -LiteralPath $pending) -and (Get-Content -LiteralPath $pending -Raw | ConvertFrom-Json).restoring){throw 'Attendere il ripristino della sessione Winlink radio prima di riavviare il pannello.'} + foreach($proc in $owned){Stop-Process -Id $proc.ProcessId -ErrorAction Stop;Wait-Process -Id $proc.ProcessId -Timeout 10 -ErrorAction SilentlyContinue} +} $listener=Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue -if($listener){$proc=Get-CimInstance Win32_Process -Filter "ProcessId=$($listener[0].OwningProcess)";if($proc.Name -eq 'node.exe' -and $proc.CommandLine.Contains((Join-Path $PSScriptRoot 'server.mjs'))){exit 0};throw "Porta $port occupata da un altro processo"} -$nodeExe=if($settings.nodeExe -and (Test-Path -LiteralPath $settings.nodeExe)){$settings.nodeExe}else{(Get-Command node.exe -ErrorAction Stop).Source} -Start-Process -FilePath $nodeExe -ArgumentList ('"'+(Join-Path $PSScriptRoot 'server.mjs')+'"') -WorkingDirectory $PSScriptRoot -WindowStyle Hidden -RedirectStandardOutput (Join-Path $PSScriptRoot 'server.log') -RedirectStandardError (Join-Path $PSScriptRoot 'server-error.log') +if($listener){ + $proc=Get-CimInstance Win32_Process -Filter "ProcessId=$($listener[0].OwningProcess)" + if($proc.Name -eq 'node.exe' -and $proc.CommandLine -and $proc.CommandLine.IndexOf($serverPath,[StringComparison]::OrdinalIgnoreCase) -ge 0){ + if((Get-Item -LiteralPath $configPath).LastWriteTime -gt $proc.CreationDate){throw 'Configurazione modificata: usare Start-Console.ps1 -Restart per applicarla.'} + Write-Host "Pannello gia in esecuzione su http://127.0.0.1:$port";return + } + throw "Porta $port occupata da un altro processo: scegliere un'altra porta con Install.ps1 -Port." +} +if(!$Restart -and $owned.Count){throw "Il pannello di questa cartella e gia in esecuzione su un'altra porta: usare -Restart."} +$child=Start-Process -FilePath $nodeExe -ArgumentList ('"'+$serverPath+'"') -WorkingDirectory $PSScriptRoot -WindowStyle Hidden -RedirectStandardOutput (Join-Path $PSScriptRoot 'server.log') -RedirectStandardError (Join-Path $PSScriptRoot 'server-error.log') -PassThru +$ready=$false +for($attempt=0;$attempt -lt 40;$attempt++){ + $child.Refresh();if($child.HasExited){break} + try{$health=Invoke-RestMethod -Uri "http://127.0.0.1:$port/health" -TimeoutSec 1;if($health.service -eq 'bpq-console' -and $health.pid -eq $child.Id){$ready=$true;break}}catch{} + Start-Sleep -Milliseconds 250 +} +if(!$ready){if(!$child.HasExited){Stop-Process -Id $child.Id -ErrorAction SilentlyContinue};throw 'Avvio pannello non confermato: consultare server-error.log e correggere la configurazione.'} +Write-Host "Pannello avviato su http://127.0.0.1:$port" diff --git a/config.mjs b/config.mjs index a96f76c..f96122e 100644 --- a/config.mjs +++ b/config.mjs @@ -4,26 +4,34 @@ import os from 'node:os'; import {fileURLToPath} from 'node:url'; export function parseConfig(text){ - const lines=text.split(/\r?\n/).map(l=>l.split(';')[0].trim()).filter(Boolean); + let inText=false,inComment=false;const lines=[]; + for(let line of text.split(/\r?\n/)){line=line.trim();if(inText){if(line.startsWith('***'))inText=false;continue;}if(inComment){if(line.startsWith('*/'))inComment=false;continue;}if(line.startsWith('/*')){inComment=!line.includes('*/');continue;}if(/^(?:IDMSG|INFOMSG|BTEXT|CTEXT):/i.test(line)){inText=true;continue;}line=line.split(';')[0].trim();if(line)lines.push(line);} const value=(name)=>lines.find(l=>new RegExp('^'+name+'\\s*=','i').test(l))?.split('=').slice(1).join('=').trim()||''; - const users=lines.flatMap(l=>{const m=l.match(/^USER=([^,]+),([^,]+),([^,]+),(.*)$/i);return m&&/\bsysop\b/i.test(m[4])?[{user:m[1].trim(),password:m[2],call:m[3].trim().toUpperCase()}]:[]}); - const apps=lines.flatMap(l=>{const m=l.match(/^APPLICATION\s+\d+,([^,]+),([^,]*),([^,]*),([^,]*)/i);return m?[{command:m[1],call:m[3],alias:m[4]}]:[]}); + const users=lines.flatMap(l=>{const m=l.match(/^USER\s*=\s*([^,]+),([^,]+),([^,]+),(.*)$/i);return m&&/\bsysop\b/i.test(m[4])?[{user:m[1].trim(),password:m[2],call:m[3].trim().toUpperCase()}]:[]}); + const apps=lines.flatMap(l=>{const m=l.match(/^APPLICATION\s+\d+\s*,(.*)$/i);if(!m)return [];const fields=m[1].split(',').map(s=>s.trim());return fields[0]?[{command:fields[0].split('/')[0].toUpperCase(),call:(fields[2]||'').toUpperCase(),alias:fields[3]||''}]:[]}); let ports=[],current=null; - for(const l of lines){if(/^PORT$/i.test(l)){current={id:ports.length+1,name:'',driver:''};continue;}if(/^ENDPORT$/i.test(l)){if(current){if(!current.driver)current.driver=current.protocol||current.type||'';ports.push(current)};current=null;continue;}if(current){const m=l.match(/^(PORTNUM|ID|DRIVER|TYPE|PROTOCOL)=(.*)$/i);if(m)current[({PORTNUM:'id',ID:'name',DRIVER:'driver',TYPE:'type',PROTOCOL:'protocol'})[m[1].toUpperCase()]]=m[1].toUpperCase()==='PORTNUM'?Number(m[2]):m[2];}} + for(const l of lines){if(/^PORT$/i.test(l)){current={id:ports.length+1,name:'',driver:'',settings:{}};continue;}if(/^ENDPORT$/i.test(l)){if(current){if(!current.driver)current.driver=current.protocol||current.type||'';ports.push(current)};current=null;continue;}if(current){const m=l.match(/^(PORTNUM|ID|DRIVER|TYPE|PROTOCOL)\s*=\s*(.*)$/i);if(m)current[({PORTNUM:'id',ID:'name',DRIVER:'driver',TYPE:'type',PROTOCOL:'protocol'})[m[1].toUpperCase()]]=m[1].toUpperCase()==='PORTNUM'?Number(m[2].trim()):m[2].trim();const s=l.match(/^(HTTPPORT|TCPPORT|FBBPORT|CMS)\s*=\s*(.*)$/i);if(s)current.settings[s[1].toUpperCase()]=s[2].trim();}} + const telnet=ports.find(p=>/^TELNET(?:\.DLL)?$/i.test(p.driver)),settings=telnet?.settings||{}; + for(const p of ports)delete p.settings; const radioPorts=ports.filter(p=>!/TELNET|AXIP|LOOPBACK/i.test(p.driver)&&p.driver); const nodeCall=value('NODECALL'),sysop=users[0]; - return {nodeCall,call:sysop?.call||nodeCall.replace(/-\d+$/,''),alias:value('NODEALIAS'),locator:value('LOCATOR'),apps,ports,radioPorts,users,httpPort:Number(value('HTTPPORT'))||null,telnetPort:Number(value('TCPPORT'))||null,monitorPort:Number(value('FBBPORT'))||null,winlink:value('CMS')==='1'}; + return {nodeCall,call:sysop?.call||nodeCall.replace(/-\d+$/,''),alias:value('NODEALIAS'),locator:value('LOCATOR'),apps,ports,radioPorts,users,httpPort:Number(settings.HTTPPORT)||null,telnetPort:Number(settings.TCPPORT)||null,monitorPort:Number(settings.FBBPORT)||null,winlink:settings.CMS==='1'}; } export async function loadConfig(){ const dir=path.dirname(fileURLToPath(import.meta.url));let saved={}; try{saved=JSON.parse(await readFile(process.env.BPQ_CONSOLE_CONFIG||path.join(dir,'console.config.json'),'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;} + if(!saved||typeof saved!=='object'||Array.isArray(saved))throw new Error('La configurazione locale deve essere un oggetto JSON'); const root=process.env.BPQ_ROOT||saved.bpqRoot||path.join(process.env.APPDATA||path.join(os.homedir(),'AppData','Roaming'),'BPQ32'); const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')); if(!detected.users.length)throw new Error('Nessun utente Telnet sysop in BPQ32.cfg'); - const radio=detected.radioPorts.find(p=>p.id===saved.radioPort)||detected.radioPorts[0]||null; - const httpPort=saved.httpPort||detected.httpPort;if(!httpPort)throw new Error('HTTPPORT BPQ non rilevata: eseguire Install.ps1'); + if(saved.radioPort!=null&&!detected.radioPorts.some(p=>p.id===Number(saved.radioPort)))throw new Error('Porta radio configurata non rilevata: rieseguire Install.ps1'); + if(saved.sysopUser&&!detected.users.some(u=>u.user===saved.sysopUser))throw new Error('Utente sysop configurato non rilevato: rieseguire Install.ps1'); + const radio=detected.radioPorts.find(p=>p.id===Number(saved.radioPort))||detected.radioPorts[0]||null; + const httpPort=Number(saved.httpPort||detected.httpPort);if(!validPort(httpPort))throw new Error('HTTPPORT BPQ non valida o assente: eseguire Install.ps1'); + const port=Number(process.env.BPQ_CONSOLE_PORT||saved.port||8090);if(!validPort(port,1024)||port===httpPort)throw new Error('Porta pannello non valida o in conflitto con HTTPPORT BPQ'); const features={terminal:!!detected.telnetPort,bbs:detected.apps.some(a=>a.command==='BBS'),chat:detected.apps.some(a=>a.command==='CHAT')&&!!detected.telnetPort,monitor:!!detected.monitorPort,winlink:detected.winlink&&detected.apps.some(a=>a.command==='BBS'),vara:!!radio&&/^VARA/i.test(radio.driver),radio:!!radio}; - return {...detected,...saved,root,httpPort,radio,features,port:Number(process.env.BPQ_CONSOLE_PORT||saved.port||8090),sysop:detected.users.find(u=>u.user===saved.sysopUser)||detected.users[0]}; + return {...detected,...saved,root,httpPort,radio,features,port,sysop:detected.users.find(u=>u.user===saved.sysopUser)||detected.users[0]}; } +export const validPort=(n,min=1)=>Number.isInteger(n)&&n>=min&&n<=65535; export function publicConfig(c){return {call:c.sysop.call,nodeCall:c.nodeCall,alias:c.alias,locator:c.locator,apps:c.apps,radio:c.radio,ports:c.ports,features:c.features,forwardPeer:c.forwardPeer||'',cmsPeer:c.cmsPeer||'RMS'};} export function ownCall(sender,call){return !!call&&String(sender||'').replace(/^RMS[/:]/i,'').toUpperCase().split('@')[0].replace(/-\d+$/,'')===String(call).toUpperCase().split('@')[0].replace(/-\d+$/,'');} diff --git a/install.mjs b/install.mjs index f845a29..b6d40dd 100644 --- a/install.mjs +++ b/install.mjs @@ -1,20 +1,57 @@ -process.on('uncaughtException',e=>{console.error('Installazione interrotta: '+e.message);process.exit(1)}); -import {readFile,writeFile} from 'node:fs/promises'; -import http from 'node:http';import path from 'node:path';import {fileURLToPath} from 'node:url';import {parseConfig} from './config.mjs'; -const dir=path.dirname(fileURLToPath(import.meta.url)),args=process.argv.slice(2),arg=n=>{const i=args.indexOf('--'+n);return i>=0?args[i+1]:undefined}; -const root=arg('bpq-root')||path.join(process.env.APPDATA||'','BPQ32'); -const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')); -if(!detected.users.length)throw new Error('Configurare un USER Telnet sysop in BPQ32.cfg'); -const port=Number(arg('port')||8090),httpPort=Number(arg('http-port')||detected.httpPort); -if(!Number.isInteger(port)||port<1024||port>65535||!httpPort)throw new Error('Porte non valide o HTTPPORT BPQ assente'); -await new Promise((resolve,reject)=>{const req=http.get({host:'127.0.0.1',port:httpPort,path:'/Node/Ports.html',headers:{Connection:'close'}},res=>{let text='';res.on('data',b=>text+=b);res.on('end',()=>res.statusCode===200&&/BPQ|Ports/i.test(text)?resolve():reject(new Error('Il server HTTP non conferma BPQ')))});req.setTimeout(8000,()=>req.destroy(new Error('BPQ non risponde: avviare BPQ e verificare HTTPPORT')));req.on('error',()=>reject(new Error('BPQ non raggiungibile: avviare BPQ e verificare HTTPPORT')))}); -let previous={};try{previous=JSON.parse(await readFile(path.join(dir,'console.config.json'),'utf8'))}catch{} -const radioPort=Number(arg('radio-port')||previous.radioPort)||detected.radioPorts[0]?.id||null; -if(radioPort&&!detected.radioPorts.some(p=>p.id===radioPort))throw new Error('Porta radio selezionata non rilevata'); -const sysopUser=arg('sysop-user')||previous.sysopUser||detected.users[0].user; -if(!detected.users.some(u=>u.user===sysopUser))throw new Error('Utente sysop non rilevato'); -let peers=[];try{const mail=await readFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'utf8');const forward=mail.split(/BBSForwarding\s*:/i)[1]?.split(/BBSUsers\s*:/i)[0]||'';peers=[...forward.matchAll(/^\s{2}([A-Z0-9-]+)\s*:/gm)].map(m=>m[1]);}catch{} -const config={nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort,sysopUser,forwardPeer:arg('forward-peer')||previous.forwardPeer||'',cmsPeer:'RMS',varaSyslogPort:18514,varaLogPath:arg('vara-log')||previous.varaLogPath||null}; -if(config.forwardPeer&&!peers.includes(config.forwardPeer))throw new Error('Profilo forwarding selezionato non rilevato'); -console.log(JSON.stringify({bpq:'in esecuzione, HTTP verificato',nodeCall:detected.nodeCall,ports:detected.ports,services:detected.apps.map(a=>a.command),forwardProfiles:peers,selectedRadio:radioPort,sysopUser},null,2)); -if(!args.includes('--check-only')){await writeFile(path.join(dir,'console.config.json'),JSON.stringify(config,null,2)+'\n');console.log('Configurazione salvata senza password.');} +import {readFile,writeFile,copyFile,rename} from 'node:fs/promises'; +import http from 'node:http'; +import path from 'node:path'; +import os from 'node:os'; +import {fileURLToPath} from 'node:url'; +import {parseConfig,validPort} from './config.mjs'; +import {parseForwarding} from './forwarding.mjs'; +import {modemFamily} from './winlink-gateways.mjs'; + +const dir=path.dirname(fileURLToPath(import.meta.url)); +export async function readLocalConfig(file){try{const value=JSON.parse(await readFile(file,'utf8'));if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Object required');return value;}catch(e){if(e.code==='ENOENT')return {};throw new Error('Configurazione locale non leggibile: correggere il JSON prima di reinstallare');}} +export function probeBpq(port){return new Promise((resolve,reject)=>{ + const request=http.get({hostname:'127.0.0.1',port,path:'/Node/Ports.html',headers:{Connection:'close'},agent:false},response=>{let text='';response.on('data',b=>{text+=b;if(text.length>2e6)response.destroy(new Error('Risposta HTTP troppo grande'));});response.on('error',reject);response.on('end',()=>response.statusCode===200&&/\/Node\//i.test(text)&&/\bPorts\b/i.test(text)?resolve():reject(new Error('Il server HTTP non conferma BPQ')));}); + request.setTimeout(8000,()=>request.destroy(new Error('Timeout BPQ')));request.on('error',()=>reject(new Error('BPQ non raggiungibile: avviare BPQ e verificare HTTPPORT'))); +});} +const samePath=(a,b)=>process.platform==='win32'?path.resolve(a).toLowerCase()===path.resolve(b).toLowerCase():path.resolve(a)===path.resolve(b); +export async function prepareInstall(options={},dependencies={}){ + const configPath=path.resolve(options.configPath||process.env.BPQ_CONSOLE_CONFIG||path.join(dir,'console.config.json')); + const previous=await readLocalConfig(configPath); + const root=path.resolve(options.bpqRoot||process.env.BPQ_ROOT||previous.bpqRoot||path.join(process.env.APPDATA||path.join(os.homedir(),'AppData','Roaming'),'BPQ32')); + const detected=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')); + if(!detected.nodeCall)throw new Error('NODECALL non rilevato in BPQ32.cfg'); + if(!detected.users.length)throw new Error('Configurare un USER Telnet sysop in BPQ32.cfg'); + const sameStation=Boolean(previous.bpqRoot&&samePath(previous.bpqRoot,root)),saved=sameStation?previous:{}; + const port=Number(options.port??process.env.BPQ_CONSOLE_PORT??previous.port??8090),httpPort=Number(options.httpPort??saved.httpPort??detected.httpPort); + if(!validPort(port,1024)||!validPort(httpPort)||port===httpPort)throw new Error('Porte non valide o in conflitto: pannello 1024-65535, HTTP BPQ 1-65535, diverse fra loro'); + const chosen=options.radioPort??saved.radioPort??detected.radioPorts[0]?.id??null; + const radio=chosen==null?null:detected.radioPorts.find(p=>p.id===Number(chosen)); + if(chosen!=null&&!radio)throw new Error('Porta radio selezionata non rilevata: specificare -RadioPort'); + const sysopUser=options.sysopUser??saved.sysopUser??detected.users[0].user; + if(!detected.users.some(u=>u.user===sysopUser))throw new Error('Utente sysop non rilevato: specificare -SysopUser'); + let profiles=[];try{profiles=parseForwarding(await readFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'utf8'),detected.ports);}catch(e){if(e.code!=='ENOENT')throw e;} + const peers=profiles.map(p=>p.call),forwardPeer=String(options.forwardPeer??saved.forwardPeer??'').toUpperCase(),cmsPeer=String(options.cmsPeer??saved.cmsPeer??'RMS').toUpperCase(); + if(forwardPeer&&!peers.includes(forwardPeer))throw new Error('Profilo forwarding selezionato non rilevato'); + if(!/^[A-Z0-9-]{1,12}$/.test(cmsPeer))throw new Error('Nome profilo CMS non valido'); + if(options.cmsPeer&&!peers.includes(cmsPeer))throw new Error('Profilo CMS selezionato non rilevato'); + const sameRadio=sameStation&&Number(saved.radioPort)===radio?.id&&(!saved.radioDriver||saved.radioDriver===radio.driver); + const catControl=options.catControl??(sameRadio&&saved.winlinkRadio?.catControl===true); + if(catControl&&(!radio||!modemFamily(radio.driver)))throw new Error('Winlink radio richiede un modem HF VARA, Pactor o ARDOP'); + const vara=Boolean(radio&&/^VARA/i.test(radio.driver)); + const config={...saved,nodeExe:process.execPath,bpqRoot:root,httpPort,port,radioPort:radio?.id??null,radioDriver:radio?.driver??null,sysopUser,forwardPeer,cmsPeer,varaSyslogPort:saved.varaSyslogPort??18514,varaLogPath:vara?(options.varaLogPath??(sameRadio?saved.varaLogPath:null)??null):null,winlinkRadio:{...(sameRadio?saved.winlinkRadio:{}),catControl:Boolean(catControl)}}; + if(!validPort(Number(config.varaSyslogPort)))throw new Error('Porta syslog VARA non valida'); + const warnings=[];if(detected.radioPorts.length>1&&options.radioPort==null&&saved.radioPort==null)warnings.push('Più modem rilevati: selezionata la prima porta; usare -RadioPort per cambiarla.'); + if(detected.winlink&&!peers.includes(cmsPeer))warnings.push('Profilo CMS non presente: configurarlo in BPQ prima di usare il sync Winlink.'); + if(options.catControl===true)warnings.push('CAT abilitato su richiesta: verificare RADIO in BPQ prima di una chiamata; nessuna trasmissione eseguita dall’installer.'); + await (dependencies.probe||probeBpq)(httpPort); + return {config,configPath,previous,report:{bpq:'in esecuzione, HTTP verificato',nodeCall:detected.nodeCall,ports:detected.ports,services:detected.apps.map(a=>a.command),terminal:Boolean(detected.telnetPort),forwardProfiles:peers,selectedRadio:radio?.id??null,sysopUser,warnings}}; +} +export async function saveInstall(plan){ + if(JSON.stringify(plan.previous)===JSON.stringify(plan.config))return {changed:false}; + let backup=null;try{backup=plan.configPath+'.'+new Date().toISOString().replace(/[:.]/g,'-')+'.backup';await copyFile(plan.configPath,backup);}catch(e){if(e.code!=='ENOENT')throw e;backup=null;} + await writeFile(plan.configPath+'.tmp',JSON.stringify(plan.config,null,2)+'\n');await rename(plan.configPath+'.tmp',plan.configPath);return {changed:true,backup}; +} +export function parseArgs(args){const names={'bpq-root':'bpqRoot',port:'port','http-port':'httpPort','radio-port':'radioPort','sysop-user':'sysopUser','forward-peer':'forwardPeer','cms-peer':'cmsPeer','vara-log':'varaLogPath','config-path':'configPath'},options={}; + for(let i=0;i{}; +const cfg=(driver='VARA',call='N9DEMO')=>`NODECALL = ${call}-7 +NODEALIAS=DEMO +LOCATOR=IO91AA +PORT +PORTNUM=3 +ID=HF modem +DRIVER = ${driver} +ENDPORT +PORT +PORTNUM=7 +DRIVER = Telnet.dll +HTTPPORT = 8088 +TCPPORT=9000 +CMS=1 +USER=admin,fixture-secret,${call},sysop +USER=operator,another-fixture,${call}-1,sysop +ENDPORT +APPLICATION 1, bbs, ,${call}-11,MAIL +`; +async function fixture(t,driver='VARA'){ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),"bpq install O'Brien "));t.after(()=>fs.rm(dir,{recursive:true,force:true}));const root=path.join(dir,'station');await fs.mkdir(path.join(root,'BPQMailChat'),{recursive:true});await fs.writeFile(path.join(root,'BPQ32.cfg'),cfg(driver));await fs.writeFile(path.join(root,'BPQMailChat','BPQMail.cfg'),'BBSForwarding : {\n CMS2 : { ConnectScript="RMS"; Enabled=1; }\n N1PEER : { ConnectScript="ATTACH 3|C N1PEER"; Enabled=1; }\n}\nBBSUsers : {}'); + return {dir,root,options:{bpqRoot:root,configPath:path.join(dir,'console.config.json')}}; +} +test('configuration ignores banners and comments, accepts whitespace, DLL drivers and Telnet-specific ports',()=>{ + const parsed=parseConfig('/* single line comment */\nINFOMSG:\nNODECALL=N0WRONG\nUSER=wrong,not-a-secret,N0WRONG,sysop\n***\n'+cfg('ARDOP')+'\nPORT\nDRIVER=OTHER\nHTTPPORT=9999\nTCPPORT=9998\nENDPORT'); + assert.equal(parsed.nodeCall,'N9DEMO-7');assert.equal(parsed.users.length,2);assert.equal(parsed.httpPort,8088);assert.equal(parsed.telnetPort,9000);assert.equal(parsed.apps[0].command,'BBS');assert.equal(parsed.radioPorts[0].driver,'ARDOP');assert.equal(parsed.radioPorts.length,2); + const short=parseConfig('APPLICATION 1,bbs\nAPPLICATION 2,CHAT/TALK,,N9DEMO-12');assert.equal(short.apps[0].command,'BBS');assert.equal(short.apps[0].call,'');assert.equal(short.apps[1].command,'CHAT');assert.equal(short.apps[1].call,'N9DEMO-12'); +}); +test('fresh install detects profiles and modem without copying credentials or enabling CAT',async t=>{ + const f=await fixture(t),plan=await prepareInstall(f.options,{probe});assert.equal(plan.config.radioPort,3);assert.equal(plan.config.winlinkRadio.catControl,false);assert.equal(plan.report.terminal,true);assert.deepEqual(plan.report.forwardProfiles,['CMS2','N1PEER']);assert.ok(!JSON.stringify(plan).includes('fixture-secret'));assert.equal((await saveInstall(plan)).changed,true);assert.ok(!await fs.readFile(plan.configPath,'utf8').then(s=>s.includes('fixture-secret'))); +}); +test('reinstallation preserves custom settings, backs up once and is idempotent',async t=>{ + const f=await fixture(t),saved={bpqRoot:f.root,port:18099,httpPort:8088,radioPort:3,radioDriver:'VARA',sysopUser:'operator',cmsPeer:'CMS2',forwardPeer:'N1PEER',varaSyslogPort:19001,varaLogPath:'D:/Radio/VARAHF.log',winlinkRadio:{catControl:true},customOption:{theme:'dark'}};await fs.writeFile(f.options.configPath,JSON.stringify(saved)); + const p=await prepareInstall(f.options,{probe});assert.equal(p.config.port,18099);assert.equal(p.config.sysopUser,'operator');assert.equal(p.config.cmsPeer,'CMS2');assert.equal(p.config.winlinkRadio.catControl,true);assert.equal(p.config.varaSyslogPort,19001);assert.deepEqual(p.config.customOption,saved.customOption);const result=await saveInstall(p);assert.deepEqual(JSON.parse(await fs.readFile(result.backup,'utf8')),saved);const again=await prepareInstall(f.options,{probe});assert.equal((await saveInstall(again)).changed,false); +}); +test('a different station and changed modem do not inherit CAT, peers or VARA paths',async t=>{ + const f=await fixture(t);await fs.writeFile(f.options.configPath,JSON.stringify({bpqRoot:f.root,radioPort:3,radioDriver:'VARA',sysopUser:'operator',cmsPeer:'CMS2',forwardPeer:'N1PEER',varaLogPath:'D:/old/VARAHF.log',winlinkRadio:{catControl:true}})); + await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg('SCSPACTOR'));const changed=await prepareInstall(f.options,{probe});assert.equal(changed.config.winlinkRadio.catControl,false);assert.equal(changed.config.varaLogPath,null); + const root=path.join(f.dir,'another station');await fs.mkdir(root);await fs.writeFile(path.join(root,'BPQ32.cfg'),cfg('ARDOP','N8OTHER'));const other=await prepareInstall({...f.options,bpqRoot:root},{probe});assert.equal(other.config.sysopUser,'admin');assert.equal(other.config.forwardPeer,'');assert.equal(other.config.cmsPeer,'RMS');assert.equal(other.config.winlinkRadio.catControl,false);assert.equal(other.config.varaLogPath,null); +}); +test('Telnet-only and non-VARA stations install with absent services and no fake modem',async t=>{ + const f=await fixture(t);await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg().replace(/PORT\nPORTNUM=3[\s\S]*?ENDPORT\n/,'').replace(/^APPLICATION.*$/m,''));await fs.rm(path.join(f.root,'BPQMailChat'),{recursive:true,force:true});const p=await prepareInstall(f.options,{probe});assert.equal(p.config.radioPort,null);assert.equal(p.config.varaLogPath,null);assert.equal(p.config.winlinkRadio.catControl,false);assert.deepEqual(p.report.forwardProfiles,[]); + for(const driver of ['SCSPACTOR','ARDOP','KISS']){await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg(driver));const p=await prepareInstall(f.options,{probe});assert.equal(p.config.radioDriver,driver);assert.equal(p.config.varaLogPath,null);} + await assert.rejects(prepareInstall({...f.options,catControl:true},{probe}),/modem HF/); +}); +test('invalid ports, users, profiles and local JSON fail without overwriting settings',async t=>{ + const f=await fixture(t);for(const options of [{port:8088},{httpPort:70000},{httpPort:0},{port:1},{radioPort:99},{sysopUser:'missing'},{forwardPeer:'MISSING'},{cmsPeer:'MISSING'}])await assert.rejects(prepareInstall({...f.options,...options},{probe})); + for(const value of ['{bad json','null','[]']){await fs.writeFile(f.options.configPath,value);await assert.rejects(prepareInstall(f.options,{probe}),/JSON/);assert.equal(await fs.readFile(f.options.configPath,'utf8'),value);} +}); +test('offline BPQ and failed checks never create local configuration',async t=>{ + const f=await fixture(t);await assert.rejects(prepareInstall(f.options,{probe:async()=>{throw new Error('BPQ offline');}}),/offline/);await assert.rejects(fs.stat(f.options.configPath),{code:'ENOENT'}); +}); +test('HTTP check recognises BPQ and rejects an unrelated web service',async t=>{ + let real=false;const server=http.createServer((req,res)=>res.end(real?'BPQ Ports':'Unrelated ports page'));await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));await assert.rejects(probeBpq(server.address().port),/non conferma/);real=true;await probeBpq(server.address().port); +}); +test('CLI parses explicit options and rejects typos or missing values',()=>{ + assert.deepEqual(parseArgs(['--port','8099','--enable-radio-cat','--check-only']),{port:'8099',catControl:true,checkOnly:true});assert.throws(()=>parseArgs(['--port']));assert.throws(()=>parseArgs(['--unknown','x']));assert.throws(()=>parseArgs(['--enable-radio-cat','--disable-radio-cat'])); +}); +test('PowerShell installer CheckOnly supports paths with spaces and skips startup, task and firewall', {skip:process.platform!=='win32'},async t=>{ + const f=await fixture(t);const fake=http.createServer((req,res)=>res.end('BPQ Ports'));await new Promise(r=>fake.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>fake.close(r)));await fs.writeFile(path.join(f.root,'BPQ32.cfg'),cfg().replace('8088',String(fake.address().port))); + const env={...process.env,BPQ_CONSOLE_CONFIG:f.options.configPath};delete env.BPQ_ROOT;delete env.BPQ_CONSOLE_PORT; + const result=await run('powershell.exe',['-NoProfile','-NonInteractive','-ExecutionPolicy','RemoteSigned','-File',path.resolve('Install.ps1'),'-NodeExe',process.execPath,'-BpqRoot',f.root,'-CheckOnly','-AutoStart','-EnableLAN','-Restart'],{env,windowsHide:true,timeout:20000});assert.match(result.stdout,/N9DEMO-7/);assert.ok(!result.stdout.includes('fixture-secret'));await assert.rejects(fs.stat(f.options.configPath),{code:'ENOENT'}); +}); +const freePort=async()=>{const s=net.createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;}; +test('PowerShell startup confirms readiness, handles duplicate starts, restart and failed startup', {skip:process.platform!=='win32'},async t=>{ + const f=await fixture(t),script=path.join(f.dir,'Start-Console.ps1');await fs.copyFile('Start-Console.ps1',script);const configFile=path.join(f.dir,'console.config.json');let pid=null;t.after(()=>{if(pid)try{process.kill(pid);}catch{}}); + const source="import http from 'node:http';import fs from 'node:fs';const c=JSON.parse(fs.readFileSync('console.config.json','utf8'));http.createServer((q,r)=>{r.setHeader('Content-Type','application/json');r.end(JSON.stringify({service:'bpq-console',pid:process.pid}));}).listen(c.port,'127.0.0.1');";await fs.writeFile(path.join(f.dir,'server.mjs'),source);let port=await freePort();await fs.writeFile(configFile,JSON.stringify({port,nodeExe:process.execPath}));const env={...process.env};delete env.BPQ_CONSOLE_CONFIG;delete env.BPQ_CONSOLE_PORT;delete env.BPQ_ROOT; + const start=extra=>run('powershell.exe',['-NoProfile','-NonInteractive','-ExecutionPolicy','RemoteSigned','-File',script,...extra],{env,windowsHide:true,timeout:25000});assert.match((await start([])).stdout,/avviato/);pid=(await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid;assert.match((await start([])).stdout,/gia in esecuzione/); + const unrelated=net.createServer();await new Promise(r=>unrelated.listen(0,'127.0.0.1',r));try{await fs.writeFile(configFile,JSON.stringify({port:unrelated.address().port,nodeExe:process.execPath}));await assert.rejects(start(['-Restart']));assert.equal((await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid,pid);}finally{await new Promise(r=>unrelated.close(r));} + port=await freePort();await fs.writeFile(configFile,JSON.stringify({port,nodeExe:process.execPath}));await assert.rejects(start([]));assert.match((await start(['-Restart'])).stdout,/avviato/);pid=(await(await fetch('http://127.0.0.1:'+port+'/health')).json()).pid; + await fs.writeFile(path.join(f.dir,'server.mjs'),"throw new Error('fixture startup failure');");await assert.rejects(start(['-Restart']));pid=null;assert.match(await fs.readFile(path.join(f.dir,'server-error.log'),'utf8'),/fixture startup failure/); +}); diff --git a/package.json b/package.json index 5867d3c..ec3ab20 100644 --- a/package.json +++ b/package.json @@ -1 +1 @@ -{"name":"bpq-console","version":"1.1.0","private":true,"type":"module","scripts":{"start":"node server.mjs","test":"node --test test.mjs"}} +{"name":"bpq-console","version":"1.2.0","private":true,"type":"module","engines":{"node":">=20"},"scripts":{"start":"node server.mjs","test":"node --test"}} diff --git a/public/journal.js b/public/journal.js index 64e9f81..3822542 100644 --- a/public/journal.js +++ b/public/journal.js @@ -28,7 +28,7 @@ function renderMap(keepInfo=false){if(!data)return;const stations=mapStations(), svg.innerHTML=content;svg.setAttribute('viewBox',view.join(' '));$$('#station-map [data-map-call]').forEach(el=>{el.onclick=e=>{if(moved)return;e.stopPropagation();mapCall=el.dataset.mapCall;renderMap();};el.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();mapCall=el.dataset.mapCall;renderMap();}};}); $('#map-station-list').innerHTML=stations.map(s=>``).join('')||'

Nessun collegamento stabilito nel periodo selezionato.

';$$('[data-peer]').forEach(b=>b.onclick=()=>{mapCall=b.dataset.peer;renderMap();});if(!keepInfo)mapInfo(stations.find(s=>s.call===mapCall));} function mapInfo(s){if(!s){$('#map-info').innerHTML=`
◎

Scegli una stazione.

Clicca un punto, una traccia o un nominativo nell’elenco.

${!data.own.position?'

Il LOCATOR della stazione locale non è presente in BPQ: le tracce non possono essere disegnate.

':''}
`;return;} - const sessions=mapSessions().filter(r=>base(r.call)===s.call),latest=sessions[0];const samePosition=p=>s.position&&p&&Math.abs(p.lat-s.position.lat)<1e-8&&Math.abs(p.lon-s.position.lon)<1e-8;const colocated=mapStations().filter(other=>samePosition(other.position));const sharedLocal=samePosition(data.own.position);const shared=sharedLocal||colocated.length>1?'
Stazioni nello stesso punto'+(sharedLocal?'

'+esc(data.own.call)+' · stazione locale

':'')+colocated.map(other=>'').join('')+'Il locator individua un’area: le posizioni effettive possono essere diverse.
':'';$('#map-info').innerHTML=`
STAZIONE COLLEGATA

${esc(s.call)}

${s.position?esc(s.position.locator)+' · '+(s.distance==null?'Distanza non disponibile':s.distance===0?'Stesso locator del nodo':s.distance+' km dal nodo'):'Posizione non disponibile'}

${shared}
Ultimo collegamento nel periodo${esc(time(latest?.startedAt))}${esc(latest?.service||'')} · ${esc(transport(latest?.transport))} · ${esc(direction(latest?.direction))}
${esc(s.position?.source||'Inserisci il locator comunicato dalla stazione.')}

${sessions.length} collegamenti nel periodo

${sessions.slice(0,8).map(r=>``).join('')}
`;$$('[data-colocated]').forEach(b=>b.onclick=()=>{mapCall=b.dataset.colocated;renderMap();});$('#locator-form').onsubmit=async e=>{e.preventDefault();try{data=await api('/stations/location',{method:'POST',body:JSON.stringify({call:s.call,locator:$('#station-locator').value})});render();fit();toast('Locator salvato per '+s.call);}catch(err){toast(err.message)}};$$('[data-map-session]').forEach(b=>b.onclick=()=>{navigate('journal');detail(b.dataset.mapSession);});} + const sessions=mapSessions().filter(r=>base(r.call)===s.call),latest=sessions[0];const samePosition=p=>s.position&&p&&Math.abs(p.lat-s.position.lat)<1e-8&&Math.abs(p.lon-s.position.lon)<1e-8;const colocated=mapStations().filter(other=>samePosition(other.position));const sharedLocal=samePosition(data.own.position);const shared=sharedLocal||colocated.length>1?'
Stazioni nello stesso punto'+(sharedLocal?'

'+esc(data.own.call)+' · stazione locale

':'')+colocated.map(other=>'').join('')+'Il locator individua un’area: le posizioni effettive possono essere diverse.
':'';$('#map-info').innerHTML=`
STAZIONE COLLEGATA

${esc(s.call)}

${s.position?esc(s.position.locator)+' · '+(s.distance==null?'Distanza non disponibile':s.distance===0?'Stesso locator del nodo':s.distance+' km dal nodo'):'Posizione non disponibile'}

${shared}
Ultimo collegamento nel periodo${esc(time(latest?.startedAt))}${esc(latest?.service||'')} · ${esc(transport(latest?.transport))} · ${esc(direction(latest?.direction))}
${esc(s.position?.source||'Inserisci il locator comunicato dalla stazione.')}

${sessions.length} collegamenti nel periodo

${sessions.slice(0,8).map(r=>``).join('')}
`;$$('[data-colocated]').forEach(b=>b.onclick=()=>{mapCall=b.dataset.colocated;renderMap();});$('#locator-form').onsubmit=async e=>{e.preventDefault();try{data=await api('/stations/location',{method:'POST',body:JSON.stringify({call:s.call,locator:$('#station-locator').value})});render();fit();toast('Locator salvato per '+s.call);}catch(err){toast(err.message)}};$$('[data-map-session]').forEach(b=>b.onclick=()=>{navigate('journal');detail(b.dataset.mapSession);});} function fit(){const points=mapStations().filter(s=>s.position).map(s=>xy(s.position));if(data?.own.position)points.push(xy(data.own.position));if(!points.length){view=[0,0,1000,500];renderMap();return;}const xs=points.map(p=>p[0]),ys=points.map(p=>p[1]);const w=Math.min(1000,Math.max(100,(Math.max(...xs)-Math.min(...xs))*1.7,(Math.max(...ys)-Math.min(...ys))*3.4)),cx=(Math.min(...xs)+Math.max(...xs))/2,cy=(Math.min(...ys)+Math.max(...ys))/2;view=[Math.max(0,Math.min(1000-w,cx-w/2)),Math.max(0,Math.min(500-w/2,cy-w/4)),w,w/2];renderMap();} function zoom(factor,anchor){const w=Math.max(5,Math.min(1000,view[2]*factor));if(w===view[2])return;const point=anchor||{x:view[0]+view[2]/2,y:view[1]+view[3]/2},u=(point.x-view[0])/view[2],v=(point.y-view[1])/view[3];view=[Math.max(0,Math.min(1000-w,point.x-u*w)),Math.max(0,Math.min(500-w/2,point.y-v*w/2)),w,w/2];renderMap(true);} $('#map-plus').onclick=()=>zoom(.65);$('#map-minus').onclick=()=>zoom(1.5);$('#map-fit').onclick=fit;$('#map-tracks').onchange=renderMap;for(const id of ['map-period','map-service'])$('#'+id).onchange=()=>{mapCall=null;renderMap();fit();}; diff --git a/server.mjs b/server.mjs index 30cf615..436bb7f 100644 --- a/server.mjs +++ b/server.mjs @@ -1,4 +1,5 @@ import {Terminal} from './terminal.mjs'; +import {SingleFlight} from './single-flight.mjs'; import http from 'node:http'; import {Journal} from './journal.mjs'; import {GatewayDirectory,modemFamily} from './winlink-gateways.mjs'; @@ -38,6 +39,7 @@ function varaCpuSample(){execFile('powershell.exe',['-NoProfile','-NonInteractiv async function sampleTelemetry(){if(telemetryBusy)return;telemetryBusy=true;try{const html=config.radio?await bpq('/Node/Port?'+config.radio.id):'';const radio=parseRadio(html||'');const now=Date.now();const active=radio.connected&&!/^(Free|Idle)$/i.test(radio.state)&&Boolean(radio.state.trim());const connecting=/connect|call/i.test(radio.state)&&!/connected/i.test(radio.state);const connections=[...plain(html||'').matchAll(/\bCONNECTED ([A-Z0-9]+(?:-\d+)?) ([A-Z0-9]+(?:-\d+)?) (\d+)/g)];const calls=connections.at(-1);const delta=priorTraffic?(now-priorTraffic.at)/1000:0;const txBps=delta&&radio.sent>=priorTraffic.sent?8*(radio.sent-priorTraffic.sent)/delta:0;const rxBps=delta&&radio.received>=priorTraffic.received?8*(radio.received-priorTraffic.received)/delta:0;const sn=Number(String(radio.snr).replace(',','.'));const nativeRate=varaRate?.snapshot(active&&!connecting)||{listening:false,bps:null,tx:null,rx:null};const sample={at:now,available:!!config.radio,active,connecting,nativeRate,varaTxBps:nativeRate.tx,varaRxBps:nativeRate.rx,varaBps:nativeRate.bps,state:radio.state,frequency:radio.frequency,scan:radio.scanning,busy:radio.busy,txBps,rxBps,cpu:cpuSample(),varaCpu,snr:active&&Number.isFinite(sn)?sn:null,lastSnr:Number.isFinite(sn)?sn:null,caller:active&&!connecting&&calls?calls[1]:null,called:active&&!connecting&&calls?calls[2]:null,sent:radio.sent,received:radio.received};priorTraffic={at:now,sent:radio.sent,received:radio.received};telemetry.current=sample;telemetry.history.push(sample);if(telemetry.history.length>180)telemetry.history.shift();}catch(e){telemetry.current={at:Date.now(),available:false,error:'Modem non disponibile',cpu:cpuSample(),varaCpu};priorTraffic=null;}finally{telemetryBusy=false;}} setInterval(sampleTelemetry,2000).unref();if(config.features.vara)setInterval(varaCpuSample,5000).unref();setTimeout(()=>{sampleTelemetry();if(config.features.vara)varaCpuSample()},1000).unref(); let upstreamQueue=Promise.resolve(), mailKey=null, mailKeyAt=0; +const mailReads=new SingleFlight(),metadataReads=new SingleFlight(); function bpq(url,options={}){const work=upstreamQueue.then(()=>bpqRequest(url,options));upstreamQueue=work.catch(()=>{});return work;} async function bpqRequest(url, options={}) { // BPQ's legacy HTTP server is compatible with plain HTTP requests; modern @@ -47,15 +49,16 @@ async function bpqRequest(url, options={}) { if(payload){payload=Buffer.from(payload);headers['Content-Length']=payload.length;} return new Promise((resolve,reject)=>{const request=http.request(upstream+url,{method:options.method||'GET',headers,agent:false},response=>{let chunks=[];response.on('data',c=>chunks.push(c));response.on('end',()=>{if(response.statusCode!==200)return reject(new Error('BPQ non risponde ('+response.statusCode+')'));resolve(Buffer.concat(chunks).toString('utf8'))});response.on('error',reject)});request.setTimeout(10000,()=>request.destroy(new Error('Timeout BPQ')));request.on('error',reject);if(payload)request.write(payload);request.end()}); } -async function mailContext(){if(mailKey&&Date.now()-mailKeyAt<1800000)return {key:mailKey};const html=await bpq('/Webmail');const key=html.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw new Error('WebMail BPQ non disponibile');mailKey=key;mailKeyAt=Date.now();return {html,key};} -async function messages(includeTimes=true){let {key}=await mailContext();let html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List')){mailKey=null;({key}=await mailContext());html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List'))throw new Error('Lista messaggi BPQ non disponibile');}const list=parseMessages(html);for(const m of list.filter(m=>m.type==='P'&&(m.to==='RMS'||m.needsMetadata))){const f=await messageFields(m.id);m.from=f.From||m.from;m.to=f.To||m.to;m.subject=f.Title||m.subject;m.via=f.VIA||m.via;}if(includeTimes)for(const m of list)Object.assign(m,await messageTimes(m.id));return list;} +function mailContext(){return mailReads.run('context',async()=>{if(mailKey&&Date.now()-mailKeyAt<1800000)return {key:mailKey};const html=await bpq('/Webmail');const key=html.match(/WMB\?([^>\s]+)/)?.[1];if(!key)throw new Error('WebMail BPQ non disponibile');mailKey=key;mailKeyAt=Date.now();return {html,key};});} +function messages(includeTimes=true){return mailReads.run(includeTimes?'full':'quick',()=>readMessages(includeTimes));} +async function readMessages(includeTimes=true){let {key}=await mailContext();let html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List')){mailKey=null;({key}=await mailContext());html=await bpq('/WebMail/WMALL?'+key);if(!html.includes('Message List'))throw new Error('Lista messaggi BPQ non disponibile');}const list=parseMessages(html);for(const m of list.filter(m=>m.type==='P'&&(m.to==='RMS'||m.needsMetadata))){const f=await messageFields(m.id);m.from=f.From||m.from;m.to=f.To||m.to;m.subject=f.Title||m.subject;m.via=f.VIA||m.via;}if(includeTimes)for(const m of list)Object.assign(m,await messageTimes(m.id));return list;} function equal(a,b){const aa=Buffer.from(a),bb=Buffer.from(b);return aa.length===bb.length&&timingSafeEqual(aa,bb);} async function authenticate(user,password){const users=parseConfig(await readFile(path.join(root,'BPQ32.cfg'),'utf8')).users;const found=users.find(u=>equal(u.user.toLowerCase(),user.toLowerCase())&&equal(u.password,password)&&u.user===config.sysop.user);return found?{call:found.call,name:found.user,config:publicConfig(config)}:null;} async function body(req){let chunks=[],size=0;for await(const chunk of req){size+=chunk.length;if(size>70000)throw new Error('Messaggio troppo grande');chunks.push(chunk)}return JSON.parse(Buffer.concat(chunks).toString()||'{}');} function json(res,status,data){res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'});res.end(JSON.stringify(data));} function session(req){const token=req.headers.cookie?.match(/(?:^|;\s*)alnode=([a-f0-9]+)/)?.[1];const s=sessions.get(token);if(s&&s.expires>Date.now()){s.expires=Date.now()+8*3600000;return s;}if(token){s?.terminal?.close();sessions.delete(token);}return null;} async function dashboard(){ - const jobs=await Promise.allSettled([config.radio?bpq('/Node/Port?'+config.radio.id):Promise.resolve(null),bpq('/Node/Routes.html'),bpq('/Node/Nodes.html'),config.features.bbs?messages():Promise.resolve([])]); + const jobs=await Promise.allSettled([config.radio?bpq('/Node/Port?'+config.radio.id):Promise.resolve(null),bpq('/Node/Routes.html'),bpq('/Node/Nodes.html'),config.features.bbs?messages(false):Promise.resolve([])]); const val=i=>jobs[i].status==='fulfilled'?jobs[i].value:null; const list=val(3)||[];let activity=[],sync=null,cms=[]; try{const date=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);const log=await readFile(path.join(root,'Logs',`log_${date}_BBS.txt`),'utf8'); @@ -76,10 +79,11 @@ async function syncNow(peer=config.forwardPeer){if(!config.features.bbs)throw ne const timestampCache=new Map(); async function messageTimes(id){if(timestampCache.has(id))return timestampCache.get(id);const pending=(async()=>{const f=await messageFields(id);let reference=new Date();try{reference=(await stat(path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes'))).mtime;}catch{}const receivedAt=bpqTimestamp(f.RX,reference);return {receivedAt,createdAt:bpqTimestamp(f.Sent,receivedAt?new Date(receivedAt):reference)};})().catch(()=>{timestampCache.delete(id);return {receivedAt:null,createdAt:null};});timestampCache.set(id,pending);return pending;} const metadataCache=new Map();let metadataKey=null,metadataKeyAt=0; -async function messageFields(id){let cached=metadataCache.get(id);if(cached&&Date.now()-cached.at<60000)return cached.fields;if(!metadataKey||Date.now()-metadataKeyAt>600000){const status=await bpq('/Mail/Status');metadataKey=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];metadataKeyAt=Date.now();}if(!metadataKey)throw new Error('Metadati BBS non disponibili');const html=await bpq('/Mail/MsgDetails?'+metadataKey,{method:'POST',body:String(id)});const fields={};for(const input of html.matchAll(/]*>/gi)){const name=input[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=input[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);if(name)fields[name[1]??name[2]??name[3]]=decode(value?.[1]??value?.[2]??value?.[3]??'');}metadataCache.set(id,{at:Date.now(),fields});return fields;} +function messageFields(id){return metadataReads.run(id,()=>readMessageFields(id));} +async function readMessageFields(id){let cached=metadataCache.get(id);if(cached&&Date.now()-cached.at<60000)return cached.fields;if(!metadataKey||Date.now()-metadataKeyAt>600000){const status=await bpq('/Mail/Status');metadataKey=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];metadataKeyAt=Date.now();}if(!metadataKey)throw new Error('Metadati BBS non disponibili');const html=await bpq('/Mail/MsgDetails?'+metadataKey,{method:'POST',body:String(id)});const fields={};for(const input of html.matchAll(/]*>/gi)){const name=input[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=input[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);if(name)fields[name[1]??name[2]??name[3]]=decode(value?.[1]??value?.[2]??value?.[3]??'');}metadataCache.set(id,{at:Date.now(),fields});return fields;} async function mailMetadata(list){const out=[];for(const item of list.filter(m=>m.type==='P')){const f=await messageFields(item.id);const m={...item,from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject};const via=f.VIA||m.via,emailFrom=f.EFROM||'';if(m.to==='RMS'||m.from==='RMS'||/WINLINK|@/i.test(via+emailFrom)){const full={...m,via,emailFrom,address:m.to==='RMS'?via:m.to,fromAddress:emailFrom?(emailFrom.startsWith('@')?m.from+emailFrom:emailFrom):m.from};out.push({...full,direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;} -async function winlink(){const list=await mailMetadata(await messages());const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}const radioSession=winlinkRadio.snapshot();const history=forwardingHistory(await forwarding.logs().catch(()=>''),config.cmsPeer||'RMS');const last=history[0];const radioLatest=radioSession&&(radioSession.restoring||last&&Math.abs(Date.parse(last.startedAt)-Date.parse(radioSession.startedAt))<5000);return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||null,radioSession,transport:radioLatest?'radio':'internet',radioSupported:Boolean(config.radio&&modemFamily(config.radio.driver)&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};} -async function deleteMessage(id){const list=await messages();if(!list.some(m=>m.id===id))throw new Error('Messaggio non presente');const {key}=await mailContext();await bpq('/WebMail/WMDel/'+id+'?'+key);metadataCache.delete(id);if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};} +async function winlink(){const list=await mailMetadata(await messages(false));for(const m of list)Object.assign(m,await messageTimes(m.id));const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}const radioSession=winlinkRadio.snapshot();const history=forwardingHistory(await forwarding.logs().catch(()=>''),config.cmsPeer||'RMS');const last=history[0];const radioLatest=radioSession&&(radioSession.restoring||last&&Math.abs(Date.parse(last.startedAt)-Date.parse(radioSession.startedAt))<5000);return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||null,radioSession,transport:radioLatest?'radio':'internet',radioSupported:Boolean(config.radio&&modemFamily(config.radio.driver)&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};} +async function deleteMessage(id){const list=await messages();if(!list.some(m=>m.id===id))throw new Error('Messaggio non presente');const {key}=await mailContext();await bpq('/WebMail/WMDel/'+id+'?'+key);metadataCache.delete(id);timestampCache.delete(id);metadataReads.invalidate(id);mailReads.clear();if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};} async function attachedMessage(id){const visible=await messages(false);const item=visible.find(m=>m.id===id);if(!item)throw new Error('Messaggio non disponibile');const file=path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes');const info=await stat(file);if(info.size>32*1024*1024)throw new Error('Messaggio troppo grande per il download web (32 MB)');const bytes=await readFile(file);const files=parseAttachments(bytes);const rebuilt=await sevenPlus.forMessage(id,visible);if(rebuilt?.file)files.push({...rebuilt.file,index:files.length});const encoded=item.subject.match(/^7\+\s+(.+?)\s+(\d+)\/(\d+)$/i);return {item,bytes,files,encoded:rebuilt?.metadata||(encoded?{name:safeName(encoded[1]),part:Number(encoded[2]),total:Number(encoded[3]),state:'unavailable'}:null)};} async function sendMessage(data){ const to=String(data.to||'').trim().toUpperCase(),subject=String(data.subject||'').trim(),text=String(data.text||'').trim(),type=String(data.type||'P'); @@ -90,7 +94,7 @@ async function sendMessage(data){ const response=await bpq('/WebMail/EMSave?'+key,{method:'POST',body:form}); if(/alert\(/i.test(response)&&!/(sent|saved|created)/i.test(response))throw new Error(plain(response.match(/alert\(["']([^"']+)/)?.[1]||'BPQ ha rifiutato il messaggio')); // A successful write must be visible in BPQ's message list, not inferred from HTTP 200. - const list=await messages();const expectedTo=/^RMS[/:]/.test(to)||/@[^@]*\./.test(to)?'RMS':to.split('@')[0];const created=list.find(m=>!previous.has(m.id)&&ownCall(m.from,config.sysop.call)&&m.subject===subject&&(m.to===expectedTo||m.to===to.split('@')[0])); + mailReads.clear();const list=await messages();const expectedTo=/^RMS[/:]/.test(to)||/@[^@]*\./.test(to)?'RMS':to.split('@')[0];const created=list.find(m=>!previous.has(m.id)&&ownCall(m.from,config.sysop.call)&&m.subject===subject&&(m.to===expectedTo||m.to===to.split('@')[0])); if(!created)throw new Error('BPQ non ha confermato il salvataggio. Controlla la lista prima di riprovare.'); return {id:created.id}; } @@ -101,6 +105,7 @@ const server=http.createServer(async(req,res)=>{ if(!/^(localhost|127\.0\.0\.1|192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3})$/.test(host.split(':')[0])||host.split(':')[1]!==String(port)){json(res,403,{error:'Host non autorizzato'});return;} res.setHeader('X-Content-Type-Options','nosniff');res.setHeader('X-Frame-Options','DENY');res.setHeader('Referrer-Policy','same-origin');res.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; worker-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"); const url=new URL(req.url,'http://'+host); + if(url.pathname==='/health'&&req.method==='GET'){json(res,200,{service:'bpq-console',pid:process.pid});return;} if(req.method==='POST'&&req.headers.origin!=='http://'+host){json(res,403,{error:'Origine non autorizzata'});return;} if(url.pathname==='/api/login'&&req.method==='POST'){ const ip=req.socket.remoteAddress;let a=attempts.get(ip);if(a&&a.until>Date.now()&&a.count>=10){json(res,429,{error:'Troppi tentativi. Riprova tra 15 minuti.'});return;}if(!a||a.until{ } if(url.pathname.startsWith('/api/')){ const user=session(req);if(!user){json(res,401,{error:'Accedi con le credenziali BPQ'});return;} - const capability=url.pathname.startsWith('/api/chat')?'chat':url.pathname.startsWith('/api/monitor')?'monitor':url.pathname.startsWith('/api/winlink')?'winlink':url.pathname.startsWith('/api/forwarding')||url.pathname.startsWith('/api/messages')||url.pathname==='/api/sync'?'bbs':null;if(capability&&!config.features[capability]){json(res,409,{error:'Servizio non configurato in BPQ'});return;} + const capability=url.pathname.startsWith('/api/terminal')?'terminal':url.pathname.startsWith('/api/chat')?'chat':url.pathname.startsWith('/api/monitor')?'monitor':url.pathname.startsWith('/api/winlink')?'winlink':url.pathname.startsWith('/api/forwarding')||url.pathname.startsWith('/api/messages')||url.pathname==='/api/sync'?'bbs':null;if(capability&&!config.features[capability]){json(res,409,{error:'Servizio non configurato in BPQ'});return;} if(req.method==='POST'&&!equal(req.headers['x-csrf-token']||'',user.csrf)){json(res,403,{error:'Sessione non valida. Ricarica la pagina.'});return;} if(url.pathname.startsWith('/api/terminal')){ if(!config.telnetPort)throw new Error('Porta Telnet BPQ non configurata'); diff --git a/single-flight.mjs b/single-flight.mjs new file mode 100644 index 0000000..e847a4a --- /dev/null +++ b/single-flight.mjs @@ -0,0 +1,7 @@ +// Share only work currently in flight. Results are never cached here. +export class SingleFlight { + constructor(){this.pending=new Map();} + run(key,work){if(this.pending.has(key))return this.pending.get(key);const promise=Promise.resolve().then(work).finally(()=>{if(this.pending.get(key)===promise)this.pending.delete(key);});this.pending.set(key,promise);return promise;} + invalidate(key){this.pending.delete(key);} + clear(){this.pending.clear();} +} diff --git a/single-flight.test.mjs b/single-flight.test.mjs new file mode 100644 index 0000000..3f4d560 --- /dev/null +++ b/single-flight.test.mjs @@ -0,0 +1,11 @@ +import {test} from 'node:test';import assert from 'node:assert/strict';import {SingleFlight} from './single-flight.mjs'; +test('simultaneous mail readers share one native session and list, without caching stale results',async()=>{ + const flights=new SingleFlight();let opened=0,lists=0;const context=()=>flights.run('session',async()=>{await new Promise(r=>setTimeout(r,5));return ++opened;});const read=()=>flights.run('messages',async()=>{const key=await context();lists++;await new Promise(r=>setTimeout(r,5));assert.equal(key,opened);return [{id:lists}];}); + const results=await Promise.all([read(),read(),read(),read()]);assert.equal(opened,1);assert.equal(lists,1);assert.ok(results.every(v=>v===results[0]));await read();assert.equal(opened,2);assert.equal(lists,2); +}); +test('failed metadata requests can retry and separate messages never share fields',async()=>{ + const flights=new SingleFlight();let attempts=0;const work=()=>flights.run(1,async()=>{attempts++;throw new Error('native offline');});await Promise.all([assert.rejects(work()),assert.rejects(work())]);assert.equal(attempts,1);await assert.rejects(work());assert.equal(attempts,2);assert.deepEqual(await Promise.all([flights.run(1,()=>({id:1})),flights.run(2,()=>({id:2}))]),[{id:1},{id:2}]); +}); +test('writes invalidate pending reads without letting an old reader remove a newer operation',async()=>{ + const flights=new SingleFlight();let releaseOld,releaseNew;const old=flights.run('messages',()=>new Promise(r=>releaseOld=r));await Promise.resolve();flights.invalidate('messages');const current=flights.run('messages',()=>new Promise(r=>releaseNew=r));await Promise.resolve();releaseOld('before write');assert.equal(await old,'before write');assert.equal(flights.run('messages',()=>{throw new Error('duplicate reader');}),current);releaseNew('after write');assert.equal(await current,'after write');assert.equal(await flights.run('messages',()=> 'fresh'),'fresh'); +}); diff --git a/test.mjs b/test.mjs index a612d24..7ddfcb7 100644 --- a/test.mjs +++ b/test.mjs @@ -54,8 +54,8 @@ test('generic PACTOR station runs without VARA, chat, monitor or BBS',async()=>{ const child=cp.spawn(process.execPath,['server.mjs'],{cwd:process.cwd(),env:{...process.env,BPQ_ROOT:tmp,BPQ_CONSOLE_CONFIG:path.join(tmp,'console.config.json'),BPQ_CONSOLE_PORT:'18991'},windowsHide:true,stdio:['ignore','pipe','pipe']}); try{ await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(new Error('Server fixture timeout')),8000);child.stdout.once('data',()=>{clearTimeout(timeout);resolve()});child.once('exit',code=>{clearTimeout(timeout);reject(new Error('Server fixture exited '+code))})}); - const base='http://127.0.0.1:18991';const login=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({user:'admin',password:'fixture'})});assert.equal(login.status,200);const user=await login.json();assert.equal(user.call,'N9DEMO');assert.equal(user.config.features.vara,false);assert.equal(user.config.features.bbs,false);assert.equal(user.config.radio.id,3);assert.equal(JSON.stringify(user.config).includes('fixture'),false); - const headers={Cookie:login.headers.get('set-cookie').split(';')[0]};const logbook=await fetch(base+'/api/journal',{headers});assert.equal(logbook.status,200);assert.deepEqual((await logbook.json()).sessions,[]);const denied=await fetch(base+'/api/stations/location',{method:'POST',headers:{...headers,Origin:base,'Content-Type':'application/json'},body:JSON.stringify({call:'N3TEST',locator:'JN45NN'})});assert.equal(denied.status,403);assert.equal((await fetch(base+'/api/chat',{headers})).status,409);assert.equal((await fetch(base+'/api/monitor',{headers})).status,409);assert.equal((await fetch(base+'/api/winlink',{headers})).status,409); + const base='http://127.0.0.1:18991';const health=await fetch(base+'/health');assert.equal(health.status,200);assert.equal((await health.json()).service,'bpq-console');const login=await fetch(base+'/api/login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:JSON.stringify({user:'admin',password:'fixture'})});assert.equal(login.status,200);const user=await login.json();assert.equal(user.call,'N9DEMO');assert.equal(user.config.features.vara,false);assert.equal(user.config.features.bbs,false);assert.equal(user.config.radio.id,3);assert.equal(JSON.stringify(user.config).includes('fixture'),false); + const headers={Cookie:login.headers.get('set-cookie').split(';')[0]};const logbook=await fetch(base+'/api/journal',{headers});assert.equal(logbook.status,200);assert.deepEqual((await logbook.json()).sessions,[]);const denied=await fetch(base+'/api/stations/location',{method:'POST',headers:{...headers,Origin:base,'Content-Type':'application/json'},body:JSON.stringify({call:'N3TEST',locator:'JN45NN'})});assert.equal(denied.status,403);assert.equal((await fetch(base+'/api/terminal',{headers})).status,409);assert.equal((await fetch(base+'/api/chat',{headers})).status,409);assert.equal((await fetch(base+'/api/monitor',{headers})).status,409);assert.equal((await fetch(base+'/api/winlink',{headers})).status,409); await new Promise(r=>setTimeout(r,1200));const telemetry=await (await fetch(base+'/api/telemetry',{headers})).json();assert.equal(telemetry.current.available,true);assert.equal(telemetry.current.nativeRate.listening,false);assert.equal(telemetry.current.varaCpu,null);assert.equal(telemetry.current.sent,12); const dash=await (await fetch(base+'/api/dashboard',{headers})).json();assert.equal(dash.counts.messages,0); }finally{child.kill();await new Promise(r=>child.once('exit',r));await new Promise(r=>upstream.close(r));await fs.rm(tmp,{recursive:true,force:true});}