mirror of
https://github.com/Zakkaus/doona.git
synced 2026-12-06 08:02:04 +00:00
feat(connections): identify devices by MAC
In dual-stack LANs one device showed up as separate IPv4 and IPv6 entries (daeuniverse/honk#446). honk is adding Connection.src_mac and a `mac` query to listing and closing connections; the vendored contract carries both ahead of that change, and the mock reports MAC addresses for its devices, one of them also over IPv6 and one without a MAC address. A device is now its MAC address when the backend knows it, otherwise its source address. The device ranking, the dashboard ranking widget and the connections grouped by device key on it, so one device's IPv4 and IPv6 traffic merge. An unnamed device keeps the address it showed before: its latest IPv4 address, else its first one. A MAC device links to and filters its connections with `?mac=`; a link in dash, dotted, bare or upper-case form reads as the colon form, one honk cannot read is still sent so its refusal shows, and a MAC address replaces any `src` in the same link, so bulk close never goes out wider than the list. The connection details show the source MAC address as a link that names the device. Names are kept in this browser only, re-read before each save and synced across tabs, and replace the address in the ranking, the groups and the device picker. Search matches the MAC address and its name. With no MAC addresses reported the pages render as before.
This commit is contained in:
35 files changed
+453
-122
No files matched your search
@@ -0,0 +1,4 @@
|
||||
Added
|
||||
|
||||
- With a backend that reports each connection's source MAC address, the device ranking and the connections grouped by device count one device's IPv4 and IPv6 connections together, and a device filters its connections by its MAC address.
|
||||
- A connection's details show its source MAC address, which can be given a name kept in this browser; the name replaces the device's address in the device ranking, groups and device filter.
|
||||
@@ -1,6 +1,6 @@
|
||||
Pin: api-standardize e6b0dbab5599689d965bc18a71be67c809d99d0f + honk 3ae980fed extension
|
||||
|
||||
SHA-256: bc7599a8b693a8a28b64704764cc3b2577b93707b425c66d5d9436b60a50ecac
|
||||
SHA-256: 250c514b10a19068dfaf9635c9b52aa0b99353943cd9d7d7cb9cac854b6995a6
|
||||
|
||||
openapi.yaml combines api-standardize `source/openapi.yaml` at commit
|
||||
e6b0dbab5599689d965bc18a71be67c809d99d0f with the unchanged
|
||||
@@ -18,5 +18,10 @@ optional, as with verify_checksum, because older engines omit it, and leaves out
|
||||
The bundle drops the `pattern` of ProviderCreate.name ahead of the matching
|
||||
api-standardize and honk changes: a subscription tag may be any text the
|
||||
configuration can quote, and names outside [A-Za-z0-9_.-] are written quoted.
|
||||
The bundle adds Connection.src_mac and the `mac` query of listing and closing
|
||||
connections ahead of the matching honk change for daeuniverse/honk issue 446:
|
||||
src_mac is always present, the source MAC address in lower case or null when
|
||||
unknown, and `mac`
|
||||
matches it case-insensitively, combined with `src` by AND.
|
||||
|
||||
Regenerate src/api/types.ts with `pnpm gen:api`.
|
||||
@@ -3995,6 +3995,12 @@ paths:
|
||||
schema:
|
||||
$ref: '#/components/schemas/IpAddress'
|
||||
example: 192.168.1.100
|
||||
- name: mac
|
||||
in: query
|
||||
description: Source MAC address, six colon-separated hex octets, matched case-insensitively; applied with type and src before limit. Totals and truncated describe only matching visible entries.
|
||||
schema:
|
||||
type: string
|
||||
example: aa:bb:cc:dd:ee:ff
|
||||
- $ref: '#/components/parameters/Limit1000'
|
||||
- $ref: '#/components/parameters/Detail'
|
||||
responses:
|
||||
@@ -4022,6 +4028,7 @@ paths:
|
||||
pname: curl
|
||||
state: active
|
||||
src: 192.168.1.100:12345
|
||||
src_mac: aa:bb:cc:dd:ee:ff
|
||||
dst: 1.2.3.4:443
|
||||
domain: example.com
|
||||
outbound: proxy
|
||||
@@ -4046,6 +4053,7 @@ paths:
|
||||
pname: null
|
||||
state: unknown
|
||||
src: 192.168.1.100:5353
|
||||
src_mac: aa:bb:cc:dd:ee:ff
|
||||
dst: 8.8.8.8:53
|
||||
domain: null
|
||||
outbound: direct
|
||||
@@ -4088,9 +4096,10 @@ paths:
|
||||
resources.connections.can_close; unavailable closing returns 404
|
||||
capability_not_supported.
|
||||
|
||||
Combine type and exact source-IP src filters with AND. Missing type and
|
||||
type=all do not restrict the set. Without type=tcp, type=udp, or src,
|
||||
require all=true or return 400 invalid_request before closing anything.
|
||||
Combine type, exact source-IP src and source-MAC mac filters with AND.
|
||||
Missing type and type=all do not restrict the set. Without type=tcp,
|
||||
type=udp, src, or mac, require all=true or return 400 invalid_request
|
||||
before closing anything.
|
||||
all=true does not override supplied filters. Reject limit and detail,
|
||||
which apply only to listing.
|
||||
|
||||
@@ -4123,9 +4132,10 @@ paths:
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/0'
|
||||
- $ref: '#/components/parameters/1'
|
||||
- $ref: '#/components/parameters/2'
|
||||
- name: all
|
||||
in: query
|
||||
description: Explicitly permit an unfiltered close; does not override type or src.
|
||||
description: Explicitly permit an unfiltered close; does not override type, src, or mac.
|
||||
schema:
|
||||
type: boolean
|
||||
default: false
|
||||
@@ -6714,6 +6724,13 @@ components:
|
||||
schema:
|
||||
$ref: '#/components/schemas/IpAddress'
|
||||
example: 192.168.1.100
|
||||
'2':
|
||||
name: mac
|
||||
in: query
|
||||
description: Source MAC address, six colon-separated hex octets, matched case-insensitively; applied with type and src before limit. Totals and truncated describe only matching visible entries.
|
||||
schema:
|
||||
type: string
|
||||
example: aa:bb:cc:dd:ee:ff
|
||||
Detail:
|
||||
name: detail
|
||||
in: query
|
||||
@@ -11018,6 +11035,7 @@ components:
|
||||
- flow_id
|
||||
- pname
|
||||
- state
|
||||
- src_mac
|
||||
- outbound
|
||||
- chain
|
||||
- chain_source
|
||||
@@ -11049,6 +11067,12 @@ components:
|
||||
src:
|
||||
type: string
|
||||
minLength: 1
|
||||
src_mac:
|
||||
type:
|
||||
- string
|
||||
- 'null'
|
||||
pattern: '^[0-9a-f]{2}(:[0-9a-f]{2}){5}$'
|
||||
description: Source MAC address of the flow's first Ethernet frame in lower case, the router's own interface address for traffic the router sends; null when none was captured, such as on a non-Ethernet interface.
|
||||
dst:
|
||||
type: string
|
||||
minLength: 1
|
||||
|
||||
@@ -1049,7 +1049,8 @@ test('the rankings, outbound usage and latency tile open the connections and nod
|
||||
const device = ranking.getByRole('link').first();
|
||||
const address = (await device.innerText()).trim();
|
||||
await device.click();
|
||||
await expect(page).toHaveURL(new RegExp(`#/connections\\?src=${escape(address)}$`));
|
||||
// The device reads as its address and is followed by its MAC address.
|
||||
await expect(page).toHaveURL(/#\/connections\?mac=[\da-f]{2}(?:%3A[\da-f]{2}){5}$/);
|
||||
await expect(page.getByRole('tab', {name: 'List', exact: true})).toHaveAttribute('aria-selected', 'true');
|
||||
await expect(list).toContainText(address);
|
||||
await page.goBack();
|
||||
|
||||
@@ -166,7 +166,7 @@ test('activating a checked source or rule removes that filter', async ({page}) =
|
||||
const source = page.getByRole('menuitemradio').first();
|
||||
const sourceName = await source.locator('.rp-il').innerText();
|
||||
await source.click();
|
||||
await expect(page).toHaveURL(new RegExp(`src=${encodeURIComponent(sourceName)}`));
|
||||
await expect(page).toHaveURL(/mac=/);
|
||||
await pick.click();
|
||||
const selectedSource = page.getByRole('menuitemradio').filter({hasText: sourceName});
|
||||
await expect(selectedSource).toHaveAttribute('aria-checked', 'true');
|
||||
|
||||
@@ -29,12 +29,12 @@ test.describe('390px', () => {
|
||||
await expect(page.getByRole('menuitem', {name: /^Network protocol/})).toContainText('TCP');
|
||||
await page.getByRole('menuitem', {name: /^Device/}).click();
|
||||
await page.getByRole('menuitemradio').nth(1).click();
|
||||
await expect(page).toHaveURL(/src=\d+\.\d+\.\d+\.\d+/);
|
||||
await expect(page).toHaveURL(/mac=/);
|
||||
await expect(page.getByRole('button', {name: 'Filters, 2 applied'})).toBeVisible();
|
||||
await page.getByRole('button', {name: 'Filters, 2 applied'}).click();
|
||||
await page.getByRole('menuitem', {name: /^Device/}).click();
|
||||
await page.getByRole('menuitemradio', {name: 'All devices'}).click();
|
||||
await expect(page).not.toHaveURL(/src=/);
|
||||
await expect(page).not.toHaveURL(/mac=/);
|
||||
await page.getByRole('button', {name: 'Clear filters'}).click();
|
||||
await expect(page.getByRole('button', {name: 'Filters', exact: true})).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -2,6 +2,17 @@ import type {Connection, ConnectionList, FlowDetail, DnsCacheList} from '../../s
|
||||
import {createFlow, flowFields, type ConnectionSeed} from '../flows';
|
||||
import {ago, ahead, observedAt, instanceId} from './clock';
|
||||
const AGES: Record<string, number> = {'1': 252, '2': 723, '3': 18, '4': 5, '5': 1, '6': 580, '7': 61, '8': 3};
|
||||
// Each device's MAC address, from the documentation range. 10.0.0.7 also connects over IPv6 under the same address, and
|
||||
// honk learns no MAC address for 10.0.0.12.
|
||||
const deviceMacs: Record<string, string> = {
|
||||
'10.0.0.7': '00:00:5e:00:53:07',
|
||||
'2001:db8::7': '00:00:5e:00:53:07',
|
||||
'10.0.0.20': '00:00:5e:00:53:20',
|
||||
'10.0.0.31': '00:00:5e:00:53:31',
|
||||
'10.0.0.42': '00:00:5e:00:53:42',
|
||||
'10.0.0.53': '00:00:5e:00:53:53',
|
||||
'10.0.0.64': '00:00:5e:00:53:64'
|
||||
};
|
||||
export const flows: FlowDetail[] = [];
|
||||
function connection(
|
||||
id: string,
|
||||
@@ -20,6 +31,7 @@ function connection(
|
||||
pname,
|
||||
state: outbound === 'block' ? 'blocked' : 'active',
|
||||
src,
|
||||
src_mac: deviceMacs[src] ?? null,
|
||||
dst,
|
||||
domain,
|
||||
outbound,
|
||||
@@ -132,7 +144,8 @@ const extra = demoDomains.map((domain, i) => {
|
||||
const id = String(i + 9);
|
||||
const outbound = i >= 15 && i <= 22 ? 'direct' : [6, 23, 31].includes(i) ? 'gaming' : i % 9 === 0 ? 'auto' : i % 4 === 0 ? 'direct' : 'proxy';
|
||||
const network = i % 6 === 0 ? 'udp' : 'tcp';
|
||||
const src = devices[i % devices.length];
|
||||
// One of 10.0.0.7's connections leaves over IPv6.
|
||||
const src = i === 6 ? '2001:db8::7' : devices[i % devices.length];
|
||||
const dst = `203.0.113.${10 + i}:443`;
|
||||
return {
|
||||
network,
|
||||
@@ -185,6 +198,7 @@ function retained(id: string, domain: string, outbound: string, network: 'tcp' |
|
||||
pname: null,
|
||||
state: outbound === 'block' ? 'blocked' : 'closed',
|
||||
src: '10.0.0.' + (10 + (Number(id.replace(/\D/g, '')) % 40)) + ':' + (40000 + Number(id.replace(/\D/g, ''))),
|
||||
src_mac: null,
|
||||
dst: '203.0.113.' + (Number(id.replace(/\D/g, '')) % 250) + ':443',
|
||||
domain,
|
||||
outbound,
|
||||
|
||||
+1
-1
@@ -67,7 +67,7 @@ export function createFlow(connection: ConnectionSeed, network: 'tcp' | 'udp', o
|
||||
domain_source: connection.domain ? 'dns_mapping' : null,
|
||||
pid: null,
|
||||
process_path: null,
|
||||
src_mac: null,
|
||||
src_mac: connection.src_mac ?? null,
|
||||
ingress: 'lan',
|
||||
domain_rule_ids: null,
|
||||
dscp: 0,
|
||||
|
||||
+18
-10
@@ -1,5 +1,5 @@
|
||||
import type {Api} from '../src/api/api';
|
||||
import type {Capabilities, DnsLogRecord, FlowDetail, RuleList, RuntimeOutbounds, RuntimeSettings} from '../src/api/model';
|
||||
import type {Capabilities, Connection, DnsLogRecord, FlowDetail, RuleList, RuntimeOutbounds, RuntimeSettings} from '../src/api/model';
|
||||
import {ApiError} from '../src/api/error';
|
||||
import {ipLiteral, sourceIp} from '../src/api/selectors';
|
||||
import * as fixtures from './fixtures/network';
|
||||
@@ -14,7 +14,8 @@ function buildDnsLog(flows: FlowDetail[], faults: boolean): DnsLogRecord[] {
|
||||
let seed = 941;
|
||||
const next = () => (seed = (seed * 48271) % 2147483647) / 2147483647;
|
||||
const domains = [...new Set(flows.map(flow => flow.input.domain).filter((name): name is string => !!name))];
|
||||
const sources = [...new Set([...fixtures.connections.tcp, ...fixtures.connections.udp].map(row => sourceIp(row.src)))];
|
||||
// Lookups come from the IPv4 clients, so one device also connecting over IPv6 leaves the DNS log as it was.
|
||||
const sources = [...new Set([...fixtures.connections.tcp, ...fixtures.connections.udp].map(row => sourceIp(row.src)))].filter(ip => !ip?.includes(':'));
|
||||
const blocked = ['ad.doubleclick.net', 'pagead2.googlesyndication.com', 'ads.tracker.example'];
|
||||
let age = 0;
|
||||
return Array.from({length: 480}, (_, i) => {
|
||||
@@ -57,6 +58,15 @@ function buildDnsLog(flows: FlowDetail[], faults: boolean): DnsLogRecord[] {
|
||||
};
|
||||
});
|
||||
}
|
||||
// The source filters of listing and closing connections: an IP literal and a MAC address, both applied when both are given.
|
||||
function sourceFilter(query: {src?: string; mac?: string} | undefined) {
|
||||
const src = query?.src === undefined ? undefined : ipLiteral(query.src);
|
||||
if (query?.src !== undefined && !src) throw new ApiError(400, 'invalid_request', 'Expected a source IP literal');
|
||||
const mac = query?.mac?.toLowerCase();
|
||||
if (mac !== undefined && !/^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/.test(mac)) throw new ApiError(400, 'invalid_request', 'Expected a MAC address');
|
||||
return {src, mac};
|
||||
}
|
||||
const matches = (c: Connection, src: string | undefined, mac: string | undefined) => (!src || sourceIp(c.src) === src) && (!mac || c.src_mac === mac);
|
||||
type NetworkApi = Pick<
|
||||
Api,
|
||||
| 'connections'
|
||||
@@ -151,10 +161,9 @@ export function createNetwork(
|
||||
if (!capabilities.resources.connections.available) throw new ApiError(404, 'capability_not_supported', 'Connections are unavailable');
|
||||
if (busy)
|
||||
for (const c of [...connections.tcp, ...connections.udp]) if (c.state === 'active') c.download_bytes = String(BigInt(c.download_bytes ?? '0') + 1460n);
|
||||
const src = query?.src === undefined ? undefined : ipLiteral(query.src);
|
||||
if (query?.src !== undefined && !src) throw new ApiError(400, 'invalid_request', 'Expected a source IP literal');
|
||||
const tcp = query?.type === 'udp' ? [] : connections.tcp.filter(c => !src || sourceIp(c.src) === src);
|
||||
const udp = query?.type === 'tcp' ? [] : connections.udp.filter(c => !src || sourceIp(c.src) === src);
|
||||
const {src, mac} = sourceFilter(query);
|
||||
const tcp = query?.type === 'udp' ? [] : connections.tcp.filter(c => matches(c, src, mac));
|
||||
const udp = query?.type === 'tcp' ? [] : connections.udp.filter(c => matches(c, src, mac));
|
||||
const limit = pageLimit(query?.limit);
|
||||
// A summary leaves out the endpoints and the domain, which only the full detail carries.
|
||||
const shown = <T extends object>(rows: T[]) =>
|
||||
@@ -306,12 +315,11 @@ export function createNetwork(
|
||||
closeConnections: async (query, signal) => {
|
||||
signal?.throwIfAborted();
|
||||
if (!capabilities.resources.connections.can_close) throw new ApiError(404, 'capability_not_supported', 'Closing connections is unavailable');
|
||||
const src = query?.src === undefined ? undefined : ipLiteral(query.src);
|
||||
if (query?.src !== undefined && !src) throw new ApiError(400, 'invalid_request', 'Expected a source IP literal');
|
||||
const {src, mac} = sourceFilter(query);
|
||||
const type = query?.type ?? 'all';
|
||||
if (type === 'all' && !src && !query?.all) throw new ApiError(400, 'invalid_request', 'An unfiltered close needs all=true');
|
||||
if (type === 'all' && !src && !mac && !query?.all) throw new ApiError(400, 'invalid_request', 'An unfiltered close needs all=true');
|
||||
const lists: Array<'tcp' | 'udp'> = type === 'tcp' ? ['tcp'] : type === 'udp' ? ['udp'] : ['tcp', 'udp'];
|
||||
const selected = lists.flatMap(network => connections[network].filter(c => !src || sourceIp(c.src) === src).map(c => ({network, c})));
|
||||
const selected = lists.flatMap(network => connections[network].filter(c => matches(c, src, mac)).map(c => ({network, c})));
|
||||
const max = capabilities.resources.connections.max_bulk_close ?? 1000;
|
||||
if (selected.length > max) throw new ApiError(413, 'request_too_large', `More than ${max} connections match`);
|
||||
let closed = 0;
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
eventSummary,
|
||||
logLevelLabels,
|
||||
logLevels,
|
||||
macLiteral,
|
||||
memoryTone,
|
||||
noNodeSources,
|
||||
nodeOwner,
|
||||
@@ -104,6 +105,10 @@ it('reads the port of an address, including a bracketed IPv6 one', () => {
|
||||
expect(addressPort('10.0.0.2')).toBeUndefined();
|
||||
expect(addressPort(undefined)).toBeUndefined();
|
||||
});
|
||||
it('reads a MAC address in each form the backend accepts and writes it in lower case with colons', () => {
|
||||
for (const text of ['00:00:5E:00:53:07', '00-00-5e-00-53-07', '0000.5e00.5307', '00005E005307']) expect(macLiteral(text)).toBe('00:00:5e:00:53:07');
|
||||
for (const text of ['', '00:00:5e-00:53:07', '00:00:5e:00:53', '0000.5e00.530g', '10.0.0.7']) expect(macLiteral(text)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('names every operation status, queued included, and shows an unknown one as sent', () => {
|
||||
const t = (key: Parameters<typeof translate>[1], params?: Parameters<typeof translate>[2]) => translate('en', key, params);
|
||||
|
||||
@@ -114,6 +114,17 @@ export function simulatedAddress(result: DnsQueryResponse['results'][number]): s
|
||||
return (result.answers ?? []).find(answer => answer.type === result.type)?.data ?? null;
|
||||
}
|
||||
|
||||
// A MAC address in any form honk's `mac` filter reads (colon, dash, dotted or bare hex, any case), written as honk
|
||||
// reports it: lower case with colons.
|
||||
export function macLiteral(text: string): string | undefined {
|
||||
const value = text.trim().toLowerCase();
|
||||
if (!/^(?:[\da-f]{2}([:-])[\da-f]{2}(?:\1[\da-f]{2}){4}|[\da-f]{4}\.[\da-f]{4}\.[\da-f]{4}|[\da-f]{12})$/.test(value)) return undefined;
|
||||
return value
|
||||
.replace(/[^\da-f]/g, '')
|
||||
.match(/../g)!
|
||||
.join(':');
|
||||
}
|
||||
|
||||
export function ipLiteral(text: string): string | undefined {
|
||||
const value = text.trim().replace(/^\[([^\]]+)\]$/, '$1');
|
||||
if (/^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/.test(value) && value.split('.').every(n => Number(n) <= 255)) return value;
|
||||
|
||||
@@ -32,6 +32,7 @@ it('keeps the keys browsers already hold', () => {
|
||||
'doona-policy-folds',
|
||||
'doona-alive-only',
|
||||
'doona-getting-started',
|
||||
'doona-device-aliases',
|
||||
'doona-session',
|
||||
'doona-saved',
|
||||
'doona-hub-pages'
|
||||
|
||||
@@ -34,6 +34,8 @@ export const storageKeys = {
|
||||
// Whether the node grids list only available nodes, for every group; see features/policies/aliveOnly.ts.
|
||||
aliveOnly: 'doona-alive-only',
|
||||
gettingStarted: 'doona-getting-started',
|
||||
// The names the reader gave devices by MAC address; see store/deviceAliases.ts.
|
||||
deviceAliases: 'doona-device-aliases',
|
||||
// The password session; see api/session.ts.
|
||||
session: 'doona-session',
|
||||
// sessionStorage
|
||||
|
||||
+22
-4
@@ -814,9 +814,10 @@ export interface paths {
|
||||
* resources.connections.can_close; unavailable closing returns 404
|
||||
* capability_not_supported.
|
||||
*
|
||||
* Combine type and exact source-IP src filters with AND. Missing type and
|
||||
* type=all do not restrict the set. Without type=tcp, type=udp, or src,
|
||||
* require all=true or return 400 invalid_request before closing anything.
|
||||
* Combine type, exact source-IP src and source-MAC mac filters with AND.
|
||||
* Missing type and type=all do not restrict the set. Without type=tcp,
|
||||
* type=udp, src, or mac, require all=true or return 400 invalid_request
|
||||
* before closing anything.
|
||||
* all=true does not override supplied filters. Reject limit and detail,
|
||||
* which apply only to listing.
|
||||
*
|
||||
@@ -2630,6 +2631,8 @@ export interface components {
|
||||
pname: string | null;
|
||||
state: components["schemas"]["ConnectionState"];
|
||||
src?: string;
|
||||
/** @description Source MAC address of the flow's first Ethernet frame in lower case, the router's own interface address for traffic the router sends; null when none was captured, such as on a non-Ethernet interface. */
|
||||
src_mac: string | null;
|
||||
dst?: string;
|
||||
domain?: string | null;
|
||||
outbound: string | null;
|
||||
@@ -3759,6 +3762,11 @@ export interface components {
|
||||
* @example 192.168.1.100
|
||||
*/
|
||||
1: components["schemas"]["IpAddress"];
|
||||
/**
|
||||
* @description Source MAC address, six colon-separated hex octets, matched case-insensitively; applied with type and src before limit. Totals and truncated describe only matching visible entries.
|
||||
* @example aa:bb:cc:dd:ee:ff
|
||||
*/
|
||||
2: string;
|
||||
/** @example full */
|
||||
Detail: "summary" | "full";
|
||||
/** @example 100 */
|
||||
@@ -5511,6 +5519,11 @@ export interface operations {
|
||||
* @example 192.168.1.100
|
||||
*/
|
||||
src?: components["schemas"]["IpAddress"];
|
||||
/**
|
||||
* @description Source MAC address, six colon-separated hex octets, matched case-insensitively; applied with type and src before limit. Totals and truncated describe only matching visible entries.
|
||||
* @example aa:bb:cc:dd:ee:ff
|
||||
*/
|
||||
mac?: string;
|
||||
/** @example 100 */
|
||||
limit?: components["parameters"]["Limit1000"];
|
||||
/** @example full */
|
||||
@@ -5549,7 +5562,12 @@ export interface operations {
|
||||
* @example 192.168.1.100
|
||||
*/
|
||||
src?: components["parameters"]["1"];
|
||||
/** @description Explicitly permit an unfiltered close; does not override type or src. */
|
||||
/**
|
||||
* @description Source MAC address, six colon-separated hex octets, matched case-insensitively; applied with type and src before limit. Totals and truncated describe only matching visible entries.
|
||||
* @example aa:bb:cc:dd:ee:ff
|
||||
*/
|
||||
mac?: components["parameters"]["2"];
|
||||
/** @description Explicitly permit an unfiltered close; does not override type, src, or mac. */
|
||||
all?: boolean;
|
||||
};
|
||||
header?: never;
|
||||
|
||||
@@ -44,7 +44,7 @@ export function RankingCard({model}: {model: ReturnType<typeof useRankingCard>})
|
||||
<div className="rp-list rp-columns" style={columns(rows.length)}>
|
||||
{rows.map(row => (
|
||||
<Bar
|
||||
key={row.name}
|
||||
key={row.id}
|
||||
label={
|
||||
<Link appearance="link" href={row.href}>
|
||||
{row.name}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {expect, it} from 'vitest';
|
||||
import {createMockApi} from '../../../mock';
|
||||
import {connectionRanking} from '../shared/ranking';
|
||||
import {connectionRanking, deviceNames} from '../shared/ranking';
|
||||
|
||||
it('groups both transports by source IP or domain, falling back to the destination', async () => {
|
||||
const snapshot = await createMockApi().connections();
|
||||
@@ -11,12 +11,12 @@ it('groups both transports by source IP or domain, falling back to the destinati
|
||||
];
|
||||
snapshot.udp = [{...row, src: '[2001:db8::1]:53', domain: 'a.example', download_bytes: '50'}];
|
||||
expect(connectionRanking(snapshot, 'dev')).toEqual([
|
||||
{name: '2001:db8::1', download: 150n, percent: 75},
|
||||
{name: '10.0.0.1', download: 50n, percent: 25}
|
||||
{name: '2001:db8::1', label: '2001:db8::1', mac: false, download: 150n, percent: 75},
|
||||
{name: '10.0.0.1', label: '10.0.0.1', mac: false, download: 50n, percent: 25}
|
||||
]);
|
||||
expect(connectionRanking(snapshot, 'host')).toEqual([
|
||||
{name: 'a.example', download: 150n, percent: 75},
|
||||
{name: '192.0.2.1:443', download: 50n, percent: 25}
|
||||
{name: 'a.example', label: 'a.example', mac: false, download: 150n, percent: 75},
|
||||
{name: '192.0.2.1:443', label: '192.0.2.1:443', mac: false, download: 50n, percent: 25}
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -25,7 +25,9 @@ it('uses all groups for percentages before taking the top five and keeps exact l
|
||||
const row = snapshot.tcp[0];
|
||||
snapshot.tcp = Array.from({length: 6}, (_, i) => ({...row, domain: String(i), download_bytes: '18446744073709551615'}));
|
||||
snapshot.udp = [{...row, domain: '', dst: '', download_bytes: null}];
|
||||
expect(connectionRanking(snapshot, 'host')).toEqual(Array.from({length: 5}, (_, i) => ({name: String(i), download: 18446744073709551615n, percent: 16.67})));
|
||||
expect(connectionRanking(snapshot, 'host')).toEqual(
|
||||
Array.from({length: 5}, (_, i) => ({name: String(i), label: String(i), mac: false, download: 18446744073709551615n, percent: 16.67}))
|
||||
);
|
||||
});
|
||||
|
||||
it('sorts unknown aggregates last and leaves every share unknown when any group is unknown', async () => {
|
||||
@@ -37,11 +39,28 @@ it('sorts unknown aggregates last and leaves every share unknown when any group
|
||||
];
|
||||
snapshot.udp = [{...row, domain: 'unknown', download_bytes: null}];
|
||||
expect(connectionRanking(snapshot, 'host')).toEqual([
|
||||
{name: 'known', download: 20n, percent: null},
|
||||
{name: 'unknown', download: null, percent: null}
|
||||
{name: 'known', label: 'known', mac: false, download: 20n, percent: null},
|
||||
{name: 'unknown', label: 'unknown', mac: false, download: null, percent: null}
|
||||
]);
|
||||
snapshot.tcp = [{...row, domain: 'zero', download_bytes: '0'}];
|
||||
snapshot.udp = [];
|
||||
expect(connectionRanking(snapshot, 'host')).toEqual([{name: 'zero', download: 0n, percent: 0}]);
|
||||
expect(connectionRanking(snapshot, 'host')).toEqual([{name: 'zero', label: 'zero', mac: false, download: 0n, percent: 0}]);
|
||||
expect(connectionRanking(undefined, 'dev')).toEqual([]);
|
||||
});
|
||||
|
||||
it('labels an unnamed device known by its MAC address with its latest IPv4 address, else its first address', () => {
|
||||
const at = (src: string, src_mac: string, started_at: string) => ({src, src_mac, started_at});
|
||||
const rows = [
|
||||
at('[2001:db8::7]:80', '00:00:5e:00:53:07', '2026-01-01T00:00:03Z'),
|
||||
at('10.0.0.7:80', '00:00:5e:00:53:07', '2026-01-01T00:00:02Z'),
|
||||
at('10.0.0.8:80', '00:00:5e:00:53:07', '2026-01-01T00:00:01Z'),
|
||||
at('[2001:db8::9]:80', '00:00:5e:00:53:09', '2026-01-01T00:00:01Z'),
|
||||
at('[2001:db8::10]:80', '00:00:5e:00:53:09', '2026-01-01T00:00:02Z'),
|
||||
at('10.0.0.11:80', '00:00:5e:00:53:11', '2026-01-01T00:00:01Z')
|
||||
];
|
||||
expect(deviceNames(rows, {'00:00:5e:00:53:11': 'Printer'})).toEqual({
|
||||
'00:00:5e:00:53:07': '10.0.0.7',
|
||||
'00:00:5e:00:53:09': '2001:db8::9',
|
||||
'00:00:5e:00:53:11': 'Printer'
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import {useMemo, useState} from 'react';
|
||||
import {poll, useCapabilities, useConnections} from '../../store';
|
||||
import {poll, useCapabilities, useConnections, useDeviceAliases} from '../../store';
|
||||
import {LOCALE, useLang, useT} from '../../i18n';
|
||||
import {usePalette} from '../../ui/charts';
|
||||
import {useNearViewport} from '../../ui/ui';
|
||||
@@ -19,7 +19,8 @@ export function useRankingCard(enabled = true, selection?: {by: string; setBy: (
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const connections = useConnections(undefined, enabled && available === true, !near && loaded, poll.summary);
|
||||
if (connections.data && !loaded) setLoaded(true);
|
||||
const rows = useMemo(() => activityRanking(connections.data, by, p, locale, t, limit), [connections.data, by, p, locale, t, limit]);
|
||||
const aliases = useDeviceAliases();
|
||||
const rows = useMemo(() => activityRanking(connections.data, by, p, locale, t, limit, aliases), [connections.data, by, p, locale, t, limit, aliases]);
|
||||
const state = connections.data ? (rows.length ? 'ready' : 'empty') : connections.error ? 'error' : available === true ? 'loading' : 'unavailable';
|
||||
return {
|
||||
ref,
|
||||
|
||||
@@ -30,7 +30,8 @@ it('distinguishes missing metrics from zero and keeps block traffic separate fro
|
||||
expect(activityOutbounds(runtimeOutbounds, 'en-US', colors, t).rows.find(row => row.name === t('ui.block'))?.color).toBe('red');
|
||||
const ranking = activityRanking(connections, 'dev', colors, 'en', t);
|
||||
expect(ranking[0].pct).toBeGreaterThan(ranking[1].pct);
|
||||
expect(ranking[0].href).toBe(`#/connections?src=${ranking[0].name}`);
|
||||
// The busiest device is known by its MAC address and links to its connections by it.
|
||||
expect(ranking[0].href).toBe(`#/connections?mac=${encodeURIComponent(ranking[0].id)}`);
|
||||
const domains = activityRanking(connections, 'host', colors, 'en', t);
|
||||
expect(domains[0].href).toBe(`#/connections?q=${encodeURIComponent(domains[0].name)}`);
|
||||
const only = activityRanking({...connections, tcp: connections.tcp.slice(0, 1), udp: []}, 'host', colors, 'en', t);
|
||||
|
||||
@@ -167,13 +167,22 @@ export function activityOutbounds(outbounds: RuntimeOutbounds | undefined, local
|
||||
};
|
||||
}
|
||||
|
||||
export function activityRanking(connections: ConnectionList | undefined, by: string, colors: {cat: string[]}, locale: string, t: LabelFn, limit = 5) {
|
||||
return connectionRanking(connections, by, limit).map((row, i) => ({
|
||||
name: row.name,
|
||||
export function activityRanking(
|
||||
connections: ConnectionList | undefined,
|
||||
by: string,
|
||||
colors: {cat: string[]},
|
||||
locale: string,
|
||||
t: LabelFn,
|
||||
limit = 5,
|
||||
aliases: Readonly<Record<string, string>> = {}
|
||||
) {
|
||||
return connectionRanking(connections, by, limit, aliases).map((row, i) => ({
|
||||
id: row.name,
|
||||
name: row.label,
|
||||
value: formatBytes(row.download, locale),
|
||||
share: row.percent === null ? undefined : t('ui.percent', {n: row.percent}),
|
||||
pct: row.percent ?? 0,
|
||||
color: colors.cat[i % colors.cat.length],
|
||||
href: href('connections', by === 'dev' ? {src: row.name} : {q: row.name})
|
||||
href: href('connections', by !== 'dev' ? {q: row.name} : row.mac ? {mac: row.name} : {src: row.name})
|
||||
}));
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
import {IpLookup} from '../../ui/IpLookup';
|
||||
import {Link} from '../../ui/Link';
|
||||
import {ipLookupSites} from '../shared/ipLookup';
|
||||
import {OutboundTag} from '../shared/OutboundTag';
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
ConfirmButton,
|
||||
ConfirmDialog,
|
||||
Form,
|
||||
HelpRow,
|
||||
DetailPanel,
|
||||
Kv,
|
||||
@@ -31,11 +34,12 @@ import {useT} from '../../i18n';
|
||||
import {useConnectionsPage} from './useConnectionsPage';
|
||||
import {connectionsTabs} from './nav';
|
||||
import type {ConnectionView} from './viewState';
|
||||
import type {ReactNode} from 'react';
|
||||
import {useId, type ReactNode} from 'react';
|
||||
|
||||
export function Connections(props: PageProps) {
|
||||
const t = useT();
|
||||
const vm = useConnectionsPage(props);
|
||||
const nameFormId = useId();
|
||||
const cur = vm.detail;
|
||||
const list = (
|
||||
<>
|
||||
@@ -131,7 +135,7 @@ export function Connections(props: PageProps) {
|
||||
...(vm.ruleAction.canEdit ? [{id: 'edit-rule', label: t('conn.editRule'), onAction: () => vm.showRule(true)}] : []),
|
||||
...(vm.canViewFlow ? [{id: 'view-flow', label: t('conn.viewFlow'), onAction: vm.showFlow}] : []),
|
||||
...(vm.canTrace ? [{id: 'trace', label: t('conn.trace'), onAction: vm.traceConnection}] : []),
|
||||
...(cur.source ? [{id: 'only-client', label: t('conn.onlyThisClient'), onAction: vm.onlyClient}] : []),
|
||||
...(cur.source || cur.mac ? [{id: 'only-client', label: t('conn.onlyThisClient'), onAction: vm.onlyClient}] : []),
|
||||
...(vm.canClose && cur.closable
|
||||
? [
|
||||
{
|
||||
@@ -174,7 +178,15 @@ export function Connections(props: PageProps) {
|
||||
title={t('conn.section.connection')}
|
||||
items={cur.sections.connection.map(([label, value]) => [
|
||||
label,
|
||||
typeof value === 'string' ? value : <IpLookup ip={value.ip} address={value.address} sites={ipLookupSites(value.ip)} />
|
||||
typeof value === 'string' ? (
|
||||
value
|
||||
) : 'mac' in value ? (
|
||||
<Link appearance="link" layout="inline" tip={t('conn.nameDevice')} onPress={vm.naming.open}>
|
||||
{cur.macText}
|
||||
</Link>
|
||||
) : (
|
||||
<IpLookup ip={value.ip} address={value.address} sites={ipLookupSites(value.ip)} />
|
||||
)
|
||||
])}
|
||||
/>
|
||||
{cur.sections.traffic.length > 0 && (
|
||||
@@ -201,6 +213,31 @@ export function Connections(props: PageProps) {
|
||||
</div>
|
||||
{vm.notInSnapshot && <span className="rp-label">{t('conn.notInSnapshot')}</span>}
|
||||
<RuleDialog dialog={vm.ruleAction.dialog} />
|
||||
<ConfirmDialog
|
||||
title={t('conn.nameDevice')}
|
||||
isOpen={vm.naming.isOpen}
|
||||
onCancel={vm.naming.cancel}
|
||||
tone="accent"
|
||||
confirmLabel={t('settings.save')}
|
||||
form={nameFormId}
|
||||
>
|
||||
<Form
|
||||
id={nameFormId}
|
||||
className="rp-contents"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
vm.naming.save();
|
||||
}}
|
||||
>
|
||||
<TextField
|
||||
label={t('conn.deviceName')}
|
||||
value={vm.naming.name}
|
||||
onChange={vm.naming.setName}
|
||||
placeholder={vm.naming.mac}
|
||||
description={t('conn.deviceNameHelp')}
|
||||
/>
|
||||
</Form>
|
||||
</ConfirmDialog>
|
||||
</>
|
||||
);
|
||||
const content = {
|
||||
|
||||
@@ -4,7 +4,8 @@ import {tagId} from '../shared/taggedId';
|
||||
import {ranked} from '../shared/ranked';
|
||||
import {enumLabel} from '../../i18n/enum';
|
||||
import {addU64, parseU64} from '../../api/u64';
|
||||
import {chainPath, connectionStates, nodeLabel, outboundLabel, sourceIp, type OutboundNames} from '../../api/selectors';
|
||||
import {chainPath, connectionStates, nodeLabel, outboundLabel, type OutboundNames} from '../../api/selectors';
|
||||
import {deviceKey} from '../shared/ranking';
|
||||
import {compareNames, formatBytes, formatRate} from '../../i18n/format';
|
||||
import {formatNumber, type Translator as LabelFn} from '../../i18n';
|
||||
import {ruleHref} from '../shared/link';
|
||||
@@ -95,7 +96,8 @@ export function connectionTableView(
|
||||
locale: string,
|
||||
names: OutboundNames,
|
||||
rulesListed: boolean,
|
||||
t: LabelFn
|
||||
t: LabelFn,
|
||||
devices: Readonly<Record<string, string>> = {}
|
||||
): ConnectionTableRow[] {
|
||||
const project = (c: Connection): ConnectionRowView => {
|
||||
const hit = projected.get(c);
|
||||
@@ -125,7 +127,7 @@ export function connectionTableView(
|
||||
id: row.id,
|
||||
group: row.group,
|
||||
children: row.children.map(project),
|
||||
label: t('conn.groupCount', {name: groupName(row.group, view.group as Exclude<ConnectionView['group'], 'none'>, t), n: row.children.length}),
|
||||
label: t('conn.groupCount', {name: groupName(row.group, view.group as Exclude<ConnectionView['group'], 'none'>, t, devices), n: row.children.length}),
|
||||
totals: {down: formatBytes(row.download, locale), state: t('conn.activeCount', {n: row.active})}
|
||||
}
|
||||
);
|
||||
@@ -140,7 +142,9 @@ export function connectionsView(
|
||||
rule: string,
|
||||
out: string,
|
||||
locale: string,
|
||||
t: LabelFn
|
||||
t: LabelFn,
|
||||
mac?: string,
|
||||
devices: Readonly<Record<string, string>> = {}
|
||||
) {
|
||||
// A link can filter by an outbound no open connection uses, such as one from the usage totals; it stays listed so the
|
||||
// picker still shows it.
|
||||
@@ -152,6 +156,8 @@ export function connectionsView(
|
||||
const present = values.flatMap(value => (value ? [value] : []));
|
||||
return ranked(present, Infinity).top;
|
||||
};
|
||||
// A device known by its MAC address filters by it and reads as its name or address (deviceNames).
|
||||
const macs = new Set(rows.flatMap(c => (c.src_mac ? [c.src_mac] : [])));
|
||||
const outboundItems = [{id: 'all', label: t('conn.allOutbounds')}, ...[...outbounds].map(id => ({id, label: outboundLabel(id, t)}))];
|
||||
return {
|
||||
networks: [
|
||||
@@ -165,8 +171,12 @@ export function connectionsView(
|
||||
picks: [
|
||||
{
|
||||
title: t('ui.device'),
|
||||
value: tagId('src', src ?? ''),
|
||||
items: seen(rows.map(c => sourceIp(c.src))).map(({key: ip, count}) => ({id: tagId('src', ip), label: ip, desc: formatNumber(count, locale)}))
|
||||
value: mac ? tagId('mac', mac) : tagId('src', src ?? ''),
|
||||
items: seen(rows.map(deviceKey)).map(({key, count}) =>
|
||||
macs.has(key)
|
||||
? {id: tagId('mac', key), label: devices[key] || key, desc: formatNumber(count, locale)}
|
||||
: {id: tagId('src', key), label: key, desc: formatNumber(count, locale)}
|
||||
)
|
||||
},
|
||||
{
|
||||
title: t('ui.rule'),
|
||||
|
||||
@@ -1,10 +1,21 @@
|
||||
import {useCallback, useDeferredValue, useEffect, useMemo, useRef, useState} from 'react';
|
||||
import {readTag} from '../shared/taggedId';
|
||||
import {useCapabilities, useConnectionClose, useConnections, useFlowDemand, useGroups, useNodes, useOutboundNames, useRuntime} from '../../store';
|
||||
import {
|
||||
useCapabilities,
|
||||
useConnectionClose,
|
||||
useConnections,
|
||||
useDeviceAliases,
|
||||
saveDeviceAlias,
|
||||
useFlowDemand,
|
||||
useGroups,
|
||||
useNodes,
|
||||
useOutboundNames,
|
||||
useRuntime
|
||||
} from '../../store';
|
||||
import {kernelTrafficUncounted} from '../shared/traffic';
|
||||
import {outboundTag} from '../shared/link';
|
||||
import {ApiError, errorText} from '../../api/error';
|
||||
import {chainNames, closedAllTone, connectionRows, ipLiteral, nodeSubscription, outboundLabel, type OutboundNames} from '../../api/selectors';
|
||||
import {chainNames, closedAllTone, connectionRows, ipLiteral, macLiteral, nodeSubscription, outboundLabel, type OutboundNames} from '../../api/selectors';
|
||||
import {downloadFile, exportName, panelQuery, phoneQuery, toast, toastErrorDetail, useLinked, useMediaQuery, useWhileShown} from '../../ui/ui';
|
||||
import {pickTab, tabQuery, within} from '../../shell/route';
|
||||
import {useT, useLang, LOCALE} from '../../i18n';
|
||||
@@ -15,6 +26,7 @@ import {closeSelection, connectionsExport, connectionDetail, filterMenu, type Cl
|
||||
import {connectionsView, connectionTableView} from './tableRows';
|
||||
import {offered} from '../../api/capabilities';
|
||||
import {pathLatency} from './latency';
|
||||
import {deviceNames} from '../shared/ranking';
|
||||
import {useConnectionRule} from './useConnectionRule';
|
||||
import {connectionsTabs} from './nav';
|
||||
|
||||
@@ -22,7 +34,7 @@ const connectionTabs = connectionsTabs().map(tab => tab.id);
|
||||
// The traffic chart comes first; a link into the table (a connection, a source, a filter) opens the table.
|
||||
const connectionsFallback = (query: string) => {
|
||||
const params = new URLSearchParams(query);
|
||||
return ['id', 'src', 'network', 'out', 'rule', 'q'].some(key => params.has(key)) ? 'list' : 'traffic';
|
||||
return ['id', 'src', 'mac', 'network', 'out', 'rule', 'q'].some(key => params.has(key)) ? 'list' : 'traffic';
|
||||
};
|
||||
// While the link decides the tab, a change within the page writes it, so clearing the filter or selection that opened
|
||||
// the table keeps the table.
|
||||
@@ -73,8 +85,13 @@ export function useConnectionsPage({go, query}: PageProps) {
|
||||
const select = (id: string | null) => go('connections', stay(latest.current, {id}));
|
||||
// Filtering follows typing at React's pace, not a fixed delay, so an export or close right after typing sees it.
|
||||
const settledText = useDeferredValue(text);
|
||||
const src = ipLiteral(q.get('src') ?? '');
|
||||
const resource = useConnections(src);
|
||||
// A MAC address in any form the backend reads, written as it reports them. One it cannot read is still sent, so its
|
||||
// refusal shows instead of every device. A MAC address names the whole device, so it replaces any source address.
|
||||
const macQuery = q.get('mac') || undefined;
|
||||
const mac = macQuery && (macLiteral(macQuery) ?? macQuery);
|
||||
const src = mac ? undefined : ipLiteral(q.get('src') ?? '');
|
||||
const resource = useConnections({src, mac});
|
||||
const aliases = useDeviceAliases();
|
||||
const capabilities = useCapabilities();
|
||||
const canClose = capabilities.data?.resources.connections.can_close === true;
|
||||
const rulesListed = offered(capabilities.data?.resources, 'rules', {whileLoading: false});
|
||||
@@ -109,6 +126,7 @@ export function useConnectionsPage({go, query}: PageProps) {
|
||||
() => [...new Set(trafficRows.map(row => row.outbound))].sort((a, b) => compareNames(locale)(a ?? '', b ?? '')),
|
||||
[trafficRows, locale]
|
||||
);
|
||||
const devices = useMemo(() => deviceNames(rows, aliases), [rows, aliases]);
|
||||
const needle = settledText.trim().toLowerCase();
|
||||
const shown = useMemo(
|
||||
() =>
|
||||
@@ -122,6 +140,8 @@ export function useConnectionsPage({go, query}: PageProps) {
|
||||
c.dst,
|
||||
c.domain,
|
||||
c.src,
|
||||
c.src_mac,
|
||||
c.src_mac && aliases[c.src_mac],
|
||||
c.pname,
|
||||
outboundLabel(c.outbound, t),
|
||||
chainNames(c.chain, names).join(' '),
|
||||
@@ -132,7 +152,7 @@ export function useConnectionsPage({go, query}: PageProps) {
|
||||
.toLowerCase()
|
||||
.includes(needle))
|
||||
),
|
||||
[rows, network, out, rule, needle, names, subscriptions, t]
|
||||
[rows, network, out, rule, needle, names, subscriptions, t, aliases]
|
||||
);
|
||||
const cur = sel ? rows.find(c => c.id === sel) : undefined;
|
||||
// A connection opened by its id shows its row: its group unfolds once, when the id arrives or the connection moves
|
||||
@@ -145,14 +165,26 @@ export function useConnectionsPage({go, query}: PageProps) {
|
||||
setCollapse(expandGroup(collapse, target.group));
|
||||
}
|
||||
const ruleAction = useConnectionRule(cur, go);
|
||||
const lists = useMemo(() => connectionsView(rows, listData, src, rule, out, locale, t), [rows, listData, src, rule, out, locale, t]);
|
||||
const lists = useMemo(
|
||||
() => connectionsView(rows, listData, src, rule, out, locale, t, mac, devices),
|
||||
[rows, listData, src, rule, out, locale, t, mac, devices]
|
||||
);
|
||||
const groups = useGroups(offered(capabilities.data?.resources, 'groups', {whileLoading: false})).data;
|
||||
const detail = useMemo(() => {
|
||||
const base = connectionDetail(cur, locale, t, names, rulesListed, subscriptions);
|
||||
return base && {...base, outboundTag: outboundTag(base.outbound, groups, t)};
|
||||
}, [cur, locale, t, names, rulesListed, subscriptions, groups]);
|
||||
if (!base) return base;
|
||||
const {mac} = base;
|
||||
const alias = (mac && aliases[mac]) || null;
|
||||
// The MAC row reads the name the reader gave the device, with the address beside it.
|
||||
return {...base, outboundTag: outboundTag(base.outbound, groups, t), alias, macText: mac && alias ? t('ui.aside', {text: alias, note: mac}) : mac};
|
||||
}, [cur, locale, t, names, rulesListed, subscriptions, groups, aliases]);
|
||||
const model = {...lists, detail};
|
||||
const collection = useMemo(() => connectionTableView(shown, view, locale, names, rulesListed, t), [shown, view, locale, names, rulesListed, t]);
|
||||
const collection = useMemo(
|
||||
() => connectionTableView(shown, view, locale, names, rulesListed, t, devices),
|
||||
[shown, view, locale, names, rulesListed, t, devices]
|
||||
);
|
||||
// The device the detail panel is naming, by its MAC address, and the name being typed.
|
||||
const [naming, setNaming] = useState<{mac: string; name: string} | null>(null);
|
||||
const close = async () => {
|
||||
if (!model.detail) return;
|
||||
const {id} = model.detail;
|
||||
@@ -177,15 +209,17 @@ export function useConnectionsPage({go, query}: PageProps) {
|
||||
return t('ui.valuePair', {label: t('conn.closeFailed'), value: errorText(error, t)});
|
||||
}
|
||||
};
|
||||
// Picking the chosen device or rule again lifts it, as does an empty value (the menu's "all" entry).
|
||||
// Picking the chosen device or rule again lifts it, as does an empty value (the menu's "all" entry). A device is
|
||||
// picked by its address or by its MAC address, never both.
|
||||
const pick = (key: string | number) => {
|
||||
const picked = readTag(String(key), ['src', 'rule'] as const);
|
||||
if (picked?.kind === 'src') {
|
||||
const picked = readTag(String(key), ['src', 'mac', 'rule'] as const);
|
||||
if (picked?.kind === 'src' || picked?.kind === 'mac') {
|
||||
const chosen = picked.kind === 'src' ? src : mac;
|
||||
setText('');
|
||||
go('connections', stay(query, {src: !picked.value || src === picked.value ? null : picked.value, q: null}));
|
||||
go('connections', stay(query, {src: null, mac: null, [picked.kind]: !picked.value || chosen === picked.value ? null : picked.value, q: null}));
|
||||
} else if (picked?.kind === 'rule') setFilter('rule', rule === picked.value ? 'all' : picked.value);
|
||||
};
|
||||
const menu = filterMenu(lists, {network, out, src, rule}, t);
|
||||
const menu = filterMenu(lists, {network, out, src, mac, rule}, t);
|
||||
const pickFor = {network: (value: string) => setFilter('network', value), out: (value: string) => setFilter('out', value), src: pick, rule: pick};
|
||||
const compactMenu = {
|
||||
active: menu.active,
|
||||
@@ -233,10 +267,10 @@ export function useConnectionsPage({go, query}: PageProps) {
|
||||
const hidden = view.hidden.includes(id) ? view.hidden.filter(value => value !== id) : [...view.hidden, id];
|
||||
if (hidden.length < columns.length) updateView({hidden});
|
||||
},
|
||||
filtered: network !== 'all' || out !== 'all' || rule !== 'all' || !!src || text.trim() !== '',
|
||||
filtered: network !== 'all' || out !== 'all' || rule !== 'all' || !!src || !!mac || text.trim() !== '',
|
||||
clear: () => {
|
||||
setText('');
|
||||
go('connections', stay(query, {network: null, out: null, rule: null, q: null, src: null}));
|
||||
go('connections', stay(query, {network: null, out: null, rule: null, q: null, src: null, mac: null}));
|
||||
},
|
||||
error: resource.error,
|
||||
retry: resource.refetch,
|
||||
@@ -246,20 +280,21 @@ export function useConnectionsPage({go, query}: PageProps) {
|
||||
canViewFlow,
|
||||
closeAll: {
|
||||
confirmationText: confirmed?.query
|
||||
? t(
|
||||
confirmed.query.type === 'all' ? 'conn.closeAllLive' : confirmed.query.type === 'tcp' ? 'conn.closeAllLiveTcp' : 'conn.closeAllLiveUdp',
|
||||
src ? {n: confirmed.count ?? confirmed.ids.length, source: src} : {n: confirmed.count ?? confirmed.ids.length, source: t('conn.anySource')}
|
||||
)
|
||||
? t(confirmed.query.type === 'all' ? 'conn.closeAllLive' : confirmed.query.type === 'tcp' ? 'conn.closeAllLiveTcp' : 'conn.closeAllLiveUdp', {
|
||||
n: confirmed.count ?? confirmed.ids.length,
|
||||
source: (mac && (aliases[mac] || mac)) || src || t('conn.anySource')
|
||||
})
|
||||
: t('conn.closeAllHelp', {n: confirmed?.ids.length ?? 0}),
|
||||
open: !!confirmed,
|
||||
setOpen: (open: boolean) =>
|
||||
setConfirmed(
|
||||
open
|
||||
? q.get('scope') === 'all' && network === 'all' && !src && out === 'all' && rule === 'all' && !needle
|
||||
? q.get('scope') === 'all' && network === 'all' && !src && !mac && out === 'all' && rule === 'all' && !needle
|
||||
? {ids: [], query: {type: 'all', all: true}, count: (resource.data?.total_tcp ?? 0) + (resource.data?.total_udp ?? 0)}
|
||||
: closeSelection(shown, {
|
||||
network,
|
||||
src,
|
||||
mac,
|
||||
narrowed: out !== 'all' || rule !== 'all' || !!needle,
|
||||
truncated: !!resource.data?.truncated,
|
||||
bulkLimit: capabilities.data?.resources.connections.max_bulk_close
|
||||
@@ -284,10 +319,23 @@ export function useConnectionsPage({go, query}: PageProps) {
|
||||
showFlow: () => {
|
||||
if (model.detail && canViewFlow) go('flows', model.detail.flowQuery);
|
||||
},
|
||||
// A device known by its MAC address is followed by it, so its IPv4 and IPv6 connections stay together.
|
||||
onlyClient: () => {
|
||||
if (model.detail?.source) {
|
||||
if (model.detail?.mac || model.detail?.source) {
|
||||
setText('');
|
||||
go('connections', stay(query, {src: model.detail.source, q: null}));
|
||||
go('connections', stay(query, model.detail.mac ? {src: null, mac: model.detail.mac, q: null} : {src: model.detail.source, mac: null, q: null}));
|
||||
}
|
||||
},
|
||||
naming: {
|
||||
open: () => model.detail?.mac && setNaming({mac: model.detail.mac, name: model.detail.alias ?? ''}),
|
||||
mac: naming?.mac ?? '',
|
||||
name: naming?.name ?? '',
|
||||
setName: (name: string) => setNaming(current => current && {...current, name}),
|
||||
isOpen: !!naming,
|
||||
cancel: () => setNaming(null),
|
||||
save: () => {
|
||||
if (naming) saveDeviceAlias(naming.mac, naming.name);
|
||||
setNaming(null);
|
||||
}
|
||||
},
|
||||
canExport: shown.length > 0,
|
||||
|
||||
@@ -20,6 +20,8 @@ const chainSources: Partial<Record<Connection['chain_source'], Key>> = {
|
||||
reconstructed: 'conn.chainSource.reconstructed'
|
||||
};
|
||||
type Destination = {ip: string; address: string};
|
||||
// The source's MAC address, which the panel lets the reader name.
|
||||
type DeviceMac = {mac: string};
|
||||
// A byte count and, while the connection moves data, its rate.
|
||||
type Amount = {total: string; rate: string | null};
|
||||
type Field<T> = [Key, T | null];
|
||||
@@ -35,10 +37,11 @@ export function connectionDetails(c: Connection, locale: string) {
|
||||
// A backend that predates chain_source leaves it out, and the row with it.
|
||||
const chainSource = known(c.chain_source);
|
||||
return {
|
||||
connection: present<string | MessageRef | Destination>([
|
||||
connection: present<string | MessageRef | Destination | DeviceMac>([
|
||||
['ui.domain', c.domain || null],
|
||||
['conn.f.dst', c.dst ? (ip && isPublicIp(ip) ? {ip, address: c.dst} : c.dst) : null],
|
||||
['ui.device', c.src || null],
|
||||
['conn.f.mac', c.src_mac ? {mac: c.src_mac} : null],
|
||||
['ui.process', c.pname || null],
|
||||
['conn.f.ingress', c.ingress ? word(c.ingress) : null],
|
||||
['conn.f.started', c.started_at ? localTime(c.started_at, locale) : null]
|
||||
@@ -59,7 +62,7 @@ export function connectionDetails(c: Connection, locale: string) {
|
||||
// choices, and each with an entry that lifts it. The count of filters in force labels the menu's button.
|
||||
export function filterMenu(
|
||||
lists: ReturnType<typeof connectionsView>,
|
||||
filters: {network: string; out: string; src: string | undefined; rule: string},
|
||||
filters: {network: string; out: string; src: string | undefined; mac?: string; rule: string},
|
||||
t: LabelFn
|
||||
) {
|
||||
const [devices, rules] = lists.picks;
|
||||
@@ -77,7 +80,7 @@ export function filterMenu(
|
||||
searchLabel
|
||||
});
|
||||
return {
|
||||
active: [filters.network !== 'all', filters.out !== 'all', !!filters.src, filters.rule !== 'all'].filter(Boolean).length,
|
||||
active: [filters.network !== 'all', filters.out !== 'all', !!filters.src || !!filters.mac, filters.rule !== 'all'].filter(Boolean).length,
|
||||
submenus: [
|
||||
one(
|
||||
'network',
|
||||
@@ -128,7 +131,11 @@ export function connectionDetail(
|
||||
rule: current.rule_expression ? {expression: current.rule_expression, href: ruleHref(current.rule_id, rulesListed)} : null,
|
||||
sections: {
|
||||
connection: sections.connection.map(
|
||||
([key, value]) => [t(key), typeof value === 'string' || 'ip' in value ? value : t(value.key, value.params)] as [string, string | Destination]
|
||||
([key, value]) =>
|
||||
[t(key), typeof value === 'string' || 'ip' in value || 'mac' in value ? value : t(value.key, value.params)] as [
|
||||
string,
|
||||
string | Destination | DeviceMac
|
||||
]
|
||||
),
|
||||
traffic: sections.traffic.map(([key, value]) => [t(key), value] as [string, Amount]),
|
||||
provenance: sections.provenance.map(([key, value]) => [t(key), typeof value === 'string' ? value : t(value.key, value.params)] as [string, string])
|
||||
@@ -149,6 +156,7 @@ export function connectionDetail(
|
||||
})
|
||||
: null,
|
||||
source: current.src ? (sourceIp(current.src) ?? current.src) : null,
|
||||
mac: current.src_mac ?? null,
|
||||
closable: current.state === 'active' || current.state === 'dialing' || current.state === 'routing',
|
||||
// An ebpf-only observation is kernel-forwarded: the backend has no userspace transport to cancel.
|
||||
closeReason: current.observed_by === 'ebpf' ? t('conn.notClosable') : null,
|
||||
@@ -181,15 +189,17 @@ export function connectionsExport(shown: Array<Connection & {network: string}>,
|
||||
);
|
||||
}
|
||||
|
||||
// The contract's bulk close selects every live connection of a network and source; anything narrower (an
|
||||
// The contract's bulk close selects every live connection of a network, source address and MAC; anything narrower (an
|
||||
// outbound, rule or text filter, or a truncated list) closes the listed ids one by one. The ids travel with the
|
||||
// bulk query so a 413 from the advertised limit can fall back to them without widening the confirmed scope.
|
||||
export type CloseSelection = {ids: string[]; query?: NonNullable<BulkCloseQuery>};
|
||||
export function closeSelection(
|
||||
shown: Connection[],
|
||||
scope: {network: string; src: string | undefined; narrowed: boolean; truncated: boolean; bulkLimit: number | null | undefined}
|
||||
scope: {network: string; src: string | undefined; mac?: string; narrowed: boolean; truncated: boolean; bulkLimit: number | null | undefined}
|
||||
): CloseSelection {
|
||||
const ids = shown.map(c => c.id);
|
||||
const overLimit = scope.bulkLimit != null && ids.length > scope.bulkLimit;
|
||||
return scope.narrowed || scope.truncated || overLimit ? {ids} : {ids, query: {type: scope.network as 'all' | 'tcp' | 'udp', src: scope.src, all: true}};
|
||||
return scope.narrowed || scope.truncated || overLimit
|
||||
? {ids}
|
||||
: {ids, query: {type: scope.network as 'all' | 'tcp' | 'udp', src: scope.src, mac: scope.mac, all: true}};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {Connection} from '../../api/model';
|
||||
import {storageKeys} from '../../api/storage';
|
||||
import {sourceIp, outboundLabel} from '../../api/selectors';
|
||||
import {outboundLabel} from '../../api/selectors';
|
||||
import {deviceKey} from '../shared/ranking';
|
||||
import type {Key, Translator as LabelFn} from '../../i18n';
|
||||
import type {SortDescriptor} from 'react-aria-components';
|
||||
|
||||
@@ -32,11 +33,13 @@ export function toggleGroup(state: GroupCollapse, group: string): GroupCollapse
|
||||
}
|
||||
export const expandGroup = (state: GroupCollapse, group: string) => (isCollapsed(state, group) ? toggleGroup(state, group) : state);
|
||||
// Groups key on what the backend sent, not on its label, so a change of language keeps which groups are folded and
|
||||
// an outbound named like a built-in label stays its own group. Source groups key on the address without the port, so
|
||||
// one client is one group; a connection without an outbound joins `unknown`, which its label already reads as.
|
||||
// an outbound named like a built-in label stays its own group. Source groups key on the device, its MAC address or else
|
||||
// its address without the port, so one client is one group; a connection without an outbound joins `unknown`, which
|
||||
// its label already reads as. A device known by its MAC address reads as its name or address (deviceNames).
|
||||
export const groupKey = (row: Connection, group: Exclude<ConnectionView['group'], 'none'>) =>
|
||||
group === 'source' ? (sourceIp(row.src ?? undefined) ?? row.src ?? '—') : (row.outbound ?? 'unknown');
|
||||
export const groupName = (key: string, group: Exclude<ConnectionView['group'], 'none'>, t: LabelFn) => (group === 'source' ? key : outboundLabel(key, t));
|
||||
group === 'source' ? (deviceKey(row) ?? row.src ?? '—') : (row.outbound ?? 'unknown');
|
||||
export const groupName = (key: string, group: Exclude<ConnectionView['group'], 'none'>, t: LabelFn, devices: Readonly<Record<string, string>> = {}) =>
|
||||
group === 'source' ? devices[key] || key : outboundLabel(key, t);
|
||||
|
||||
// Groups and connections share the table's keys. A group's key is its own key after `g:`; a connection keeps its id
|
||||
// as its key, the way links and the selection name it, unless the id could read as a group's key or as an escaped
|
||||
|
||||
@@ -1,16 +1,43 @@
|
||||
import type {ConnectionList} from '../../api/model';
|
||||
import type {Connection, ConnectionList} from '../../api/model';
|
||||
import {connectionRows, sourceIp} from '../../api/selectors';
|
||||
import {addU64, pctU64} from '../../api/u64';
|
||||
|
||||
export function connectionRanking(snapshot: ConnectionList | undefined, by: string, limit = 5) {
|
||||
const totals = new Map<string, bigint | null>();
|
||||
for (const row of connectionRows(snapshot)) {
|
||||
const name = by === 'dev' ? sourceIp(row.src) : row.domain || row.dst;
|
||||
if (!name) continue;
|
||||
totals.set(name, addU64(totals.has(name) ? totals.get(name)! : 0n, row.download_bytes));
|
||||
// A device is its MAC address when the backend knows it, so one client's IPv4 and IPv6 connections count together, and
|
||||
// otherwise its source address.
|
||||
export const deviceKey = (row: Pick<Connection, 'src' | 'src_mac'>) => row.src_mac ?? sourceIp(row.src);
|
||||
|
||||
// What each device known by its MAC address reads as: the name the reader gave it, else the IPv4 address its latest
|
||||
// connection came from, else its first address, so an unnamed device looks as it did before its addresses merged.
|
||||
export function deviceNames(rows: ReadonlyArray<Pick<Connection, 'src' | 'src_mac' | 'started_at'>>, aliases: Readonly<Record<string, string>>) {
|
||||
const names: Record<string, string> = {};
|
||||
const latest: Record<string, number> = {};
|
||||
for (const row of rows) {
|
||||
const ip = sourceIp(row.src);
|
||||
if (!row.src_mac || !ip) continue;
|
||||
const mac = row.src_mac;
|
||||
const at = Date.parse(row.started_at ?? '') || 0;
|
||||
const v4 = !ip.includes(':');
|
||||
// An IPv4 address replaces an earlier or IPv6 one; an IPv6 address only names a device not seen yet.
|
||||
if (v4 ? !(mac in latest) || at > latest[mac] : !(mac in names)) {
|
||||
names[mac] = ip;
|
||||
if (v4) latest[mac] = at;
|
||||
}
|
||||
}
|
||||
const rows = [...totals].map(([name, download]) => ({name, download}));
|
||||
const total = addU64(...rows.map(row => row.download));
|
||||
rows.sort((a, b) => (a.download === b.download ? 0 : a.download === null ? 1 : b.download === null ? -1 : a.download > b.download ? -1 : 1));
|
||||
return rows.slice(0, limit).map(row => ({...row, percent: pctU64(row.download, total)}));
|
||||
return {...names, ...aliases};
|
||||
}
|
||||
|
||||
// The busiest devices or hosts by download. A device known by its MAC address is labelled as deviceNames reads it.
|
||||
export function connectionRanking(snapshot: ConnectionList | undefined, by: string, limit = 5, aliases: Readonly<Record<string, string>> = {}) {
|
||||
const totals = new Map<string, {download: bigint | null; mac: boolean}>();
|
||||
const rows = connectionRows(snapshot);
|
||||
for (const row of rows) {
|
||||
const name = by === 'dev' ? deviceKey(row) : row.domain || row.dst;
|
||||
if (!name) continue;
|
||||
totals.set(name, {download: addU64(totals.has(name) ? totals.get(name)!.download : 0n, row.download_bytes), mac: by === 'dev' && !!row.src_mac});
|
||||
}
|
||||
const devices = by === 'dev' ? deviceNames(rows, aliases) : {};
|
||||
const ranked = [...totals].map(([name, {download, mac}]) => ({name, label: (mac && devices[name]) || name, mac, download}));
|
||||
const total = addU64(...ranked.map(row => row.download));
|
||||
ranked.sort((a, b) => (a.download === b.download ? 0 : a.download === null ? 1 : b.download === null ? -1 : a.download > b.download ? -1 : 1));
|
||||
return ranked.slice(0, limit).map(row => ({...row, percent: pctU64(row.download, total)}));
|
||||
}
|
||||
@@ -404,6 +404,8 @@
|
||||
"conn.closedAll": "Closed {closed}, skipped {skipped}",
|
||||
"conn.collapseAll": "Collapse all",
|
||||
"conn.columns": "Columns",
|
||||
"conn.deviceName": "Device name",
|
||||
"conn.deviceNameHelp": "Shown in place of the MAC address, in this browser only. Leave it empty to show the MAC address again.",
|
||||
"conn.editRule": "Edit matched rule's outbound settings",
|
||||
"conn.empty": "No matching connections",
|
||||
"conn.expandAll": "Expand all",
|
||||
@@ -413,6 +415,7 @@
|
||||
"conn.f.downloadRate": "Download rate",
|
||||
"conn.f.dst": "Target address",
|
||||
"conn.f.ingress": "Ingress",
|
||||
"conn.f.mac": "MAC",
|
||||
"conn.f.observedBy": "Observed by",
|
||||
"conn.f.started": "Start time",
|
||||
"conn.filterHint": "Target, device, process",
|
||||
@@ -432,6 +435,7 @@
|
||||
"conn.latency.sample": "Nodes with a latency: {n}, without: {missing}",
|
||||
"conn.latency.weighted": "Nodes in use, weighted by connections, P50: {p50}",
|
||||
"conn.latency.weightedUnplaced": "Nodes in use, weighted by connections, P50: {p50}, connections without a latency: {n}",
|
||||
"conn.nameDevice": "Name device",
|
||||
"conn.notClosable": "The backend has no userspace transfer to interrupt, so this connection cannot be closed. Connections the kernel forwards directly are of this kind.",
|
||||
"conn.notInSnapshot": "This connection is not in the current list.",
|
||||
"conn.observed.mixed": "Userspace and eBPF",
|
||||
|
||||
@@ -347,6 +347,8 @@
|
||||
"conn.closedAll": "已关闭 {closed} 条,跳过 {skipped} 条",
|
||||
"conn.collapseAll": "全部折叠",
|
||||
"conn.columns": "列",
|
||||
"conn.deviceName": "设备名称",
|
||||
"conn.deviceNameHelp": "仅在此浏览器中代替 MAC 地址显示。留空则恢复显示 MAC 地址。",
|
||||
"conn.editRule": "编辑命中规则的出站设置",
|
||||
"conn.empty": "没有匹配的连接",
|
||||
"conn.expandAll": "全部展开",
|
||||
@@ -356,6 +358,7 @@
|
||||
"conn.f.downloadRate": "下载速率",
|
||||
"conn.f.dst": "目标地址",
|
||||
"conn.f.ingress": "入口",
|
||||
"conn.f.mac": "MAC",
|
||||
"conn.f.observedBy": "观测来源",
|
||||
"conn.f.started": "开始时间",
|
||||
"conn.filterHint": "目标、设备、进程",
|
||||
@@ -372,6 +375,7 @@
|
||||
"conn.latency.sample": "有延迟的节点:{n},无延迟数据:{missing}",
|
||||
"conn.latency.weighted": "使用中节点按连接数加权 P50:{p50}",
|
||||
"conn.latency.weightedUnplaced": "使用中节点按连接数加权 P50:{p50},无延迟数据:{n} 条连接",
|
||||
"conn.nameDevice": "命名设备",
|
||||
"conn.notClosable": "后端没有可中断的用户空间传输,无法关闭此连接。由内核直接转发的连接属于此类。",
|
||||
"conn.notInSnapshot": "当前列表未包含此连接。",
|
||||
"conn.observed.mixed": "用户空间与 eBPF",
|
||||
|
||||
@@ -347,6 +347,8 @@
|
||||
"conn.closedAll": "已關閉 {closed} 條,略過 {skipped} 條",
|
||||
"conn.collapseAll": "全部收合",
|
||||
"conn.columns": "欄位",
|
||||
"conn.deviceName": "裝置名稱",
|
||||
"conn.deviceNameHelp": "僅在此瀏覽器中代替 MAC 位址顯示。留空即恢復顯示 MAC 位址。",
|
||||
"conn.editRule": "編輯命中規則的出站設定",
|
||||
"conn.empty": "沒有符合的連線",
|
||||
"conn.expandAll": "全部展開",
|
||||
@@ -356,6 +358,7 @@
|
||||
"conn.f.downloadRate": "下載速率",
|
||||
"conn.f.dst": "目標位址",
|
||||
"conn.f.ingress": "入口",
|
||||
"conn.f.mac": "MAC",
|
||||
"conn.f.observedBy": "觀測來源",
|
||||
"conn.f.started": "開始時間",
|
||||
"conn.filterHint": "目標、裝置、行程",
|
||||
@@ -372,6 +375,7 @@
|
||||
"conn.latency.sample": "有延遲的節點:{n},無延遲資料:{missing}",
|
||||
"conn.latency.weighted": "使用中節點按連線數加權 P50:{p50}",
|
||||
"conn.latency.weightedUnplaced": "使用中節點按連線數加權 P50:{p50},無延遲資料:{n} 條連線",
|
||||
"conn.nameDevice": "命名裝置",
|
||||
"conn.notClosable": "後端沒有可中斷的使用者空間傳輸,無法關閉此連線。由核心直接轉發的連線屬於此類。",
|
||||
"conn.notInSnapshot": "目前清單未包含此連線。",
|
||||
"conn.observed.mixed": "使用者空間與 eBPF",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {useContext, useMemo} from 'react';
|
||||
import {useT, useLang, LOCALE, formatNumber} from '../../i18n';
|
||||
import {formatBytes, formatLatency, localTime} from '../../i18n/format';
|
||||
import {useCapabilities, useConnections, useRuntimeOutbounds, useDnsLog, poll} from '../../store';
|
||||
import {useCapabilities, useConnections, useDeviceAliases, useRuntimeOutbounds, useDnsLog, poll} from '../../store';
|
||||
import {connectionRows, outboundLabel, outboundUsage} from '../../api/selectors';
|
||||
import {connectionRanking} from '../../features/shared/ranking';
|
||||
import {outboundColor} from '../../features/activity/widgets';
|
||||
@@ -12,8 +12,9 @@ import {Bar, columns, Empty, Kv} from '../../ui/ui';
|
||||
import {contentLimit, registry, WidgetSurface, type Widget} from './layout';
|
||||
import {Reading} from './Reading';
|
||||
|
||||
// One share chart for every module that splits a total: donut, waffle, ranked bars or key-value rows, by form.
|
||||
type Share = {name: string; count: number; percent?: number; color?: string};
|
||||
// One share chart for every module that splits a total: donut, waffle, ranked bars or key-value rows, by form. A share
|
||||
// whose name can repeat, such as a device's, brings an id that does not.
|
||||
type Share = {id?: string; name: string; count: number; percent?: number; color?: string};
|
||||
// The shares with a value, each with its percentage of their total unless it brings its own, and a colour.
|
||||
export function shareRows(rows: Share[], colors: readonly string[]) {
|
||||
rows = rows.filter(row => row.count > 0);
|
||||
@@ -26,21 +27,21 @@ function Shares({item, rows, bytes = false, empty}: {item: Widget; rows: Share[]
|
||||
const p = usePalette();
|
||||
const format = (value: number) => (bytes ? formatBytes(value, locale) : formatNumber(value, locale));
|
||||
const {total, rows: shown} = shareRows(rows, p.cat);
|
||||
const shares = shown.map(row => ({...row, text: format(row.count)}));
|
||||
const shares = shown.map(row => ({...row, id: row.id ?? row.name, text: format(row.count)}));
|
||||
const chart = {legendLimit: item.rows ?? contentLimit(item.size), label: t(registry[item.id].label)};
|
||||
// A split of fixed categories has no row count on the dashboard and lists every one.
|
||||
const natural = useContext(WidgetSurface) === 'dashboard' && !registry[item.id].rows;
|
||||
if (!total) return <Empty>{empty}</Empty>;
|
||||
if (item.form === 'donut') return <Donut {...chart} total={format(total)} rows={shares.map(row => ({...row, value: Math.round(row.pct)}))} />;
|
||||
if (item.form === 'waffle') return <Waffle {...chart} shares={shares.map(row => ({...row, id: row.name, label: row.name}))} />;
|
||||
if (item.form === 'waffle') return <Waffle {...chart} shares={shares.map(row => ({...row, label: row.name}))} />;
|
||||
const listed = shares.slice(0, natural ? undefined : (item.rows ?? contentLimit(item.size)));
|
||||
return (
|
||||
<div className="rp-list rp-columns" style={columns(listed.length)}>
|
||||
{listed.map(row =>
|
||||
item.form === 'ranked' ? (
|
||||
<Bar key={row.name} label={row.name} value={row.text} pct={row.pct} color={row.color} />
|
||||
<Bar key={row.id} label={row.name} value={row.text} pct={row.pct} color={row.color} />
|
||||
) : (
|
||||
<Kv key={row.name} compact row={item.size !== 'small'} items={[[row.name, row.text]]} />
|
||||
<Kv key={row.id} compact row={item.size !== 'small'} items={[[row.name, row.text]]} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
@@ -49,14 +50,16 @@ function Shares({item, rows, bytes = false, empty}: {item: Widget; rows: Share[]
|
||||
export function RankingWidget({item}: {item: Widget}) {
|
||||
const t = useT();
|
||||
const list = useConnections(undefined, true, false, poll.summary);
|
||||
const aliases = useDeviceAliases();
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
connectionRanking(list.data, item.by ?? 'dev', item.rows ?? 5).map(row => ({
|
||||
name: row.name,
|
||||
connectionRanking(list.data, item.by ?? 'dev', item.rows ?? 5, aliases).map(row => ({
|
||||
id: row.name,
|
||||
name: row.label,
|
||||
count: Number(row.download ?? 0n),
|
||||
percent: row.percent ?? undefined
|
||||
})),
|
||||
[list.data, item.by, item.rows]
|
||||
[list.data, item.by, item.rows, aliases]
|
||||
);
|
||||
return (
|
||||
<Reading state={list}>
|
||||
|
||||
@@ -222,7 +222,7 @@ function watchedLists() {
|
||||
const clock = {ms: 0};
|
||||
const api = {connections: async () => snapshot(clock.ms, [['a', String(clock.ms)]])} as unknown as Api;
|
||||
const read = async (src: string) => {
|
||||
const watched = watchResource(api, connectionsResource(api, src, 0), () => {});
|
||||
const watched = watchResource(api, connectionsResource(api, {src}, 0), () => {});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
const data = watched.getSnapshot().data!;
|
||||
watched.dispose();
|
||||
|
||||
@@ -13,14 +13,17 @@ import {useAction} from './action';
|
||||
// The snapshot each connection list measures its next rates against, by resource key. A list the store no longer
|
||||
// holds, such as a source filter left a minute ago, drops its baseline rather than keeping it for the life of the tab.
|
||||
const baselines = new WeakMap<Api, Map<string, ConnectionList>>();
|
||||
export function connectionsResource(api: Api, src?: string, every?: number) {
|
||||
const key: ResourceKey = ['connections', {src}];
|
||||
// The source filters the backend applies: an IP address, a MAC address, or both.
|
||||
export type ConnectionFilter = {src?: string; mac?: string};
|
||||
export function connectionsResource(api: Api, filter: ConnectionFilter = {}, every?: number) {
|
||||
const {src, mac} = filter;
|
||||
const key: ResourceKey = ['connections', {src, mac}];
|
||||
const name = normalizeResourceKey(key);
|
||||
return {
|
||||
key,
|
||||
every,
|
||||
fetch: async (signal: AbortSignal) => {
|
||||
const next = await api.connections({type: 'all', detail: 'full', limit: MAX_PAGE, src}, signal);
|
||||
const next = await api.connections({type: 'all', detail: 'full', limit: MAX_PAGE, src, mac}, signal);
|
||||
let held = baselines.get(api);
|
||||
if (!held) baselines.set(api, (held = new Map()));
|
||||
for (const other of held.keys()) if (other !== name && !holds(api, other)) held.delete(other);
|
||||
@@ -32,8 +35,8 @@ export function connectionsResource(api: Api, src?: string, every?: number) {
|
||||
}
|
||||
};
|
||||
}
|
||||
export function useConnections(src?: string, enabled = true, paused = false, every?: number) {
|
||||
return useResource(connectionsResource(getApi(), src, every), {enabled, paused});
|
||||
export function useConnections(filter?: ConnectionFilter, enabled = true, paused = false, every?: number) {
|
||||
return useResource(connectionsResource(getApi(), filter, every), {enabled, paused});
|
||||
}
|
||||
const RATE_WINDOW_MS = 1000;
|
||||
const rateFields = ['upload', 'download'] as const;
|
||||
@@ -109,14 +112,15 @@ export async function closeInBatches(api: CloseApi, query: NonNullable<BulkClose
|
||||
return {closed: closed + round.closed, skipped: round.skipped};
|
||||
}
|
||||
// Only the full detail tier carries `src`.
|
||||
const listing = await api.connections({type, src: query.src, detail: 'full', limit: MAX_PAGE}, signal);
|
||||
const listing = await api.connections({type, src: query.src, mac: query.mac, detail: 'full', limit: MAX_PAGE}, signal);
|
||||
const listed = listing[type];
|
||||
const sources = new Map<string | undefined, string[]>();
|
||||
for (const row of listed) {
|
||||
const src = query.src ?? sourceIp(row.src ?? undefined);
|
||||
sources.set(src, (sources.get(src) ?? []).concat(row.id));
|
||||
}
|
||||
for (const [src, ids] of sources) add(round, src && !query.src ? await closeInBatches(api, {type, src}, signal) : await closeEach(api, ids, signal));
|
||||
for (const [src, ids] of sources)
|
||||
add(round, src && !query.src ? await closeInBatches(api, {type, src, mac: query.mac}, signal) : await closeEach(api, ids, signal));
|
||||
closed += round.closed;
|
||||
if (!round.closed) return {closed, skipped: type === 'tcp' ? listing.total_tcp : listing.total_udp};
|
||||
}
|
||||
@@ -125,7 +129,7 @@ export async function closeInBatches(api: CloseApi, query: NonNullable<BulkClose
|
||||
export function useConnectionClose(refetch: () => void) {
|
||||
const api = getApi();
|
||||
const {busy, run, cancel} = useAction<string>({rethrow: true});
|
||||
// Bulk close for a selection the contract can express (network and source IP); anything narrower (a text
|
||||
// Bulk close for a selection the contract can express (network, source IP and MAC); anything narrower (a text
|
||||
// or outbound filter) closes one by one. Over the advertised bulk limit, listed ids keep the confirmed scope; a
|
||||
// selection without them (close everything) goes in batches the limit admits.
|
||||
const closeAll = useCallback(
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import {useSyncExternalStore} from 'react';
|
||||
import {storageKeys} from '../api/storage';
|
||||
|
||||
// Names the reader gave devices, by MAC address, kept in this browser only; the backend never sees them.
|
||||
export type DeviceAliases = Readonly<Record<string, string>>;
|
||||
// The stored names, or undefined when storage is blocked.
|
||||
function stored(): DeviceAliases | undefined {
|
||||
let text: string | null;
|
||||
try {
|
||||
text = localStorage.getItem(storageKeys.deviceAliases);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const value: unknown = JSON.parse(text ?? '{}');
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? (value as DeviceAliases) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
let current: DeviceAliases | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
const snapshot = () => (current ??= stored() ?? {});
|
||||
// Another tab's names arrive through the storage event, as the dashboard layout's do.
|
||||
const subscribe = (listener: () => void) => {
|
||||
listeners.add(listener);
|
||||
const sync = (event: StorageEvent) => {
|
||||
if (event.key !== storageKeys.deviceAliases && event.key !== null) return;
|
||||
current = undefined;
|
||||
listener();
|
||||
};
|
||||
addEventListener('storage', sync);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
removeEventListener('storage', sync);
|
||||
};
|
||||
};
|
||||
// An empty name removes the alias, so the device shows its address again. The stored names are read again first, so a
|
||||
// name another tab saved meanwhile stays; blocked storage keeps this session's.
|
||||
export function saveDeviceAlias(mac: string, name: string) {
|
||||
const next = {...(stored() ?? snapshot())};
|
||||
if (name.trim()) next[mac] = name.trim();
|
||||
else delete next[mac];
|
||||
current = next;
|
||||
try {
|
||||
localStorage.setItem(storageKeys.deviceAliases, JSON.stringify(next));
|
||||
} catch {
|
||||
/* Retain this session's names. */
|
||||
}
|
||||
listeners.forEach(listener => listener());
|
||||
}
|
||||
export const useDeviceAliases = () => useSyncExternalStore(subscribe, snapshot);
|
||||
@@ -22,3 +22,4 @@ export {useLogFeed, useEventFeed, useNoticeFeed, LOG_FEED_LIMIT} from './logs';
|
||||
export {historyLost, reopenEvents, useFlowDemand, EVENT_FEED_LIMIT} from './events';
|
||||
export {pendingRules, usePendingRules, type PendingRule, type HeldRule, type PendingPlace, type PendingFailure} from './pendingRules';
|
||||
export {poll} from './cadence';
|
||||
export {useDeviceAliases, saveDeviceAlias, type DeviceAliases} from './deviceAliases';
|
||||
@@ -57,7 +57,8 @@ export const Spark = memo(function Spark(props: ComponentProps<typeof LazySpark>
|
||||
</LoadBoundary>
|
||||
);
|
||||
});
|
||||
// Scroll long legends so the chart does not stretch adjacent cards. A row with `href` names what it opens.
|
||||
// Scroll long legends so the chart does not stretch adjacent cards. A row with `href` names what it opens, and one
|
||||
// whose name can repeat brings an `id`.
|
||||
export const Donut = memo(
|
||||
function Donut({
|
||||
label,
|
||||
@@ -66,7 +67,7 @@ export const Donut = memo(
|
||||
legendLimit
|
||||
}: {
|
||||
label: string;
|
||||
rows: Array<{name: string; value: number | null; text: string; color: string; href?: string}>;
|
||||
rows: Array<{id?: string; name: string; value: number | null; text: string; color: string; href?: string}>;
|
||||
total: string;
|
||||
legendLimit?: number;
|
||||
}) {
|
||||
@@ -84,7 +85,7 @@ export const Donut = memo(
|
||||
</div>
|
||||
<div className="lst">
|
||||
{legend.slice(0, legendLimit).map(r => (
|
||||
<div key={r.name} className="r">
|
||||
<div key={r.id ?? r.name} className="r">
|
||||
<i className="dot" style={{background: r.color}} />
|
||||
<span className="n">
|
||||
{r.href ? (
|
||||
|
||||
@@ -6,7 +6,7 @@ import {ChartTip, useChartTip} from './tip';
|
||||
import {useSelection} from './interaction';
|
||||
import {donutAngles} from './layout';
|
||||
|
||||
export function DonutPlot({label, rows}: {label: string; rows: Array<{name: string; value: number | null; text: string; color: string}>}) {
|
||||
export function DonutPlot({label, rows}: {label: string; rows: Array<{id?: string; name: string; value: number | null; text: string; color: string}>}) {
|
||||
const t = useT();
|
||||
const [ref, size] = useContentSize<HTMLDivElement>(Math.round, 120);
|
||||
const {tip, showAt, hide} = useChartTip();
|
||||
@@ -67,7 +67,7 @@ export function DonutPlot({label, rows}: {label: string; rows: Array<{name: stri
|
||||
<g transform={`translate(${width / 2},${height / 2})`}>
|
||||
{sectors.map((sector, index) => (
|
||||
<path
|
||||
key={data[index].name}
|
||||
key={data[index].id ?? data[index].name}
|
||||
d={ring({...sector, endAngle: Math.min(sector.endAngle, sector.startAngle + (359.999 * Math.PI) / 180)}) ?? undefined}
|
||||
fill={data[index].color}
|
||||
stroke="none"
|
||||
|
||||
Reference in new issue
Block a user