Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(scan): choose the port range before a deep scan
Pouzorc6d6b525eaa0
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.pyindex 50107d1..47955c0 100644--- a/backend/app/api/routes/scan.py+++ b/backend/app/api/routes/scan.py@@ -35,6 +35,7 @@ from app.services.node_dedupe import dedupe_nodes_by_device, find_duplicate_nodefrom app.services.scanner import (DeepScanOptions,_valid_port_range,+ _valid_port_spec,request_cancel,run_device_scan,run_scan,@@ -191,6 +192,7 @@ async def _background_device_scan(device_id: str,deep_scan: DeepScanOptions | None = None,full_ports: bool = True,+ ports: str | None = None,) -> None:async with AsyncSessionLocal() as db:try:@@ -200,6 +202,7 @@ async def _background_device_scan(run_id,deep_scan=deep_scan or DeepScanOptions(),full_ports=full_ports,+ ports=ports,)except Exception:logger.exception("Device scan run %s failed unexpectedly", run_id)@@ -246,12 +249,27 @@ async def trigger_scan(class RescanDeviceRequest(BaseModel):- """Per-device deep rescan. Defaults to every TCP port — that is the point."""+ """Per-device deep rescan. Defaults to every TCP port — that is the point.++ ``ports`` narrows the sweep to what the user typed in the deep-scan dialog+ (``80,443``, ``1-1024``); it wins over ``full_ports``.+ """full_ports: bool = True+ ports: str | None = Nonehttp_probe_enabled: bool | None = Noneverify_tls: bool | None = None+ @field_validator("ports")+ @classmethod+ def _check_ports(cls, v: str | None) -> str | None:+ if v is None or not v.strip():+ return None+ spec = v.strip()+ if not _valid_port_spec(spec):+ raise ValueError("Invalid port range")+ return spec+@router.post("/pending/{device_id}/rescan", response_model=ScanRunResponse)async def rescan_device(@@ -297,7 +315,7 @@ async def rescan_device(await db.commit()await db.refresh(run)background_tasks.add_task(- _background_device_scan, run.id, device_id, deep_scan, p.full_ports+ _background_device_scan, run.id, device_id, deep_scan, p.full_ports, p.ports)return rundiff --git a/backend/app/services/scanner.py b/backend/app/services/scanner.pyindex 54a6457..375b01e 100644--- a/backend/app/services/scanner.py+++ b/backend/app/services/scanner.py@@ -75,9 +75,67 @@ _FULL_PORTS = "1-65535"_DEEP_CHUNK_SIZE = 8192+def _parse_port_spec(spec: str) -> list[tuple[int, int]]:+ """Parse an nmap ``-p`` spec into sorted, merged ``(start, end)`` ranges.++ Accepts what the user can type in the deep-scan dialog: ``80``,+ ``8000-9000``, or a comma list of both. Returns ``[]`` for anything invalid+ — the caller turns that into a 422 rather than handing nmap a bad ``-p``.+ """+ ranges: list[tuple[int, int]] = []+ for token in (t.strip() for t in spec.split(",")):+ if not token or not _valid_port_range(token):+ return []+ parts = [int(p) for p in token.split("-")]+ ranges.append((parts[0], parts[-1]))+ if not ranges:+ return []+ ranges.sort()+ merged = [ranges[0]]+ for start, end in ranges[1:]:+ last_start, last_end = merged[-1]+ if start <= last_end + 1:+ merged[-1] = (last_start, max(last_end, end))+ else:+ merged.append((start, end))+ return merged+++def _valid_port_spec(spec: str) -> bool:+ """True when ``spec`` is a usable comma list of ports/ranges."""+ return bool(_parse_port_spec(spec))+++def _port_chunks(spec: str, size: int = _DEEP_CHUNK_SIZE) -> list[str]:+ """Slice a port spec into nmap ``-p`` specs of at most ``size`` ports each.++ Ranges are packed, not scanned one call per range: ``80,443`` is one chunk,+ not two, while ``1-65535`` becomes eight. Each chunk is a scan boundary —+ where a stop request lands and where the time budget is checked.+ """+ chunks: list[str] = []+ current: list[str] = []+ budget = size+ for start, end in _parse_port_spec(spec):+ cursor = start+ while cursor <= end:+ take = min(budget, end - cursor + 1)+ stop = cursor + take - 1+ current.append(f"{cursor}-{stop}" if stop > cursor else str(cursor))+ budget -= take+ cursor = stop + 1+ if budget == 0:+ chunks.append(",".join(current))+ current = []+ budget = size+ if current:+ chunks.append(",".join(current))+ return chunks++def _deep_port_chunks(size: int = _DEEP_CHUNK_SIZE) -> list[str]:"""Slice the whole TCP range into nmap ``-p`` specs of ``size`` ports."""- return [f"{start}-{min(start + size - 1, 65535)}" for start in range(1, 65536, size)]+ return _port_chunks(_FULL_PORTS, size)def _build_port_spec(http_ranges: list[str] | None, full: bool = False) -> str:@@ -763,6 +821,7 @@ async def run_device_scan(run_id: str,deep_scan: DeepScanOptions | None = None,full_ports: bool = True,+ ports: str | None = None,) -> None:"""Deep-rescan one known device and refresh its inventory row.@@ -771,11 +830,17 @@ async def run_device_scan(TCP ports, which is the point of the feature — a device added before thescanner knew a service, or listening on a port no curated list covers.Minutes, not seconds; the run is cancellable like any other.++ ``ports`` narrows that to a user-chosen spec (``80,443``, ``1-1024``) and+ wins over ``full_ports`` — the dialog prefills the full range, so a caller+ that passes something else means it."""from app.api.routes.status import broadcast_scan_updatedeep_scan = deep_scan or DeepScanOptions()- port_spec = _build_port_spec(deep_scan.http_ranges, full=full_ports)+ port_spec = (+ ports if ports else _build_port_spec(deep_scan.http_ranges, full=full_ports)+ )try:device = await db.get(InventoryDevice, device_id)@@ -793,7 +858,16 @@ async def run_device_scan(# The full range goes out in slices so a stop request lands within one# slice instead of at the end, and so a spent budget keeps the ports# found so far. A curated port list is one call, as before.- chunks = _deep_port_chunks() if full_ports else [port_spec]+ if ports:+ chunks = _port_chunks(ports)+ elif full_ports:+ chunks = _deep_port_chunks()+ else:+ chunks = [port_spec]+ # Retry-free timing pays for itself over thousands of ports on a host+ # that drops packets; over a handful it only costs accuracy.+ total_ports = sum(end - start + 1 for start, end in _parse_port_spec(port_spec))+ bounded = total_ports > _DEEP_CHUNK_SIZEdeadline = time.monotonic() + settings.scanner_deep_host_timeoutfound: list[dict[str, Any]] = []seen: set[tuple[str, int]] = set()@@ -812,7 +886,7 @@ async def run_device_scan(break# bounded: retry-free timing, for a host that drops packets.scanned = await asyncio.to_thread(- _nmap_scan_single, dict(host), chunk, full_ports+ _nmap_scan_single, dict(host), chunk, bounded)for port in scanned.get("open_ports") or []:key = (port["protocol"], port["port"])diff --git a/backend/tests/scan/test_scan_routes.py b/backend/tests/scan/test_scan_routes.pyindex 376fdaf..8bf5a3c 100644--- a/backend/tests/scan/test_scan_routes.py+++ b/backend/tests/scan/test_scan_routes.py@@ -444,6 +444,50 @@ async def test_rescan_device_creates_run_for_that_ip(client: AsyncClient, headerassert bg.call_args.args[3] is True+async def test_rescan_device_passes_the_requested_port_range(+ client: AsyncClient, headers, pending_device+):+ """The dialog's range reaches the scanner verbatim."""+ with patch("app.api.routes.scan._background_device_scan", new_callable=AsyncMock) as bg:+ res = await client.post(+ f"/api/v1/scan/pending/{pending_device.id}/rescan",+ headers=headers,+ json={"ports": " 80,443,8000-9000 "},+ )+ assert res.status_code == 200, res.text+ assert bg.call_args.args[4] == "80,443,8000-9000"+++async def test_rescan_device_rejects_an_unusable_port_range(+ client: AsyncClient, headers, pending_device+):+ """A bad spec is refused here, not handed to nmap."""+ for bad in ["0", "65536", "100-50", "80,", "http"]:+ res = await client.post(+ f"/api/v1/scan/pending/{pending_device.id}/rescan",+ headers=headers,+ json={"ports": bad},+ )+ assert res.status_code == 422, f"{bad}: {res.text}"+++async def test_rescan_device_treats_a_blank_range_as_the_full_sweep(+ client: AsyncClient, headers, pending_device+):+ with patch("app.api.routes.scan._background_device_scan", new_callable=AsyncMock) as bg:+ res = await client.post(+ f"/api/v1/scan/pending/{pending_device.id}/rescan",+ headers=headers,+ json={"ports": " "},+ )+ assert res.status_code == 200, res.text+ assert bg.call_args.args[4] is None+ assert bg.call_args.args[3] is True++@pytest.mark.asyncioasync def test_rescan_device_unknown_id_404(client: AsyncClient, headers):res = await client.post(f"/api/v1/scan/pending/{uuid.uuid4()}/rescan", headers=headers)diff --git a/backend/tests/test_scanner.py b/backend/tests/test_scanner.pyindex cce5863..bda20d8 100644--- a/backend/tests/test_scanner.py+++ b/backend/tests/test_scanner.py@@ -427,6 +427,27 @@ def test_deep_port_chunks_cover_every_port_once():assert covered == list(range(1, 65536))+def test_port_chunks_pack_ranges_and_honour_the_slice_size():+ from app.services.scanner import _port_chunks++ # Small ranges share one call instead of one call each.+ assert _port_chunks("80,443,8000-9000") == ["80,443,8000-9000"]+ # A range wider than the slice is cut at the slice boundary.+ assert _port_chunks("1-100", 40) == ["1-40", "41-80", "81-100"]+ # Overlapping input is merged before slicing, so no port is scanned twice.+ assert _port_chunks("1-100,50-200", 1000) == ["1-200"]+ assert _port_chunks("nonsense") == []+++def test_parse_port_spec_rejects_what_nmap_could_not_use():+ from app.services.scanner import _parse_port_spec, _valid_port_spec++ for bad in ["", " ", "0", "65536", "100-50", "80,", "http", "-80"]:+ assert _parse_port_spec(bad) == [], bad+ assert _valid_port_spec(bad) is False, bad+ assert _valid_port_spec("80,443,8000-9000") is True++# ---------------------------------------------------------------------------# _nmap_scan# ---------------------------------------------------------------------------@@ -1253,6 +1274,44 @@ async def test_run_device_scan_unions_ports_across_slices(mem_db):assert len(_deep_port_chunks()) == 8+async def test_run_device_scan_honours_a_requested_port_range(mem_db):+ """A user-chosen range replaces the full sweep — and skips retry-free timing.++ A handful of ports is cheap enough to scan properly; the bounded flags only+ pay off over thousands of them.+ """+ from app.services.scanner import run_device_scan++ run_id = _make_run_id()+ async with mem_db() as session:+ session.add(ScanRun(id=run_id, status="running", kind="device", ranges=["192.168.1.9/32"]))+ session.add(InventoryDevice(id="d1", ip="192.168.1.9", status="pending", services=[]))+ await session.commit()++ calls = []++ def _scanned(host_dict, port_spec, bounded=False):+ calls.append((port_spec, bounded))+ host_dict["open_ports"] = [{"port": 8096, "protocol": "tcp", "banner": ""}]+ return host_dict++ async with mem_db() as session:+ with patch("app.services.scanner._nmap_scan_single", side_effect=_scanned), \+ patch("app.api.routes.status.broadcast_scan_update", new_callable=AsyncMock):+ await run_device_scan("d1", session, run_id, ports="8000-9000")++ async with mem_db() as session:+ device = await session.get(InventoryDevice, "d1")+ run = await session.get(ScanRun, run_id)++ assert calls == [("8000-9000", False)]+ assert device is not None and run is not None+ assert {s.get("port") for s in device.services} == {8096}+ assert run.status == "done"+ assert run.error is None++@pytest.mark.asyncioasync def test_run_device_scan_keeps_what_it_found_when_the_budget_runs_out(mem_db):"""A spent budget stops the sweep — it never discards the ports found.diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.tsindex 73edb64..0d4b236 100644--- a/frontend/src/api/client.ts+++ b/frontend/src/api/client.ts@@ -176,7 +176,7 @@ export const scanApi = {* Returns the ScanRun, so the caller polls `run` and can `stop` it.* 409 when the device has no IP, is hidden, or is already being rescanned.*/- rescanDevice: (id: string, opts?: { full_ports?: boolean; http_probe_enabled?: boolean; verify_tls?: boolean }) =>+ rescanDevice: (id: string, opts?: { full_ports?: boolean; ports?: string; http_probe_enabled?: boolean; verify_tls?: boolean }) =>api.post<ScanRunSummary>(`/scan/pending/${id}/rescan`, opts ?? {}),hidden: () => api.get('/scan/hidden'),runs: () => api.get('/scan/runs'),diff --git a/frontend/src/components/modals/DeepScanModal.tsx b/frontend/src/components/modals/DeepScanModal.tsxnew file mode 100644index 0000000..c49b8ec--- /dev/null+++ b/frontend/src/components/modals/DeepScanModal.tsx@@ -0,0 +1,130 @@+/**+ * Deep scan — pick what to sweep before starting one.+ *+ * The full 65535-port range is the default and the point of the feature+ * (issue #350), but it costs minutes per host. A user who already knows where+ * a service lives, or who only wants the low ports back, types a narrower spec+ * here instead of waiting for the whole range.+ */+import { useState } from 'react'+import { Radar } from 'lucide-react'+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { countPorts, isValidPortSpec, FULL_PORT_RANGE } from '@/utils/portSpec'+import modalStyles from './modal-interactive.module.css'++const PRESETS: Array<{ label: string; spec: string }> = [+ { label: 'All ports', spec: FULL_PORT_RANGE },+ { label: 'Well-known', spec: '1-1024' },+ { label: 'Common', spec: '1-10000' },+]++interface DeepScanModalProps {+ open: boolean+ target?: string | null+ onClose: () => void+ onStart: (ports: string) => void+}++export function DeepScanModal({ open, target, onClose, onStart }: DeepScanModalProps) {+ // Prefilled with the full range. The caller mounts this only while it is+ // open, so a previous narrow spec never becomes the next scan's default.+ const [spec, setSpec] = useState(FULL_PORT_RANGE)++ const trimmed = spec.trim()+ const valid = isValidPortSpec(trimmed)+ const total = countPorts(trimmed)++ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault()+ if (!valid) return+ onStart(trimmed)+ onClose()+ }++ return (+ <Dialog open={open} onOpenChange={(o) => !o && onClose()}>+ <DialogContent className="sm:max-w-md bg-[#161b22] border-[#30363d]">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-base">+ <Radar size={15} className="text-[#00d4ff]" />+ Deep scan{target ? ` — ${target}` : ''}+ </DialogTitle>+ </DialogHeader>++ <form onSubmit={handleSubmit} className="flex flex-col gap-3">+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="deep-scan-ports" className="text-xs text-muted-foreground">+ Port range+ </Label>+ <Input+ id="deep-scan-ports"+ value={spec}+ onChange={(e) => setSpec(e.target.value)}+ autoFocus+ spellCheck={false}+ placeholder={FULL_PORT_RANGE}+ data-testid="deep-scan-ports"+ className="h-8 font-mono text-sm bg-[#21262d] border-[#30363d]"+ />+ <div className="flex items-center justify-between gap-2 text-[10px]">+ <span className="text-muted-foreground">+ A port, a range, or a comma list — <span className="font-mono">80,443,8000-9000</span>+ </span>+ {trimmed !== '' && (+ <span className={valid ? 'text-muted-foreground shrink-0' : 'text-[#f85149] shrink-0'}>+ {valid ? `${total.toLocaleString('en-US')} ports` : 'Invalid range'}+ </span>+ )}+ </div>+ </div>++ <div className="flex flex-wrap gap-1.5">+ {PRESETS.map((preset) => (+ <button+ key={preset.spec}+ type="button"+ onClick={() => setSpec(preset.spec)}+ className={`px-2 py-1 text-[10px] border transition-colors cursor-pointer ${modalStyles['modal-radius']} ${+ trimmed === preset.spec+ ? 'border-[#00d4ff] text-[#00d4ff] bg-[#00d4ff]/10'+ : 'border-[#30363d] text-muted-foreground hover:text-foreground'+ }`}+ >+ {preset.label}+ </button>+ ))}+ </div>++ <p className="text-[10px] text-muted-foreground">+ Scanning runs in the background — the whole range takes several minutes. Found services are+ merged into the device; nothing already recorded is removed.+ </p>++ <div className="flex justify-end gap-2 pt-1">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className={`cursor-pointer ${modalStyles['modal-cancel-hover']}`}+ onClick={onClose}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ size="sm"+ disabled={!valid}+ data-testid="deep-scan-start"+ className="bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"+ >+ Start scan+ </Button>+ </div>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/components/modals/InventoryDeviceModal.tsx b/frontend/src/components/modals/InventoryDeviceModal.tsxindex f173854..d316aed 100644--- a/frontend/src/components/modals/InventoryDeviceModal.tsx+++ b/frontend/src/components/modals/InventoryDeviceModal.tsx@@ -42,6 +42,7 @@ import { Label } from '@/components/ui/label'import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue } from '@/components/ui/select'import { PropertyList } from '@/components/common/PropertyList'import { ServiceModal } from './ServiceModal'+import { DeepScanModal } from './DeepScanModal'import { scanApi } from '@/api/client'import { useCanvasStore } from '@/stores/canvasStore'import { useThemeStore } from '@/stores/themeStore'@@ -51,6 +52,7 @@ import { NODE_TYPE_DEFAULT_ICONS } from '@/utils/nodeIcons'import { isRackDevice, orderedSources, SOURCE_META } from '@/utils/deviceSources'import { DEVICE_TYPE_GROUPS } from '@/utils/nodeTypeGroups'import { formatRelative, formatTimestamp } from '@/utils/timeFormat'+import { countPorts } from '@/utils/portSpec'import { serviceToForm, type ServiceFormData, type ServiceSubmitData } from '@/utils/serviceForm'import { NODE_TYPE_LABELS, type CheckMethod, type InventoryEntry, type NodeProperty, type NodeType, type ServiceInfo } from '@/types'import modalStyles from './modal-interactive.module.css'@@ -268,6 +270,8 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn// The id of the deep rescan this modal started, while it is still running.const [rescanRunId, setRescanRunId] = useState<string | null>(null)const [rescanStarting, setRescanStarting] = useState(false)+ // The port-range dialog, opened by the Deep scan link.+ const [deepScanOpen, setDeepScanOpen] = useState(false)const activeTheme = useThemeStore((s) => s.activeTheme)// Kept in a ref so the poll effect below doesn't restart — and lose its// timer — every time the parent re-renders with a new callback identity.@@ -286,6 +290,7 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnsetEditing(false)setSvcModal(null)setRescanRunId(null)+ setDeepScanOpen(false)}, [device])// Wait on a running deep rescan. A full 65535-port scan takes minutes, so the@@ -360,13 +365,14 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnsetServices(device.services ?? [])}- const handleRescan = async () => {+ const handleRescan = async (ports: string) => {if (!device.ip || rescanRunId || rescanStarting) returnsetRescanStarting(true)try {- const res = await scanApi.rescanDevice(device.id, { full_ports: true })+ const res = await scanApi.rescanDevice(device.id, { ports })setRescanRunId(res.data.id)- toast.info('Deep scan started — all 65535 ports, this takes a few minutes')+ const n = countPorts(ports)+ toast.info(`Deep scan started — ${n.toLocaleString('en-US')} ports, this takes a few minutes`)} catch (err) {const detail = (err as { response?: { data?: { detail?: string } } }).response?.data?.detailtoast.error(detail ?? 'Could not start the scan')@@ -707,10 +713,10 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn</button>) : (<button- onClick={handleRescan}+ onClick={() => setDeepScanOpen(true)}disabled={rescanStarting}data-testid="device-rescan"- title="Scan all 65535 TCP ports and refresh the services"+ title="Pick a port range and refresh the services"className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"><Radar size={10} /> Deep scan@@ -868,6 +874,15 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn)}</div>+ {deepScanOpen && (+ <DeepScanModal+ open+ target={device.ip}+ onClose={() => setDeepScanOpen(false)}+ onStart={handleRescan}+ />+ )}+{svcModal && (<ServiceModalkey={`svc-${svcModal.index ?? 'new'}`}diff --git a/frontend/src/components/modals/__tests__/InventoryDeviceModalRescan.test.tsx b/frontend/src/components/modals/__tests__/InventoryDeviceModalRescan.test.tsxindex 9225141..0ad4cdc 100644--- a/frontend/src/components/modals/__tests__/InventoryDeviceModalRescan.test.tsx+++ b/frontend/src/components/modals/__tests__/InventoryDeviceModalRescan.test.tsx@@ -39,6 +39,15 @@ function makeDevice(overrides: Partial<InventoryEntry> = {}): InventoryEntry {}}+/** The link opens the port-range dialog; the scan starts from there. */+async function startScan() {+ fireEvent.click(screen.getByTestId('device-rescan'))+ await waitFor(() => expect(screen.getByTestId('deep-scan-start')).toBeInTheDocument())+ // The start resolves a promise that sets state — act() keeps that update+ // inside the test's control, fake timers or not.+ await act(async () => { fireEvent.click(screen.getByTestId('deep-scan-start')) })+}+const noop = { onClose: vi.fn(), onApprove: vi.fn(), onHide: vi.fn(), onIgnore: vi.fn() }beforeEach(() => {@@ -74,16 +83,42 @@ describe('InventoryDeviceModal — deep rescan', () => {it('scans every port and swaps to a stop control while it runs', async () => {render(<InventoryDeviceModal {...noop} device={makeDevice()} />)- fireEvent.click(screen.getByTestId('device-rescan'))+ await startScan()await waitFor(() => expect(screen.getByTestId('device-rescan-stop')).toBeInTheDocument())- expect(mockRescanDevice).toHaveBeenCalledWith('dev-1', { full_ports: true })+ expect(mockRescanDevice).toHaveBeenCalledWith('dev-1', { ports: '1-65535' })expect(screen.queryByTestId('device-rescan')).toBeNull()})- it('stops the run through the same ScanRun the header uses', async () => {+ it('sends the range the user typed instead of the whole space', async () => {+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ fireEvent.click(screen.getByTestId('device-rescan'))+ const input = await screen.findByTestId('deep-scan-ports')+ expect(input).toHaveValue('1-65535')++ fireEvent.change(input, { target: { value: '80,443,8000-9000' } })+ fireEvent.click(screen.getByTestId('deep-scan-start'))++ await waitFor(() =>+ expect(mockRescanDevice).toHaveBeenCalledWith('dev-1', { ports: '80,443,8000-9000' })+ )+ })++ it('refuses to start on a range nmap could not use', async () => {render(<InventoryDeviceModal {...noop} device={makeDevice()} />)fireEvent.click(screen.getByTestId('device-rescan'))+ const input = await screen.findByTestId('deep-scan-ports')++ fireEvent.change(input, { target: { value: '99999' } })+ expect(screen.getByTestId('deep-scan-start')).toBeDisabled()++ fireEvent.click(screen.getByTestId('deep-scan-start'))+ expect(mockRescanDevice).not.toHaveBeenCalled()+ })++ it('stops the run through the same ScanRun the header uses', async () => {+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ await startScan()await waitFor(() => expect(screen.getByTestId('device-rescan-stop')).toBeInTheDocument())fireEvent.click(screen.getByTestId('device-rescan-stop'))@@ -96,7 +131,7 @@ describe('InventoryDeviceModal — deep rescan', () => {})const { toast } = await import('sonner')render(<InventoryDeviceModal {...noop} device={makeDevice()} />)- fireEvent.click(screen.getByTestId('device-rescan'))+ await startScan()await waitFor(() =>expect(toast.error).toHaveBeenCalledWith('A scan is already running for this device')@@ -111,7 +146,7 @@ describe('InventoryDeviceModal — deep rescan', () => {services: [{ port: 8096, protocol: 'tcp', service_name: 'Jellyfin' }],})render(<InventoryDeviceModal {...noop} onSaved={onSaved} device={makeDevice()} />)- fireEvent.click(screen.getByTestId('device-rescan'))+ await startScan()await waitFor(() => expect(screen.getByTestId('device-rescan-stop')).toBeInTheDocument())mockRun.mockResolvedValue({ data: { id: 'run-1', status: 'done', error: null } })@@ -130,7 +165,7 @@ describe('InventoryDeviceModal — deep rescan', () => {const { toast } = await import('sonner')const fresh = makeDevice({ services: [{ port: 22, protocol: 'tcp', service_name: 'SSH' }] })render(<InventoryDeviceModal {...noop} device={makeDevice()} />)- fireEvent.click(screen.getByTestId('device-rescan'))+ await startScan()await waitFor(() => expect(screen.getByTestId('device-rescan-stop')).toBeInTheDocument())// A done run carrying an advisory — it scanned part of the range only.@@ -152,7 +187,7 @@ describe('InventoryDeviceModal — deep rescan', () => {vi.useFakeTimers({ shouldAdvanceTime: true })const { toast } = await import('sonner')render(<InventoryDeviceModal {...noop} device={makeDevice()} />)- fireEvent.click(screen.getByTestId('device-rescan'))+ await startScan()await waitFor(() => expect(screen.getByTestId('device-rescan-stop')).toBeInTheDocument())mockRun.mockResolvedValue({ data: { id: 'run-1', status: 'error', error: 'nmap missing' } })diff --git a/frontend/src/utils/__tests__/portSpec.test.ts b/frontend/src/utils/__tests__/portSpec.test.tsnew file mode 100644index 0000000..c104423--- /dev/null+++ b/frontend/src/utils/__tests__/portSpec.test.ts@@ -0,0 +1,39 @@+import { describe, it, expect } from 'vitest'+import { parsePortSpec, isValidPortSpec, countPorts, FULL_PORT_RANGE } from '../portSpec'++describe('parsePortSpec', () => {+ it('reads a single port, a range and a comma list', () => {+ expect(parsePortSpec('80')).toEqual([[80, 80]])+ expect(parsePortSpec('1-1024')).toEqual([[1, 1024]])+ expect(parsePortSpec('443,80')).toEqual([[80, 80], [443, 443]])+ })++ it('merges overlapping and adjacent ranges', () => {+ expect(parsePortSpec('1-100,50-200')).toEqual([[1, 200]])+ expect(parsePortSpec('1-100,101-200')).toEqual([[1, 200]])+ expect(parsePortSpec('1-100,300-400')).toEqual([[1, 100], [300, 400]])+ })++ it('tolerates whitespace around tokens', () => {+ expect(parsePortSpec(' 80 , 443 ')).toEqual([[80, 80], [443, 443]])+ })++ it('rejects what nmap could not use', () => {+ for (const bad of ['', ' ', '0', '65536', '100-50', '80,', 'http', '80-', '-80', '1-2-3']) {+ expect(parsePortSpec(bad)).toBeNull()+ }+ })+})++describe('isValidPortSpec / countPorts', () => {+ it('counts merged ranges once', () => {+ expect(countPorts('1-100,50-200')).toBe(200)+ expect(countPorts('80,443')).toBe(2)+ expect(countPorts(FULL_PORT_RANGE)).toBe(65535)+ })++ it('counts an invalid spec as nothing', () => {+ expect(isValidPortSpec('nope')).toBe(false)+ expect(countPorts('nope')).toBe(0)+ })+})diff --git a/frontend/src/utils/portSpec.ts b/frontend/src/utils/portSpec.tsnew file mode 100644index 0000000..791fb98--- /dev/null+++ b/frontend/src/utils/portSpec.ts@@ -0,0 +1,50 @@+/**+ * nmap-style port specs — `80`, `1-1024`, or a comma list of both.+ *+ * Mirrors `_parse_port_spec` in `backend/app/services/scanner.py`: the deep-scan+ * dialog validates here so a typo is caught before a request, and the backend+ * validates again because it is the one handing the spec to nmap.+ */++export const FULL_PORT_RANGE = '1-65535'++const TOKEN_RE = /^\d{1,5}(-\d{1,5})?$/++/**+ * Sorted, merged `[start, end]` ranges, or `null` when the spec is unusable.+ * An empty spec is unusable too — a scan of nothing is never what was meant.+ */+export function parsePortSpec(spec: string): Array<[number, number]> | null {+ const tokens = spec.split(',').map((t) => t.trim())+ if (tokens.length === 0 || tokens.some((t) => t === '')) return null++ const ranges: Array<[number, number]> = []+ for (const token of tokens) {+ if (!TOKEN_RE.test(token)) return null+ const parts = token.split('-').map(Number)+ const start = parts[0]+ const end = parts[parts.length - 1]+ if (start < 1 || end > 65535 || start > end) return null+ ranges.push([start, end])+ }++ ranges.sort((a, b) => a[0] - b[0])+ const merged: Array<[number, number]> = [ranges[0]]+ for (const [start, end] of ranges.slice(1)) {+ const last = merged[merged.length - 1]+ if (start <= last[1] + 1) last[1] = Math.max(last[1], end)+ else merged.push([start, end])+ }+ return merged+}++export function isValidPortSpec(spec: string): boolean {+ return parsePortSpec(spec) !== null+}++/** How many ports a spec covers — 0 when it is invalid. */+export function countPorts(spec: string): number {+ const ranges = parsePortSpec(spec)+ if (!ranges) return 0+ return ranges.reduce((sum, [start, end]) => sum + (end - start + 1), 0)+}