feat(nodes): add, show and edit proxy chains (#702)

## Problem / 问题

After #701, doona reads proxy chains and keeps their references intact,
but it gives no way to see or build one. A chain row shows the raw
protocol `chain` and no hops. Adding or editing a chain means editing
the configuration text, because honk's `POST /nodes` only takes share
links.

## How I fixed it / 解决方法

Display:
- A chain row shows the protocol as "Proxy chain" (代理鏈 / 代理链).
- Its detail lists the hops from entry to exit, with each hop's protocol
and health, and marks a hop that is missing or ambiguous.
- UDP is shown as "No" with the reason when the hop protocols rule it
out. Otherwise it reads "depends on node settings", because the catalog
does not expose UDP flags.
- The node-level TCP connect test is hidden for chains, since honk
returns 422. Group latency no longer counts a chain member's
`no_node_address` row as a failure.

Editing:
- The add-node dialog has a "Proxy chain" mode with an ordered picker of
2 to 4 existing non-chain nodes. Hops can be added, removed and moved up
or down.
- Editing a chain reopens the same dialog. `appendChainEntry` and
`writeChainEntry` write the configuration text through source PUT.
- Before writing, the dialog checks hop count, self reference, direct,
block or chain hops, and the protocol position rules from honk's
`nodes.md` that the catalog can show. honk's diagnostics are shown for
everything else.
- Creating and editing chains is offered only when the engine is honk
and the main source is editable.

`writeNodeEntry` and `writeChainEntry` share one edit helper.
`SearchSelect` gains optional `error` and `action` props, so a hop's
controls sit beside its picker and its error spans the row. Other call
sites are unchanged.

Group `exit` editing, the rejected subscription refresh notice and the
manual pages follow in a stacked PR.

## Screenshots

| | |
|---|---|
|
![](https://gist.githubusercontent.com/Zakkaus/1e1f373d5d925683e7ddbf5e819ca774/raw/node-list-en-light-1280.png)
|
![](https://gist.githubusercontent.com/Zakkaus/1e1f373d5d925683e7ddbf5e819ca774/raw/node-list-zh-TW-dark-390.png)
|
|
![](https://gist.githubusercontent.com/Zakkaus/1e1f373d5d925683e7ddbf5e819ca774/raw/chain-detail-en-light-1280.png)
|
![](https://gist.githubusercontent.com/Zakkaus/1e1f373d5d925683e7ddbf5e819ca774/raw/chain-detail-zh-TW-dark-1280.png)
|
|
![](https://gist.githubusercontent.com/Zakkaus/1e1f373d5d925683e7ddbf5e819ca774/raw/chain-dialog-en-light-1280.png)
|
![](https://gist.githubusercontent.com/Zakkaus/1e1f373d5d925683e7ddbf5e819ca774/raw/chain-dialog-zh-TW-dark-390.png)
|
|
![](https://gist.githubusercontent.com/Zakkaus/1e1f373d5d925683e7ddbf5e819ca774/raw/chain-dialog-error-en-light-1280.png)
|
![](https://gist.githubusercontent.com/Zakkaus/1e1f373d5d925683e7ddbf5e819ca774/raw/chain-dialog-error-zh-TW-dark-1280.png)
|

All 32 variants (390 and 1280, en and zh-TW, light and dark) are kept
locally and available on request.

## Verified / 验证

- `pnpm typecheck`, `lint` (0 warnings), `check:i18n`, `format:check`,
`check:gen` and `build` all exit 0.
- `pnpm test` exits 0: 251 files, 4405 tests.
- `check:size`:
- Nodes route is 73162 B gzip against a 76000 B budget, up from 72320 B.
  - The lazily loaded chain picker chunk is 812 B.
- Playwright `e2e/nodes.spec.ts` on chromium: 101 passed. The 6 other
specs that the new mock chain touched pass, but the full suite was not
rerun after the last change.
- A separate review ablated each key hunk, and every one is now caught
by a test.

Not verified:
- Writes against a live honk.
- Firefox and WebKit e2e.

Net shipped code is about 414 lines, over the 300-line feature budget.
The PR carries display, editing and the engine gate together; splitting
it is possible if wanted.

---

- [ ] I understand this change and answer for every line
- [x] This branch is based on the current main
- [x] I ran the repository's gates and recorded the results in Verified
- [x] Each commit is one coherent change
- [ ] If behaviour changed, I updated the documentation
- [x] If interface text changed, I updated `en.json` and every complete
language's catalogue
- [x] If interface appearance changed, I attached light and dark
screenshots
- [ ] If the API contract changed, I ran `pnpm gen:api` and `pnpm
check:gen`
- [ ] I checked the boxes above without reading them
- [ ] I am an AI agent, and this content was submitted without human
review
This commit is contained in:
Zakk authored and GitHub committed 2026-11-25 17:58:58 +11:00
1 parent 6707673a9e
commit 8d81ddb689
38 files changed
+777 -90

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
Added
- The Add node dialog has a Proxy chain mode that picks 2 to 4 existing nodes from entry to exit, checks each hop's position against its protocol, and writes the chain to the main configuration file. A chain's Edit action opens the same fields, and a rename updates the groups that name it.
- Node details list a proxy chain's hops with their protocol and latency, flag a hop that names no node or several, and say whether UDP is ruled out by protocol or depends on node settings.
- Proxy chains show as "Proxy chain" in the node list and can be tested by HTTP and DNS. A group TCP connect test no longer counts a chain member as a failure.
- honk's proxy chain diagnostics read in the page language where a configuration write is refused.
+2 -2
View File
@@ -24,7 +24,7 @@ test('the DNS rules tab lists request and response rules, each ending with its f
await expect(request).toHaveCount(5);
await expect(request.first()).toContainText('qname(geosite: category-ads-all)');
await expect(request.first()).toContainText('reject');
await expect(request.first()).toContainText('config.dae:29');
await expect(request.first()).toContainText('config.dae:30');
await expect(request.nth(3)).toContainText('alidns');
await expect(request.last()).toContainText('fallback: cloudflare');
const response = rows(page, 'Response rules');
@@ -46,7 +46,7 @@ test('the DNS rules lead to the resolution log and to the dns section of the con
await page.goBack();
await expect(page).toHaveURL(/#\/rules\?tab=dns$/);
await section(page, 'Request rules').getByRole('link', {name: 'Open DNS configuration', exact: true}).click();
await expect(page).toHaveURL(/#\/config\?tab=source&source=src-main&line=22$/);
await expect(page).toHaveURL(/#\/config\?tab=source&source=src-main&line=23$/);
});
test('a DNS request rule is added through the source splice and removed again', async ({page}) => {
+1 -1
View File
@@ -513,7 +513,7 @@ test('the statistics lead to the DNS configuration, the cache and the log filter
await page.setViewportSize({width: 1440, height: 900});
await page.goto('/#/dns');
await page.getByRole('link', {name: 'Open DNS configuration', exact: true}).click();
await expect(page).toHaveURL(/#\/config\?tab=source&source=src-main&line=22$/);
await expect(page).toHaveURL(/#\/config\?tab=source&source=src-main&line=23$/);
await expect(page.locator('.cm-activeLine')).toContainText('dns {');
await page.goBack();
await page.getByRole('region', {name: 'Cache', exact: true}).getByRole('link', {name: 'View cache', exact: true}).click();
+5 -1
View File
@@ -158,7 +158,11 @@ test('mixed argument matches edit visually and keep OR inside a negated AND row'
expect(
readGroupEntries((await api.config()).sources.find(source => source.kind === 'main')!.content).find(entry => entry.name === 'visual')!.filters
).toEqual([`!name(keyword: 'hk', regex: '^sg') && name(regex: '^[a-z]')`]);
expect((await api.group((await api.groups()).find(group => group.name === 'visual')!.id)).members.map(member => member.name)).toEqual(['jp-01', 'us-01']);
expect((await api.group((await api.groups()).find(group => group.name === 'visual')!.id)).members.map(member => member.name)).toEqual([
'jp-01',
'us-01',
'relay'
]);
});
test('OR matches can be added, removed and combined with the existing AND row', async ({page}) => {
+1 -1
View File
@@ -498,6 +498,6 @@ test('the membership summary is a short count with names in a collapsed tag list
.locator('label')
.filter({has: page.getByRole('switch', {name: 'All nodes', exact: true})})
.click();
await expect(dialog.getByRole('status')).toHaveText('125 nodes');
await expect(dialog.getByRole('status')).toHaveText('126 nodes');
await expect(dialog.getByText(/Currently selects|no filter|holds every node/)).toHaveCount(0);
});
+47 -8
View File
@@ -23,7 +23,7 @@ test('nodes sort by name, latency and protocol, and filter by group and protocol
await page.goto('/#/nodes?provider=inline');
const table = page.locator('.rp-table').first();
const list = rows(table);
await expect(list).toHaveCount(5);
await expect(list).toHaveCount(6);
await expect(list.first()).toContainText('hk-01');
await table.getByRole('columnheader', {name: /^Latency/}).click();
await expect(list.first()).toContainText('sg-01');
@@ -35,7 +35,7 @@ test('nodes sort by name, latency and protocol, and filter by group and protocol
await page.getByRole('button', {name: /Group$/}).click();
await page.getByRole('option', {name: 'gaming', exact: true}).click();
await expect(list).toHaveCount(2);
await expect(page.locator('.rp-toolbar').nth(1)).toContainText('2 / 5');
await expect(page.locator('.rp-toolbar').nth(1)).toContainText('2 / 6');
await page.getByLabel('Search nodes').fill('jp');
await expect(list).toHaveCount(1);
});
@@ -52,7 +52,7 @@ test('a node list that comes back empty once is asked for again and shown', asyn
{times: 1}
);
await page.goto('/#/nodes?provider=inline');
await expect(rows(page.locator('.rp-table').first())).toHaveCount(5);
await expect(rows(page.locator('.rp-table').first())).toHaveCount(6);
expect(dropped).toBe(1);
expect(requests.some(request => new URL(request.url()).pathname === '/api/v1/nodes')).toBe(true);
});
@@ -61,7 +61,7 @@ test('node cell content starts at its header text, including latency and action
await page.setViewportSize({width: 1440, height: 900});
await page.goto('/#/nodes?provider=inline');
const table = page.locator('.rp-table').first();
await expect(rows(table)).toHaveCount(5);
await expect(rows(table)).toHaveCount(6);
await page.evaluate(() => document.fonts.ready);
for (const label of ['Protocol', 'Latency', 'Groups', 'Actions']) {
const header = table.getByRole('columnheader', {name: new RegExp(`^${label}`)});
@@ -89,7 +89,7 @@ test('a share link becomes an inline node and can be removed again', async ({pag
await page.goto('/#/nodes?provider=inline');
const table = page.locator('.rp-table').first();
const list = rows(table);
await expect(list).toHaveCount(5);
await expect(list).toHaveCount(6);
await page.getByRole('button', {name: 'Add node', exact: true}).click();
const dialog = page.getByRole('dialog');
await dialog.getByLabel('Node link').fill('foo://nope');
@@ -99,17 +99,56 @@ test('a share link becomes an inline node and can be removed again', async ({pag
await dialog.getByLabel('Node link').fill('vless://uuid@example.com:443?security=tls#hk-03');
await dialog.getByRole('button', {name: 'Add', exact: true}).click();
await expect(page.locator('.rp-toast.positive', {hasText: 'hk-03 added'})).toBeVisible();
await expect(list).toHaveCount(6);
await expect(list).toHaveCount(7);
await expect(list.filter({hasText: 'hk-03'})).toContainText('vless');
await page.getByRole('button', {name: 'Remove hk-03', exact: true}).click();
await page.getByRole('alertdialog').getByRole('button', {name: 'Remove hk-03', exact: true}).click();
await expect(page.locator('.rp-toast.positive', {hasText: 'hk-03 removed'})).toBeVisible();
await expect(list).toHaveCount(5);
await expect(list).toHaveCount(6);
// The management write landed in the main source as a new generation.
await page.locator('.rp-nav[href="#/config"]').click();
await expect(page.locator('.rp-toolbar:visible').first()).toContainText('42');
});
test('a proxy chain is added from its hops, shown with them, edited and removed as text', async ({page}) => {
await page.goto('/#/nodes?provider=inline');
const list = rows(page.locator('.rp-table').first());
await expect(list.filter({hasText: 'relay'})).toContainText('Proxy chain');
await page.getByRole('button', {name: 'Add node', exact: true}).click();
const dialog = page.getByRole('dialog');
await dialog.getByRole('tab', {name: 'Proxy chain'}).click();
await dialog.getByLabel('Name').fill('via-us');
const pick = async (hop: string, node: string) => {
await dialog.getByRole('button', {name: new RegExp(`${hop}$`)}).click();
await page.getByRole('option', {name: new RegExp(`^${node}`)}).click();
};
await pick('Hop 1', 'hk-01');
await pick('Hop 2', 'us-01');
// AnyTLS can only be the entry, which the catalog shows before anything is written.
await expect(dialog.locator('.rp-field-error', {hasText: 'cannot be a proxy chain hop at this position'})).toBeVisible();
await expect(dialog.getByRole('button', {name: 'Add', exact: true})).toBeDisabled();
await dialog.getByRole('button', {name: 'Move hop 2 up'}).click();
await dialog.getByRole('button', {name: 'Add hop'}).click();
await pick('Hop 3', 'sg-01');
await dialog.getByRole('button', {name: 'Add', exact: true}).click();
await expect(page.locator('.rp-toast.positive', {hasText: 'via-us added'})).toBeVisible();
const row = list.filter({hasText: 'via-us'});
await expect(row).toContainText('Proxy chain');
await row.click();
await expect(page.getByText('Hops, entry to exit')).toBeVisible();
await expect(page.getByText('No (us-01 cannot be dialed through another hop)')).toBeVisible();
await moreAction(row, 'Edit…', 'Node actions');
const edit = page.getByRole('dialog');
await edit.getByLabel('Name').fill('via-us-2');
await edit.getByRole('button', {name: 'Remove hop 3'}).click();
await edit.getByRole('button', {name: 'Apply', exact: true}).click();
await expect(page.locator('.rp-toast.positive', {hasText: 'Saved via-us-2'})).toBeVisible();
await page.getByRole('button', {name: 'Remove via-us-2', exact: true}).click();
await page.getByRole('alertdialog').getByRole('button', {name: 'Remove via-us-2', exact: true}).click();
await expect(page.locator('.rp-toast.positive', {hasText: 'via-us-2 removed'})).toBeVisible();
await expect(list.filter({hasText: 'via-us'})).toHaveCount(0);
});
for (const transport of ['xhttp', 'splithttp'])
test(`raw ${transport} links reach create and edit API payloads unchanged`, async ({page}) => {
const {api, handlers, requests} = await mockBackend(page);
@@ -864,7 +903,7 @@ test('node sources list their nodes and a subscription can be refreshed', async
expect(await nodes.count()).toBeGreaterThan(10);
await sources.nth(1).click();
await expect(page).toHaveURL(/provider=inline$/);
await expect(nodes).toHaveCount(5);
await expect(nodes).toHaveCount(6);
await page.getByRole('button', {name: 'Update harbor', exact: true}).click();
await expect(page.locator('.rp-toast.positive')).toContainText('harbor updated, 120 nodes');
});
+3 -3
View File
@@ -50,7 +50,7 @@ test('the rule list shows the dictionary in evaluation order with its source lin
const list = rows(page);
await expect(list).toHaveCount(21);
await expect(list.first()).toContainText('pname(NetworkManager)');
await expect(list.first()).toContainText('config.dae:149');
await expect(list.first()).toContainText('config.dae:150');
await expect(list.nth(7)).toContainText('domain(geosite:telegram)');
await expect(list.last()).toContainText('fallback: proxy');
await expect(page.getByRole('tabpanel', {name: 'Routing rules'})).toContainText('21 rules, generation 40');
@@ -62,11 +62,11 @@ test('the rule list shows the dictionary in evaluation order with its source lin
test('a visually editable rule keeps Edit and Remove beside the link to its config file line', async ({page}) => {
await page.goto('/#/rules?tab=list&view=advanced');
const row = rows(page).first();
await expect(row).toContainText('config.dae:149');
await expect(row).toContainText('config.dae:150');
await expect(row.getByRole('button', {name: 'Edit rule', exact: true})).toBeEnabled();
await expect(row.getByRole('button', {name: 'Remove rule', exact: true})).toBeVisible();
await row.getByRole('button', {name: 'Open config file', exact: true}).click();
await expect(page).toHaveURL(/#\/config\?tab=source&source=[^&]+&line=149$/);
await expect(page).toHaveURL(/#\/config\?tab=source&source=[^&]+&line=150$/);
await expect(page.getByRole('dialog')).toHaveCount(0);
});
+3 -3
View File
@@ -12,9 +12,9 @@ async function unsupportedRule(page: import('@playwright/test').Page) {
}
const lists = [
{name: 'routing', route: '/#/rules?tab=list&view=advanced', scope: 'Routing rules', role: 'tabpanel', line: 149},
{name: 'DNS request', route: '/#/rules?tab=dns', scope: 'Request rules', role: 'region', line: 29},
{name: 'DNS response', route: '/#/rules?tab=dns', scope: 'Response rules', role: 'region', line: 36}
{name: 'routing', route: '/#/rules?tab=list&view=advanced', scope: 'Routing rules', role: 'tabpanel', line: 150},
{name: 'DNS request', route: '/#/rules?tab=dns', scope: 'Request rules', role: 'region', line: 30},
{name: 'DNS response', route: '/#/rules?tab=dns', scope: 'Response rules', role: 'region', line: 37}
] as const;
for (const lang of ['en', 'zh-TW', 'zh-CN'] as const) {
+3 -1
View File
@@ -5,6 +5,7 @@ import {nestedIn, nameText, readGroupEntries, writeGroupEntry} from '../src/dae/
import {groupAdmits} from '../src/dae/groupFilters';
import {policyKind} from '../src/dae/vocab';
import {readSubscriptionEntries} from '../src/dae/subscriptions';
import {readChainEntries} from '../src/dae/nodes';
import {displayUrl} from './common';
import {groupCapabilities, groupConfig} from './groupDefaults';
import {resolveLeaf} from './control';
@@ -43,10 +44,11 @@ export function activateInventory(
const providerIds = new Set(subscriptions.map(entry => entry.tag));
const inline = fields('node');
const inlineNames = new Set(inline.map(field => field.name));
const chains = new Set(readChainEntries(text).map(chain => chain.name));
const nextNodes = nodes.filter(node => (node.provider_id === 'inline' ? inlineNames.has(node.name) : providerIds.has(node.provider_id!)));
for (const field of inline) {
const link = unquote(field.value);
const protocol = link.split(':')[0];
const protocol = chains.has(field.name) ? 'chain' : link.split(':')[0];
const stream_transport = streamTransport(link, protocol);
const existing = nextNodes.find(node => node.provider_id === 'inline' && node.name === field.name);
if (existing) Object.assign(existing, {protocol, stream_transport});
+1
View File
@@ -47,6 +47,7 @@ node {
'sg-01': 'trojan://demo@sg-01.example.net:443#sg-01'
'jp-01': 'vless://00000000-0000-4000-8000-000000000001@jp-01.example.net:443?security=tls&type=xhttp&mode=packet-up&path=%2Fxhttp%2F&alpn=h2#jp-01'
'us-01': 'anytls://demo@us-01.example.net:443#us-01'
relay: jp-01 -> hk-02
}
dns {
+2 -1
View File
@@ -65,7 +65,8 @@ export function nodeFixtures(count: number, faults = false): {nodes: Node[]; gro
...node('jp-01', faults ? null : 132, faults ? null : 139, false, 'inline', 'vless', [0.86, 0.9]),
stream_transport: 'xhttp'
},
node('us-01', 188, 201, true, 'inline', 'anytls', [0.62, 0.7])
node('us-01', 188, 201, true, 'inline', 'anytls', [0.62, 0.7]),
node('relay', 152, 160, false, 'inline', 'chain', [0.9, 1])
];
// A UDP data probe besides the TCP and DNS ones on hk-01 and sg-01; the faults scenario fails sg-01's.
nodes[0].health.push({...health('udp', 97, [1, 1]), purpose: 'data', measurement: 'quic_handshake'});
+5 -2
View File
@@ -45,8 +45,11 @@ const measurementRank: Record<string, number> = {
dns_round_trip: 6
};
const observationRank = (h: HealthObservation) => (warmthRank[h.warmth] ?? 1) * 10 + (measurementRank[h.measurement] ?? 5);
// A group's tcp_connect probe reports a proxy chain member as unavailable with `no_node_address`: the chain has no
// server endpoint of its own, so the row measured nothing and is not a failure.
export const measured = (h: Pick<HealthObservation, 'error'>) => h.error !== 'no_node_address';
export function preferredObservation<T extends HealthObservation>(health: T[]): T | undefined {
const data = health.filter(h => h.transport === 'tcp' && h.purpose === 'data');
const data = health.filter(h => h.transport === 'tcp' && h.purpose === 'data' && measured(h));
const best = Math.min(...data.map(observationRank));
return foldFamilies(data.filter(h => observationRank(h) === best));
}
@@ -71,7 +74,7 @@ const probeKind = (h: HealthObservation): ProbeKind =>
h.purpose === 'dns' ? 'DNS' : h.transport === 'udp' ? 'UDP' : h.measurement.startsWith('http') ? 'HTTP' : 'TCP';
export function probeKinds<T extends HealthObservation>(health: T[]) {
const kinds = new Map<string, {kind: ProbeKind; transport: T['transport']; rows: T[]}>();
for (const h of health) {
for (const h of health.filter(measured)) {
const kind = probeKind(h);
const key = kind + '/' + h.transport;
const entry = kinds.get(key);
+92 -1
View File
@@ -1,5 +1,16 @@
import {expect, it} from 'vitest';
import {nodeReferenced, nodeReferrers, readChainEntries, readNodeEntries, removeChainEntry, writeNodeEntry} from './nodes';
import {
appendChainEntry,
chainHopProblem,
chainUdpProblem,
nodeReferenced,
nodeReferrers,
readChainEntries,
readNodeEntries,
removeChainEntry,
writeChainEntry,
writeNodeEntry
} from './nodes';
import {unquote} from './text';
const text = `# keep\r\nnode {\r\n "old" : 'socks5://127.0.0.1:1080' # node\r\n}\r\ngroup {\r\n proxy {\r\n filter: name('old', other) && !name(old) # filter\r\n filter: name(keyword: old)\r\n policy: random\r\n }\r\n}\r\n`;
@@ -116,3 +127,83 @@ it.each([
expect(() => removeChainEntry(source.replace('-> y', '-> w'), chain)).toThrow();
expect(() => removeChainEntry(source + source, chain)).toThrow();
});
const chainSource = "node {\n a: 'socks5://a:1'\n via: a -> 'hk: east' # keep\n}\ngroup {\n proxy {\n filter: name(via)\n final: via\n }\n}\n";
it.each([
['the hops', {name: 'via', hops: ['a', 'b c', 'd']}, chainSource.replace("a -> 'hk: east'", "a -> 'b c' -> d")],
[
'the name, and what names it',
{name: 'new via', hops: ['a', 'hk: east']},
chainSource.replace('via:', "'new via':").replace(/via\n/g, "'new via'\n").replace('name(via)', "name('new via')")
],
['nothing', {name: 'via', hops: ['a', 'hk: east']}, chainSource]
])('writes a chain with %s changed', (_, next, written) => {
const [chain] = readChainEntries(chainSource);
expect(writeChainEntry(chainSource, chain, next)).toBe(written);
});
it.each([
['a stale chain', chainSource.replace("'hk: east'", 'b'), {name: 'via', hops: ['a', 'b']}],
['a taken name', chainSource, {name: 'a', hops: ['a', 'b']}],
['one hop', chainSource, {name: 'via', hops: ['a']}],
['five hops', chainSource, {name: 'via', hops: ['a', 'b', 'c', 'd', 'e']}],
['an empty hop', chainSource, {name: 'via', hops: ['a', '']}],
['an unquotable hop', chainSource, {name: 'via', hops: ['a', "it's"]}]
])('refuses to write %s', (_, source, next) => {
const [chain] = readChainEntries(chainSource);
expect(() => writeChainEntry(source, chain, next)).toThrow();
});
it.each([
[
'the last node block, indented as its entries',
"node {\n a: 'socks5://a:1'\n}\nnode {\n\tb: 'socks5://b:1' # b\n}\n",
"node {\n a: 'socks5://a:1'\n}\nnode {\n\tb: 'socks5://b:1' # b\n\t'new': a -> 'b c'\n}\n"
],
['an empty node block', 'node {\n}\n', "node {\n 'new': a -> 'b c'\n}\n"],
['a new node block', 'global {\n}\n\n', "global {\n}\n\nnode {\n 'new': a -> 'b c'\n}\n"],
['an empty source', '', "node {\n 'new': a -> 'b c'\n}\n"],
['a CRLF file', "node {\r\n a: 'x://h'\r\n}\r\n", "node {\r\n a: 'x://h'\r\n 'new': a -> 'b c'\r\n}\r\n"],
['a block closed after its last entry', "node {\n a: 'x://h' }\n", "node {\n a: 'x://h'\n 'new': a -> 'b c'\n}\n"],
['a one-line block', "node { a: 'x://h' }\n", "node { a: 'x://h'\n 'new': a -> 'b c'\n}\n"]
])('appends a chain to %s', (_, source, appended) => {
expect(appendChainEntry(source, {name: 'new', hops: ['a', 'b c']})).toBe(appended);
expect(readChainEntries(appended).at(-1)).toMatchObject({name: 'new', hops: [{name: 'a'}, {name: 'b c'}]});
expect(() => appendChainEntry(appended, {name: 'new', hops: ['a', 'b']})).toThrow();
});
const catalog = [
{name: 'ss', protocol: 'ss'},
{name: 'hy', protocol: 'hysteria2'},
{name: 'trojan', protocol: 'trojan'},
{name: 'vmess', protocol: 'vmess'},
{name: 'xhttp', protocol: 'vless', stream_transport: 'xhttp' as const},
{name: 'via', protocol: 'chain'},
{name: 'direct', protocol: 'direct'},
{name: 'twice', protocol: 'ss'},
{name: 'twice', protocol: 'ss'}
];
it.each([
['missing', 0, 'invalid-chain-hop-reference'],
['twice', 1, 'ambiguous-chain-hop-reference'],
['hy', 0, null],
['hy', 1, 'unsupported-chain-hop'],
['xhttp', 0, null],
['xhttp', 2, 'unsupported-chain-hop'],
['trojan', 3, null],
['vmess', 1, null],
['via', 0, 'unsupported-chain-hop'],
['direct', 0, 'unsupported-chain-hop']
])('checks hop %s at position %i', (name, index, code) => {
expect(chainHopProblem(catalog, name, index)).toBe(code);
});
it.each([
[['ss', 'trojan'], null],
[['hy', 'trojan'], {kind: 'hop', name: 'hy'}],
[['ss', 'xhttp'], {kind: 'hop', name: 'xhttp'}],
[['trojan', 'ss'], {kind: 'exit', name: 'ss'}],
[['ss', 'vmess'], {kind: 'exit', name: 'vmess'}]
])('rules out UDP through %j by protocol: %j', (hops, problem) => {
expect(chainUdpProblem(hops.map(name => catalog.find(node => node.name === name)!))).toEqual(problem);
});
+75 -7
View File
@@ -1,4 +1,5 @@
import {LocalError} from '../api/error';
import type {Node} from '../api/model';
import {blockEntries, blockFields, isQuotable, quote, scanConfig, unquote} from './text';
import {quoteName} from './groups';
@@ -117,12 +118,17 @@ export function nodeReferrers(text: string, name: string): NodeReferrer[] {
return [...unique.values()];
}
// Deletes the chain's line, comment included, or only the entry when it shares a line with other text.
export function removeChainEntry(text: string, original: ChainEntry): string {
// The chain as the dialog read it, still declared once with the same hops.
function currentChain(text: string, original: ChainEntry): ChainEntry {
const entries = readChainEntries(text).filter(entry => entry.name === original.name);
const hops = (entry: ChainEntry) => JSON.stringify(entry.hops.map(hop => hop.name));
if (entries.length !== 1 || hops(entries[0]) !== hops(original)) throw new LocalError('nodes.editNodeMissing');
const {from, to} = entries[0];
return entries[0];
}
// Deletes the chain's line, comment included, or only the entry when it shares a line with other text.
export function removeChainEntry(text: string, original: ChainEntry): string {
const {from, to} = currentChain(text, original);
const start = text.lastIndexOf('\n', from - 1) + 1;
const newline = text.indexOf('\n', to);
const end = newline === -1 ? text.length : newline;
@@ -130,6 +136,63 @@ export function removeChainEntry(text: string, original: ChainEntry): string {
return text.slice(0, start) + text.slice(newline === -1 ? end : end + 1);
}
// honk's hop rules as far as the node catalog shows them: the protocol, and XHTTP among the stream transports. Vision,
// Encryption, TCP multiplexing and ECH are not in the catalog, so honk's own check reports them.
type HopNode = Pick<Node, 'name' | 'protocol' | 'stream_transport'>;
const tunneled = new Set(['socks5', 'ss', 'shadowsocks', 'trojan', 'vmess', 'vless']);
export const chainHopCandidate = (node: Pick<Node, 'protocol'>) => !['chain', 'direct', 'block'].includes(node.protocol ?? '');
// Whether a node can be a hop after the entry: dialed inside the stream the hops before it opened.
export const tunnelDialable = (node: Pick<Node, 'protocol' | 'stream_transport'>) => tunneled.has(node.protocol ?? '') && node.stream_transport !== 'xhttp';
export type ChainHopCode = 'invalid-chain-hop-reference' | 'ambiguous-chain-hop-reference' | 'unsupported-chain-hop';
export function chainHopProblem(nodes: readonly HopNode[], name: string, index: number): ChainHopCode | null {
const matches = nodes.filter(node => node.name === name);
if (matches.length !== 1) return matches.length ? 'ambiguous-chain-hop-reference' : 'invalid-chain-hop-reference';
return !chainHopCandidate(matches[0]) || (index > 0 && !tunnelDialable(matches[0])) ? 'unsupported-chain-hop' : null;
}
// What rules out UDP through the chain by protocol alone: a hop that cannot be tunnel-dialed, then an exit that is
// neither Trojan nor VLESS. null when the hops' own UDP settings decide.
export function chainUdpProblem(hops: ReadonlyArray<Pick<Node, 'name' | 'protocol' | 'stream_transport'>>) {
const hop = hops.find(node => !tunnelDialable(node));
if (hop) return {kind: 'hop' as const, name: hop.name};
const exit = hops.at(-1);
return exit && exit.protocol !== 'trojan' && exit.protocol !== 'vless' ? {kind: 'exit' as const, name: exit.name} : null;
}
type ChainUpdate = {name: string; hops: string[]};
function chainText(text: string, next: ChainUpdate, renamedFrom: string | null) {
if (next.hops.length < 2 || next.hops.length > 4) throw new LocalError('nodes.proxyChain.hopCount');
if (!next.name || !isQuotable(next.name) || next.hops.some(hop => !hop || !isQuotable(hop))) throw new LocalError('config.unquotable');
if (next.name !== renamedFrom && [...readNodeEntries(text), ...readChainEntries(text)].some(entry => entry.name === next.name))
throw new LocalError('nodes.nameTaken');
return {name: quote(next.name), value: next.hops.map(quoteName).join(' -> ')};
}
// Replaces the chain's name and hops; a rename also rewrites what names the chain, as a node rename does.
export function writeChainEntry(text: string, original: ChainEntry, next: ChainUpdate): string {
const entry = currentChain(text, original);
const {name, value} = chainText(text, next, original.name);
const hops = next.hops.join('\n') !== entry.hops.map(hop => hop.name).join('\n') ? {from: entry.hopsFrom, to: entry.to, text: value} : null;
return rewriteEntry(text, original.name, next.name, {from: entry.from, to: entry.nameTo, text: name}, hops);
}
// Adds the chain at the end of the last `node {}` block, indented as that block's entries are, or in a new block; lines
// end as the file's do.
export function appendChainEntry(text: string, next: ChainUpdate): string {
const {name, value} = chainText(text, next, null);
const eol = text.includes('\r\n') ? '\r\n' : '\n';
const block = scanConfig(text)
.blocks.filter(block => block.name === 'node')
.at(-1);
if (!block) return `${text.trimEnd()}${text.trim() ? eol + eol : ''}node {${eol} ${name}: ${value}${eol}}${eol}`;
const indent = text.slice(block.open + 1, block.close).match(/\n([ \t]+)\S/)?.[1] ?? ' ';
const closeLine = text.lastIndexOf('\n', block.close - 1) + 1;
// A `}` after other text moves to a line of its own, and the space before it is dropped.
const [head, tail] = /^[ \t]*$/.test(text.slice(closeLine, block.close))
? [text.slice(0, closeLine), text.slice(closeLine)]
: [text.slice(0, block.close).trimEnd() + eol, text.slice(block.close)];
return `${head}${indent}${name}: ${value}${eol}${tail}`;
}
export function writeNodeEntry(text: string, original: NodeEntry, next: {name: string; link: string}): string {
const all = readNodeEntries(text);
const entries = all.filter(entry => entry.name === original.name);
@@ -137,9 +200,14 @@ export function writeNodeEntry(text: string, original: NodeEntry, next: {name: s
if (!next.name || !isQuotable(next.name) || !isNodeLink(next.link) || !isQuotable(next.link)) throw new LocalError('config.unquotable');
if (next.name !== original.name && all.some(entry => entry.name === next.name)) throw new LocalError('nodes.nameTaken');
const entry = entries[0];
const changes = [];
if (next.name !== original.name) changes.push({from: entry.from, to: entry.nameTo, text: quote(next.name)});
if (next.link !== original.link) changes.push({from: entry.linkFrom, to: entry.to, text: quote(next.link)});
if (next.name !== original.name) changes.push(...nameReferences(text, original.name).map(ref => ({...ref, text: quoteName(next.name)})));
const link = next.link !== original.link ? {from: entry.linkFrom, to: entry.to, text: quote(next.link)} : null;
return rewriteEntry(text, original.name, next.name, {from: entry.from, to: entry.nameTo, text: quote(next.name)}, link);
}
type Edit = {from: number; to: number; text: string};
// Writes an entry's value when it changed and its name when renamed, with every reference to the old name.
function rewriteEntry(text: string, from: string, to: string, name: Edit, value: Edit | null): string {
const changes = value ? [value] : [];
if (to !== from) changes.push(name, ...nameReferences(text, from).map(ref => ({...ref, text: quoteName(to)})));
return changes.sort((a, b) => b.from - a.from).reduce((out, change) => out.slice(0, change.from) + change.text + out.slice(change.to), text);
}
+1
View File
@@ -12,6 +12,7 @@ it.each([
['hysteria2', false, true, true],
['tuic', false, true, true],
['juicity', false, true, true],
['chain', false, true, true],
['direct', false, true, true],
['block', false, false, false],
['unknown', false, false, false],
+2
View File
@@ -12,6 +12,8 @@ const protocols: Record<string, {connect: boolean; stream: boolean; udp: boolean
hysteria2: {connect: false, stream: true, udp: true},
tuic: {connect: false, stream: true, udp: true},
juicity: {connect: false, stream: true, udp: true},
// A proxy chain has no server of its own to connect to; HTTP and DNS probes go through every hop.
chain: {connect: false, stream: true, udp: null},
direct: {connect: false, stream: true, udp: true},
block: {connect: false, stream: false, udp: false}
};
+80
View File
@@ -0,0 +1,80 @@
import {useT} from '../../i18n';
import {Button, TextField} from '../../ui/ui';
import {SearchSelect, type SearchItem} from '../../ui/SearchSelect';
import ChevronDown from '../../ui/icons/ChevronDown';
import Close from '../../ui/icons/Close';
import AddCircle from '../../ui/icons/AddCircle';
const chainHopLimits = {min: 2, max: 4};
// A proxy chain's name and its hops from entry to exit; the controller checks them and writes the chain.
export function ChainFields({
name,
nameError,
hops,
hopErrors,
choices,
isDisabled,
onName,
onHops
}: {
name: string;
nameError?: string;
hops: string[];
hopErrors: Array<string | null>;
choices: SearchItem[];
isDisabled?: boolean;
onName: (name: string) => void;
onHops: (hops: string[]) => void;
}) {
const t = useT();
const move = (from: number, to: number) => {
const next = [...hops];
[next[from], next[to]] = [next[to], next[from]];
onHops(next);
};
const without = (index: number) => hops.filter((_, i) => i !== index);
const fewest = hops.length <= chainHopLimits.min;
return (
<>
<span className="rp-label">{t('nodes.proxyChain.help')}</span>
<TextField error={nameError} isDisabled={isDisabled} label={t('ui.name')} value={name} onChange={onName} />
{hops.map((hop, index) => {
const n = index + 1;
const last = index === hops.length - 1;
return (
<SearchSelect
key={index}
label={t('nodes.proxyChain.hop', {n})}
searchLabel={t('nodes.search')}
placeholder={t('nodes.proxyChain.pickHop')}
sections={[{id: 'nodes', items: choices}]}
value={hop}
error={hopErrors[index]}
isDisabled={isDisabled}
onChange={value => onHops(hops.map((other, i) => (i === index ? value : other)))}
action={
<>
<Button quiet icon label={t('nodes.proxyChain.moveUp', {n})} isDisabled={isDisabled || index === 0} onPress={() => move(index, index - 1)}>
<ChevronDown className="rp-up" />
</Button>
<Button quiet icon label={t('nodes.proxyChain.moveDown', {n})} isDisabled={isDisabled || last} onPress={() => move(index, index + 1)}>
<ChevronDown />
</Button>
<Button quiet icon label={t('nodes.proxyChain.removeHop', {n})} isDisabled={isDisabled || fewest} onPress={() => onHops(without(index))}>
<Close />
</Button>
</>
}
/>
);
})}
<span className="rp-cluster">
<Button secondary isDisabled={isDisabled || hops.length >= chainHopLimits.max} onPress={() => onHops([...hops, ''])}>
<AddCircle />
{t('nodes.proxyChain.addHop')}
</Button>
</span>
</>
);
}
+19 -2
View File
@@ -33,6 +33,22 @@ import type {NodeTableView} from './useNodeTable';
// Probe controls read the running node without rebuilding the table rows or columns.
const ProbeBusy = createContext<string | null>(null);
// A proxy chain's hops and UDP, read by its details without rebuilding the rows.
const Chains = createContext<NodeTableView['chains']>(new Map());
function ChainFacts({id}: {id: string}) {
const t = useT();
const chain = useContext(Chains).get(id);
if (!chain) return null;
return (
<>
<div className="rp-list">
<span className="rp-label">{t('nodes.proxyChain.hops')}</span>
<Kv items={chain.hops.map(hop => [hop.label, <span className={hop.tone}>{hop.value}</span>])} />
</div>
<Kv items={[{label: t('nodes.proxyChain.udp'), value: chain.udp, wide: true}]} />
</>
);
}
function useProbeDisabled(row: NodeTableView['rows'][number]) {
return !!useContext(ProbeBusy) || !row.canProbe;
}
@@ -176,6 +192,7 @@ export function NodeTable({model: m}: {model: NodeTableView}) {
[t('act.latency'), row.latency]
]}
/>
<ChainFacts id={row.id} />
{/* The groups take a row of their own, so their tags wrap across the card instead of stretching
the facts above into a narrow column. */}
<div className="rp-list">
@@ -211,7 +228,7 @@ export function NodeTable({model: m}: {model: NodeTableView}) {
[settings, t]
);
return (
<>
<Chains.Provider value={m.chains}>
{m.probeOptions && <ProbeOptionsDialog model={m.probeOptions} />}
{m.writable && m.sourceTip && <p className="rp-note">{m.sourceTip}</p>}
{m.scope ? (
@@ -262,6 +279,6 @@ export function NodeTable({model: m}: {model: NodeTableView}) {
detail={detail}
/>
</ProbeBusy.Provider>
</>
</Chains.Provider>
);
}
+15 -4
View File
@@ -34,6 +34,7 @@ import {preloadable} from '../../ui/preloadable';
const xhttpOptions = preloadable<ComponentProps<typeof XhttpOptionsType>>(() => import('./XhttpOptions').then(module => ({default: module.XhttpOptions})));
const XhttpOptions = xhttpOptions.Component;
const ManualFields = lazy(() => import('./ManualFields').then(module => ({default: module.ManualFields})));
const ChainFields = lazy(() => import('./ChainFields').then(module => ({default: module.ChainFields})));
const SubscriptionFields = lazy(() => import('./SubscriptionFields').then(module => ({default: module.SubscriptionFields})));
const dialogForm = 'nodes-dialog-form';
export function Nodes(props: PageProps) {
@@ -60,6 +61,8 @@ export function Nodes(props: PageProps) {
setNodeLink,
addMode,
setAddMode,
chainCreate,
chain,
draft,
nodeValue,
setDraftField,
@@ -136,6 +139,11 @@ export function Nodes(props: PageProps) {
event.preventDefault();
if (formValid && !submitting) void submit(() => setDialog(null));
};
const chainFields = chain && (
<Suspense fallback={null}>
<ChainFields {...chain} isDisabled={pending} />
</Suspense>
);
const blocked = referenced && (
<span className="rp-label">
{referenced.text}
@@ -216,7 +224,7 @@ export function Nodes(props: PageProps) {
narrow
scrollBody={dialog?.kind === 'node'}
isOpen={dialog !== null && !removing}
reason={pending ? null : formReason}
reason={pending ? null : chain ? chain.reason : formReason}
onOpenChange={isOpen => {
if (!isOpen) setDialog(null);
}}
@@ -269,15 +277,17 @@ export function Nodes(props: PageProps) {
)}
</Form>
)}
{(dialog?.kind === 'node' || dialog?.kind === 'editNode') && (
{(dialog?.kind === 'node' || dialog?.kind === 'editNode' || dialog?.kind === 'editChain') && (
<Form id={dialogForm} className="rp-list" onSubmit={send}>
{dialog.kind === 'editNode' ? (
linkTab
) : dialog.kind === 'editChain' ? (
chainFields
) : (
<Tabs
label={t('nodes.addNode')}
value={addMode}
onChange={id => setAddMode(id === 'manual' ? 'manual' : 'link')}
onChange={id => setAddMode(id === 'manual' || id === 'chain' ? id : 'link')}
items={[
{id: 'link', label: t('nodes.manual.link'), content: <div className="rp-list">{linkTab}</div>},
{
@@ -297,7 +307,8 @@ export function Nodes(props: PageProps) {
</Suspense>
</div>
)
}
},
...(chainCreate ? [{id: 'chain', label: t('nodes.proxyChain.protocol'), content: <div className="rp-list">{chainFields}</div>}] : [])
]}
/>
)}
+8
View File
@@ -57,6 +57,14 @@ it.each([
{id: 'new', name: 'new', state: 'unmeasured'}
],
down: 1
},
{
// A group TCP connect probe finds no server address on a chain member: unmeasured, not down.
name: 'a chain member a group probe could not measure',
nodes: [node('relay', ['a'], [observation({measurement: 'tcp_connect', state: 'unavailable', latency_ms: null, error: 'no_node_address'})], 'chain')],
measured: [],
missing: [{id: 'relay', name: 'relay', state: 'unmeasured'}],
down: 0
}
])('summarizes $name', ({nodes, measured, missing, down}) => {
const summary = latencySummary(latencyGroups(nodes, [], 'group', locale));
+10 -2
View File
@@ -6,8 +6,8 @@ import type {SearchTarget} from '../../shell/routes';
// The tabs are read apart from the search targets, so the startup Skeleton does not load these.
export {nodesTabs};
// Where node sources are added and edited, for search: subscriptions on the sources list, share links and renames on
// the node list.
// Where node sources are added and edited, for search: subscriptions on the sources list, share links, renames and
// proxy chains on the node list.
export function nodesTargets(resources: Capabilities['resources'] | undefined): SearchTarget[] {
return [
...(offered(resources, 'providers', {whileLoading: false})
@@ -43,6 +43,14 @@ export function nodesTargets(resources: Capabilities['resources'] | undefined):
route: 'nodes',
params: {tab: 'list'},
aliases: ['share link', 'rename']
} as const,
{
id: 'nodes:proxy-chain',
titleKey: 'nodes.proxyChain.protocol',
parentKey: 'nav.nodes',
route: 'nodes',
params: {tab: 'list'},
aliases: ['chain', 'hop', 'relay']
} as const
]
: [])
+1
View File
@@ -36,6 +36,7 @@ const input: Parameters<typeof useNodeTable>[0] = {
nodes,
all: nodes,
sourceOf: () => 'inline',
chainHops: () => null,
providers: [],
names: new Map(),
loading: false,
+19 -4
View File
@@ -10,7 +10,7 @@ import type {OutboundNames} from '../../api/selectors';
import {cachedRows, toast, toastFailure, useLinked, type TableSort} from '../../ui/ui';
import {namedIn, type GroupEntry} from '../../dae/groups';
import type {MainSourceEdit} from '../../store/mainSource';
import {nodeRows, nodeRowView} from './view';
import {chainHopsView, nodeRows, nodeRowView, protocolText} from './view';
import {compareNames} from '../../i18n/format';
import {longList} from '../../ui/longList';
import type {SearchSection} from '../../ui/SearchSelect';
@@ -50,9 +50,11 @@ type NodeTableInput = {
// Whether the node's declaring source rules out removing it here.
inInclude: (node: Node) => boolean;
edit: (node: Node) => (() => void) | null;
// A proxy chain's hop names as its declaration lists them; null when it is not declared once.
chainHops: (node: Node) => string[] | null;
};
export function useNodeTable(input: NodeTableInput) {
const {names, providers, source, query, reload, joinGroup, onNewGroup, onRemove, canManage, sourceOf, edit, inInclude} = input;
const {names, providers, source, query, reload, joinGroup, onNewGroup, onRemove, canManage, sourceOf, edit, inInclude, all, chainHops} = input;
const t = useT();
const lang = useLang();
const locale = LOCALE[lang];
@@ -84,8 +86,8 @@ export function useNodeTable(input: NodeTableInput) {
[...new Set(nodes.map(node => node.protocol ?? ''))]
.filter(Boolean)
.sort(compareNames(locale))
.map(id => ({id, label: id})),
[nodes, locale]
.map(id => ({id, label: protocolText({protocol: id}, t)})),
[nodes, locale, t]
);
const linkedGroup =
input.groupQuery && !groups.some(item => item.id === input.groupQuery)
@@ -135,6 +137,17 @@ export function useNodeTable(input: NodeTableInput) {
}),
[names, lang, sourceOf, choices, runProbe, t, entries, onNewGroup, joinGroup, canManage, inlineProviders, onRemove, inInclude, edit]
);
// Apart from the rows, so a hop's health changing rebuilds only the chains' details.
const chains = useMemo(
() =>
new Map(
all.flatMap(node => {
const hops = node.protocol === 'chain' ? chainHops(node) : null;
return hops ? [[node.id, chainHopsView(hops, all, t)] as const] : [];
})
),
[all, chainHops, t]
);
const cache = useMemo(() => ({build, rows: new WeakMap<Node, NodeTableView['rows'][number]>()}), [build]);
const rows = useMemo(() => cachedRows(cache.rows, members, cache.build), [cache, members]);
const visible = useMemo(() => new Set(rows.map(row => row.id)), [rows]);
@@ -169,6 +182,7 @@ export function useNodeTable(input: NodeTableInput) {
};
return {
rows,
chains,
selection: {keys: selectedKeys, onChange: onSelectionChange},
clearSelection,
removeSelected,
@@ -242,6 +256,7 @@ export function useNodeTable(input: NodeTableInput) {
};
}
export type NodeTableView = {
chains: ReadonlyMap<string, ReturnType<typeof chainHopsView>>;
selection: {keys: Set<string>; onChange: (keys: Selection) => void};
clearSelection: () => void;
removeSelected: () => void;
+86 -10
View File
@@ -21,12 +21,24 @@ import {isWritableName, groupsNamingTag, readGroupEntries} from '../../dae/group
import {isQuotable, quote} from '../../dae/text';
import {agentProblem} from '../../dae/subscriptions';
import {engineOf} from '../../api/engines';
import {nodeReferrers, readChainEntries, readNodeEntries, removeChainEntry, writeNodeEntry, type NodeEntry} from '../../dae/nodes';
import {
appendChainEntry,
nodeReferrers,
readChainEntries,
readNodeEntries,
removeChainEntry,
writeChainEntry,
writeNodeEntry,
type ChainEntry,
type NodeEntry
} from '../../dae/nodes';
import {duplicateXhttpHeaders, readXhttp, writeXhttp, type XhttpChange, type XhttpFields} from '../../dae/xhttp';
import type {PageProps} from '../../shell/routes';
import {replaceRoute} from '../../shell/route';
import {
editableSource,
chainEditState,
chainHopChoices,
customGroup,
joinableOwners,
joinNodesToGroups,
@@ -71,6 +83,7 @@ type NodeDialog =
| {kind: 'provider'}
| {kind: 'node'}
| {kind: 'editNode'; source: ConfigSource; entry: NodeEntry}
| {kind: 'editChain'; source: ConfigSource; entry: ChainEntry}
| {kind: 'removeProvider'; item: Provider}
| {kind: 'removeNode'; item: Node}
| {kind: 'removeNodes'; items: Node[]; onRemoved: (id: string) => void}
@@ -86,10 +99,12 @@ export function useNodesPage({go, query}: PageProps) {
const t = useT();
const [dialog, setDialog] = useState<NodeDialog | null>(null);
const [form, setForm] = useState<ProviderForm>(blank);
// The add dialog takes a pasted link or the fields of a node; each tab keeps its input, and the link is what is added.
const [addMode, setAddMode] = useState<'link' | 'manual'>('link');
// The add dialog takes a pasted link, the fields of a node or a proxy chain's hops; each tab keeps its input.
const [addMode, setAddMode] = useState<'link' | 'manual' | 'chain'>('link');
const [draft, setDraft] = useState<NodeFields>(emptyNode);
const [hops, setHops] = useState<string[]>(['', '']);
const byFields = dialog?.kind === 'node' && addMode === 'manual';
const byChain = dialog?.kind === 'editChain' || (dialog?.kind === 'node' && addMode === 'chain');
const nodeValue = byFields ? manualLink(draft) : form.value;
const [headers, setHeaders] = useState<XhttpFields['headers'] | null>(null);
const xhttp = useMemo(() => readXhttp(nodeValue), [nodeValue]);
@@ -115,7 +130,9 @@ export function useNodesPage({go, query}: PageProps) {
? Object.values(changes).some(Boolean)
: dialog?.kind === 'editNode'
? form.name !== dialog.entry.name || form.value !== dialog.entry.link
: !!(form.name || form.value) || JSON.stringify(draft) !== JSON.stringify(emptyNode(draft.protocol));
: dialog?.kind === 'editChain'
? form.name !== dialog.entry.name || hops.join('\n') !== dialog.entry.hops.map(hop => hop.name).join('\n')
: !!(form.name || form.value) || hops.some(Boolean) || JSON.stringify(draft) !== JSON.stringify(emptyNode(draft.protocol));
const guard = useDraftGuard(
!!dialog && (edited || headerEdited),
() => {
@@ -132,6 +149,7 @@ export function useNodesPage({go, query}: PageProps) {
setJoinPick([]);
setAddMode('link');
setDraft(emptyNode());
setHops(next.kind === 'editChain' ? next.entry.hops.map(hop => hop.name) : ['', '']);
setBatchProgress(null);
setRefusedName(null);
setRefusedLink(null);
@@ -140,6 +158,7 @@ export function useNodesPage({go, query}: PageProps) {
if (next.kind === 'editProvider')
setForm({...blank, name: next.entry.tag, value: next.entry.url, agent: next.entry.ua ?? '', route: next.entry.route ?? ''});
if (next.kind === 'editNode') setForm({...blank, name: next.entry.name, value: next.entry.link});
if (next.kind === 'editChain') setForm({...blank, name: next.entry.name});
setDialog(next);
},
[session]
@@ -171,6 +190,7 @@ export function useNodesPage({go, query}: PageProps) {
const daeText = engineOf(version).daeText;
const parsed =
dialog?.kind === 'node' &&
!byChain &&
parseNodeLinks(
nodeValue,
(nodeList ?? []).map(node => node.name),
@@ -222,14 +242,29 @@ export function useNodesPage({go, query}: PageProps) {
.flatMap(source => readChainEntries(source.content).map(entry => ({source, entry}))),
[sources]
);
// A proxy chain is written as text: created in the main source, edited in the one source that declares it.
const mainSource = sources.find(item => item.kind === 'main');
const chainCreate = !!mainSource && editableSource(daeText, source.writable, mainSource, isComplete(mainSource));
const nodeEdit = useCallback(
(node: Node) => {
if (node.protocol === 'chain') {
const own = authoredChains.filter(item => item.entry.name === node.name);
if (own.length !== 1 || !editableSource(daeText, source.writable, own[0].source, isComplete(own[0].source))) return null;
return () => open({kind: 'editChain', ...own[0]});
}
const own = authored.filter(item => item.entry.name === node.name);
const inline = providers.data?.providers.some(provider => provider.id === node.provider_id && provider.kind === 'inline');
if (!inline || own.length !== 1 || !editableSource(daeText, source.writable, own[0].source, isComplete(own[0].source))) return null;
return () => open({kind: 'editNode', ...own[0]});
},
[authored, providers.data, daeText, source.writable, isComplete, open]
[authored, authoredChains, providers.data, daeText, source.writable, isComplete, open]
);
const chainHops = useCallback(
(node: Node) => {
const own = authoredChains.filter(item => item.entry.name === node.name);
return own.length === 1 ? own[0].entry.hops.map(hop => hop.name) : null;
},
[authoredChains]
);
// Every source on this page is written through the one shared editor, so its busy flag covers each declaring source.
const joinOwners = useMemo(() => joinableOwners(sources, isComplete, () => source.busy), [sources, isComplete, source.busy]);
@@ -439,6 +474,27 @@ export function useNodesPage({go, query}: PageProps) {
}
toast('positive', t('nodes.added', {name}), {action: viewNodes(created.id)});
return;
} else if (byChain) {
const current = sources.find(item => item.id === (dialog.kind === 'editChain' ? dialog.source.id : mainSource?.id));
if (!current || !current.writable || isComplete(current) !== true) {
refuse(t('nodes.editNodeMissing'));
return;
}
const next = {name: form.name.trim(), hops};
const result = await apply(text => (dialog.kind === 'editChain' ? writeChainEntry(text, dialog.entry, next) : appendChainEntry(text, next)), current);
const problem = editProblem(result, sources, t);
if (problem) refuseNotice(problem);
if (result.kind !== 'ok') return;
reload();
const joined = dialog.kind === 'node' ? await joinPickedGroups([next.name]) : 'none';
if (joined !== 'failed')
toast(
'positive',
t(dialog.kind === 'editChain' ? 'nodes.edited' : joined === 'ok' ? 'nodes.addedJoined' : 'nodes.added', {
name: next.name,
groups: formatList(lang, joinPicked)
})
);
} else if (dialog.kind === 'node' && batch) {
const remaining = new Map(batch.rows.map(row => [row.id, row.link]));
const valid = batch.rows.filter(row => !row.error);
@@ -605,8 +661,8 @@ export function useNodesPage({go, query}: PageProps) {
? t('nodes.addProvider')
: dialog.kind === 'node'
? t('nodes.addNode')
: dialog.kind === 'editNode'
? t('nodes.editNodeTitle', {name: dialog.entry.name})
: dialog.kind === 'editNode' || dialog.kind === 'editChain'
? t(dialog.kind === 'editNode' ? 'nodes.editNodeTitle' : 'nodes.proxyChain.editTitle', {name: dialog.entry.name})
: dialog.kind === 'editProvider'
? t('nodes.editProviderTitle', {name: dialog.entry.tag})
: dialog.kind === 'removeNodes'
@@ -628,6 +684,8 @@ export function useNodesPage({go, query}: PageProps) {
const checkingRemoval = removal.checking;
const referrers = dialog?.kind === 'removeNode' ? referrersOf(dialog.item.name) : null;
const nodeState = dialog?.kind === 'editNode' ? nodeEditState(sources, dialog.source, dialog.entry, nodeList ?? [], form, t) : null;
const chainState = byChain ? chainEditState(sources, dialog?.kind === 'editChain' ? dialog : null, nodeList ?? [], {name: form.name, hops}, t) : null;
const hopChoices = useMemo(() => chainHopChoices(nodeList ?? [], t), [nodeList, t]);
const nodeNameError =
nodeState?.nameError ??
(dialog?.kind === 'node' && newName && (refusedName === newName || nodeList?.some(node => node.name === newName)) ? t('nodes.nameTaken') : null) ??
@@ -639,7 +697,7 @@ export function useNodesPage({go, query}: PageProps) {
? t('nodes.linkInvalid')
: nodeLinkError(nodeValue, t, engineOf(version).nodeLinkSchemes)
: (nodeState?.linkError ?? null);
const formValid = batch
const nodeFormValid = batch
? !batch.error && batch.rows.some(row => !row.error)
: dialog?.kind === 'editNode'
? nodeState!.valid && !headerError
@@ -652,6 +710,7 @@ export function useNodesPage({go, query}: PageProps) {
: dialog?.kind === 'removeNodes'
? removeNodes.length > 0
: true;
const formValid = chainState ? chainState.valid : nodeFormValid;
const subscription: SubscriptionDraft = {name: form.name, url: form.value, interval: form.interval, agent: form.agent, cache: form.cache, route: form.route};
// A new subscription shows each option the backend lists, with its default preselected or as the placeholder; an
// edit writes the options in the declaring source.
@@ -723,7 +782,8 @@ export function useNodesPage({go, query}: PageProps) {
onRemove: removeNode,
onRemoveSelected: removeSelectedNodes,
inInclude: nodeInInclude,
edit: nodeEdit
edit: nodeEdit,
chainHops
});
const tabs = nodesTabs(resources);
return {
@@ -771,6 +831,22 @@ export function useNodesPage({go, query}: PageProps) {
setAddMode: (next: typeof addMode) => {
if (submitting.current !== dialog) setAddMode(next);
},
chainCreate,
chain: chainState && {
name: form.name,
// A new chain's empty name waits for the footer's reason, as a pasted link's does.
nameError: (form.name || dialog?.kind === 'editChain' ? chainState.nameError : null) ?? undefined,
hops,
hopErrors: chainState.hopErrors,
reason: chainState.reason,
choices: hopChoices,
onName: (name: string) => {
if (submitting.current !== dialog) setForm({...form, name});
},
onHops: (next: string[]) => {
if (submitting.current !== dialog) setHops(next);
}
},
draft,
nodeValue,
setDraftField: (key: string, value: string) => {
@@ -820,7 +896,7 @@ export function useNodesPage({go, query}: PageProps) {
? dialog.kind === 'removeNodes'
? t('nodes.deleteSelected', {n: removeNodes.length})
: t('nodes.remove', {name: dialog.item.name})
: dialog?.kind === 'editProvider' || dialog?.kind === 'editNode'
: dialog?.kind === 'editProvider' || dialog?.kind === 'editNode' || dialog?.kind === 'editChain'
? t('policy.save')
: t('nodes.add')),
editOptions: subscriptionEdit.options,
+56 -1
View File
@@ -2,6 +2,9 @@ import {describe, expect, it} from 'vitest';
import type {ConfigSource, Node, Provider} from '../../api/model';
import {readSubscriptionEntries} from '../../dae/subscriptions';
import {
chainEditState,
chainHopChoices,
chainHopsView,
nodeFormReason,
editableSource,
declaredInInclude,
@@ -26,7 +29,7 @@ import {
subscriptionNameError
} from './view';
import {translate, type Translator} from '../../i18n';
import {readNodeEntries} from '../../dae/nodes';
import {readChainEntries, readNodeEntries} from '../../dae/nodes';
import {readGroupEntries} from '../../dae/groups';
import {createMockApi} from '../../../mock';
import {nodeFixtures} from '../../../mock/fixtures';
@@ -798,3 +801,55 @@ it.each([
])('offers a group to join only if it is custom: %s', (_, filters, expected) => {
expect(customGroup({filters})).toBe(expected);
});
describe('proxy chains', () => {
const {nodes} = nodeFixtures(0);
const [relay] = readChainEntries(main.content);
const original = {source: main, entry: relay};
const draft = {name: 'relay', hops: ['jp-01', 'hk-02']};
it.each([
['an unchanged chain', original, draft, {valid: false, reason: null}],
['a new exit', original, {...draft, hops: ['jp-01', 'sg-01']}, {valid: true, reason: null}],
['a taken name', original, {...draft, name: 'hk-02'}, {valid: false, nameError: t('nodes.nameTaken')}],
['an empty hop', null, {name: 'new', hops: ['hk-01', '']}, {valid: false, hopErrors: [null, null], reason: t('nodes.proxyChain.hopEmpty')}],
['a later entry-only hop', null, {name: 'new', hops: ['hk-01', 'us-01']}, {valid: false, hopErrors: [null, t('ui.backend.unsupportedChainHop')]}],
['a later XHTTP hop', null, {name: 'new', hops: ['us-01', 'jp-01']}, {valid: false, hopErrors: [null, t('ui.backend.unsupportedChainHop')]}],
['a missing hop', original, {...draft, hops: ['gone', 'hk-02']}, {valid: false, hopErrors: [t('ui.backend.invalidChainHopReference'), null]}],
['a new chain', null, {name: 'new', hops: ['us-01', 'hk-01', 'sg-01']}, {valid: true, reason: null}]
])('checks %s', (_, from, next, state) => {
expect(chainEditState([main], from, nodes, next, t)).toMatchObject(state);
});
it('lists each hop with its protocol and latency, and what decides UDP', () => {
const twice = [...nodes, node('hk-01', {protocol: 'ss'})];
expect(chainHopsView(['hk-01', 'sg-01'], nodes, t)).toMatchObject({
hops: [
{label: 'hk-01', value: 'vless (TCP) (84 ms)'},
{label: 'sg-01', value: 'trojan (TCP) (63 ms)'}
],
udp: t('nodes.proxyChain.udpDepends')
});
expect(chainHopsView(['us-01', 'sg-01'], nodes, t).udp).toBe('No (us-01 cannot be dialed through another hop)');
expect(chainHopsView(['sg-01', 'ss-01'], [...nodes, node('ss-01', {protocol: 'ss'})], t).udp).toBe('No (the exit ss-01 is not Trojan or VLESS)');
expect(chainHopsView(['gone', 'hk-01'], twice, t)).toMatchObject({
hops: [
{value: t('ui.backend.invalidChainHopReference'), tone: 'ms err'},
{value: t('ui.backend.ambiguousChainHopReference'), tone: 'ms err'}
],
udp: '—'
});
});
it('offers every node but chains once by name, disabling shared and unquotable names', () => {
const choices = chainHopChoices([...nodes, node('hk-01'), node("it's"), node('direct', {protocol: 'direct'})], t);
expect(choices.map(choice => [choice.id, !!choice.isDisabled])).toEqual([
['hk-01', true],
['hk-02', false],
['sg-01', false],
['jp-01', false],
['us-01', false],
["it's", true]
]);
expect(choices[2].desc).toBe('trojan (TCP)');
});
});
+90 -10
View File
@@ -1,4 +1,3 @@
import {isNodeLink} from '../../dae/nodes';
import type {Capabilities, ConfigSource, HealthObservation, Node, Provider, ProviderCreate} from '../../api/model';
import {enumLabel} from '../../i18n/enum';
import {
@@ -13,6 +12,7 @@ import {
type PseudoOwner
} from '../../api/selectors';
import type {TableSort} from '../../ui/ui';
import type {SearchItem} from '../../ui/SearchSelect';
import {completeSubscriptionUrl, isSubscriptionUrl, urlHost, type SubscriptionOption, type SubscriptionText} from '../../dae/subscriptions';
import {formatList, formatNumber, type Lang, type Translator} from '../../i18n';
import type {Key} from '../../i18n';
@@ -22,7 +22,17 @@ import {compareNames, localMinute, localTime, formatBytes, formatBytesFraction,
import {backendCode, backendMessage, knownCode, oneLine} from '../../i18n/backend';
import {latencyTone} from '../../ui/ui';
import {isQuotable} from '../../dae/text';
import {nodeReferenced, readChainEntries, readNodeEntries, type NodeEntry} from '../../dae/nodes';
import {
chainHopCandidate,
chainHopProblem,
chainUdpProblem,
isNodeLink,
nodeReferenced,
readChainEntries,
readNodeEntries,
type ChainEntry,
type NodeEntry
} from '../../dae/nodes';
import {
addNodesToGroup,
citingGroups,
@@ -47,15 +57,21 @@ const streamTransportLabels = new Map([
['xhttp', 'XHTTP']
]);
// A proxy chain by its kind's name; another node by its protocol and stream transport.
export function protocolText(node: Pick<Node, 'protocol' | 'stream_transport'>, t: Translator) {
if (node.protocol === 'chain') return t('nodes.proxyChain.protocol');
const protocol = node.protocol ?? '—';
const transport = node.stream_transport;
return transport ? t('ui.aside', {text: protocol, note: streamTransportLabels.get(transport) ?? transport}) : protocol;
}
export function nodeRowView(node: Node, names: OutboundNames, lang: Lang, t: Translator) {
const latency = healthView(preferredHealth(node), t);
const kinds = probeKindLines(node, t);
const protocol = node.protocol ?? '—';
const transport = node.stream_transport;
return {
id: node.id,
name: node.name,
protocol: transport ? t('ui.aside', {text: protocol, note: streamTransportLabels.get(transport) ?? transport}) : protocol,
protocol: protocolText(node, t),
latency: latency.value,
latencyClass: latency.tone,
groups: node.group_ids.length
@@ -91,6 +107,66 @@ export function probeKindLines(node: Pick<Node, 'health'>, t: Translator) {
});
}
// A chain's hops from entry to exit, each with the protocol and latency of the node it names, and what decides UDP.
export function chainHopsView(hops: readonly string[], nodes: readonly Node[], t: Translator) {
const found = hops.map(name => nodes.filter(node => node.name === name));
const lines = hops.map((name, i) => {
const [node, ...more] = found[i];
if (!node || more.length)
return {label: name, value: backendCode(node ? 'ambiguous-chain-hop-reference' : 'invalid-chain-hop-reference', t), tone: 'ms err'};
const health = healthView(preferredHealth(node), t);
return {
label: name,
value: health.value === '—' ? protocolText(node, t) : t('ui.aside', {text: protocolText(node, t), note: health.value}),
tone: health.tone
};
});
const resolved = found.every(matches => matches.length === 1) ? found.map(([node]) => node) : null;
const udp = resolved && chainUdpProblem(resolved);
return {
hops: lines,
udp: !resolved
? '—'
: udp
? t('ui.aside', {text: t('ui.no'), note: t(udp.kind === 'hop' ? 'nodes.proxyChain.udpHop' : 'nodes.proxyChain.udpExit', {name: udp.name})})
: t('nodes.proxyChain.udpDepends')
};
}
// The nodes a hop can name, once per name: a name several nodes share, or one a hop cannot write, is listed but disabled.
export function chainHopChoices(nodes: readonly Node[], t: Translator): SearchItem[] {
const byName = new Map<string, Node[]>();
for (const node of nodes.filter(chainHopCandidate)) byName.set(node.name, [...(byName.get(node.name) ?? []), node]);
return [...byName].map(([name, [node, ...more]]) => {
const problem = more.length ? backendCode('ambiguous-chain-hop-reference', t) : !isQuotable(name) ? t('nodes.proxyChain.unquotable') : null;
return {id: name, label: name, nodeName: true, desc: problem ?? protocolText(node, t), isDisabled: !!problem};
});
}
export type ChainDraft = {name: string; hops: string[]};
// The chain dialog's checks, as far as the catalog shows them; honk's own check reports the rest when it writes.
export function chainEditState(
sources: ConfigSource[],
original: {source: ConfigSource; entry: ChainEntry} | null,
nodes: Node[],
draft: ChainDraft,
t: Translator
) {
const name = draft.name.trim();
const {nameError, blocked} = nameState(sources, original?.source ?? null, original?.entry.name ?? null, name, nodes, t);
const hopErrors = draft.hops.map((hop, i) => {
const code = hop ? chainHopProblem(nodes, hop, i) : null;
return code && backendCode(code, t);
});
const reason =
nameError ??
hopErrors.find(Boolean) ??
(draft.hops.some(hop => !hop) ? t('nodes.proxyChain.hopEmpty') : null) ??
(blocked ? t('nodes.renameElsewhere') : null);
const changed = !original || name !== original.entry.name || draft.hops.join('\n') !== original.entry.hops.map(hop => hop.name).join('\n');
return {nameError, hopErrors, reason, valid: reason === null && changed};
}
export type ProviderRow = (Provider | (Omit<Provider, 'kind'> & {kind: 'builtin' | 'unattributed'})) & {
displayName?: string;
sourceTag?: string;
@@ -131,10 +207,10 @@ export function subscriptionPlace(places: Array<{source: ConfigSource; entry: Su
};
}
export function nodeEditState(sources: ConfigSource[], source: ConfigSource, entry: NodeEntry, nodes: Node[], form: ProviderForm, t: Translator) {
const name = form.name.trim();
const renamed = name !== entry.name;
const blocked = renamed && sources.some(item => item.id !== source.id && nodeReferenced(item.content, entry.name));
// A new or changed name: free among the nodes and declarations, and, when renaming, named in no other source.
function nameState(sources: ConfigSource[], source: ConfigSource | null, from: string | null, name: string, nodes: Node[], t: Translator) {
const renamed = name !== from;
const blocked = renamed && from !== null && sources.some(item => item.id !== source?.id && nodeReferenced(item.content, from));
const taken =
renamed &&
(nodes.some(node => node.name === name) ||
@@ -143,7 +219,11 @@ export function nodeEditState(sources: ConfigSource[], source: ConfigSource, ent
(item.kind === 'main' || item.kind === 'include') &&
[...readNodeEntries(item.content), ...readChainEntries(item.content)].some(entry => entry.name === name)
));
const nameError = !name ? t('nodes.nameMissing') : taken ? t('nodes.nameTaken') : !isQuotable(name) ? t('config.unquotable') : null;
return {blocked, nameError: !name ? t('nodes.nameMissing') : taken ? t('nodes.nameTaken') : !isQuotable(name) ? t('config.unquotable') : null};
}
export function nodeEditState(sources: ConfigSource[], source: ConfigSource, entry: NodeEntry, nodes: Node[], form: ProviderForm, t: Translator) {
const {nameError, blocked} = nameState(sources, source, entry.name, form.name.trim(), nodes, t);
const linkError = nodeLinkError(form.value, t) ?? (!form.value.trim() ? t('nodes.linkInvalid') : null);
const reason = nameError ?? linkError ?? (blocked ? t('nodes.renameElsewhere') : null);
return {
@@ -194,7 +194,7 @@ it('turns every-node off to an empty set or the remaining selections', () => {
expect(off).toEqual([noNodes]);
expect(nodes.filter(compileFilters(off)).map(node => node.name)).toEqual([]);
expect(includesEveryNode(off)).toBe(false);
expect(nodes.filter(compileFilters(setEveryNode(off, true))).map(node => node.name)).toEqual(['hk-01', 'hk-02', 'sg-01', 'jp-01', 'us-01']);
expect(nodes.filter(compileFilters(setEveryNode(off, true))).map(node => node.name)).toEqual(['hk-01', 'hk-02', 'sg-01', 'jp-01', 'us-01', 'relay']);
}
const off = setEveryNode(['!name(direct, block)', hk], false);
expect(nodes.filter(compileFilters(off)).map(node => node.name)).toEqual(['hk-01', 'hk-02']);
+3 -1
View File
@@ -56,7 +56,9 @@ beforeEach(() => {
it.each([
['positive', rows('unavailable', 'healthy')],
['negative', rows('unavailable', 'unknown')],
['neutral', rows('unknown')]
['neutral', rows('unknown')],
// A chain member's row from a TCP connect probe measured nothing, so it does not make the probe a failure.
['neutral', rows('unavailable', 'unknown').map((row, i) => (i ? row : {...row, error: 'no_node_address'}))]
])('reports the group probe as %s by its best member', async (level, results) => {
state.result = {
target: {type: 'group', group_id: group.id},
+2 -2
View File
@@ -15,7 +15,7 @@ import type {OutboundCatalogue} from '../shared/groupText';
import {useCheckEdit} from './useCheckEdit';
import {toast} from '../../ui/ui';
import {failureNotice, requestIdOf} from '../../api/error';
import {foldFamilies} from '../../api/selectors';
import {foldFamilies, measured} from '../../api/selectors';
import {selectMember} from '../shared/selectMember';
import {featureLink} from '../shared/limitHint';
import {readFold, saveFold} from './folds';
@@ -146,7 +146,7 @@ export function usePolicyGroup(input: PolicyGroupInput) {
void control.probe(options).then(result => {
if (result && g) {
toast(
probeLevel(foldFamilies(result.results)),
probeLevel(foldFamilies(result.results.filter(measured))),
t('ui.valuePair', {label: g.name, value: probeSummary(result, t, lang)}) + probeFallbackNotice(result.fallback, g.name, t)
);
}
+3 -1
View File
@@ -258,7 +258,9 @@ it('counts each probed member once, by the row that says most', () => {
row('a', 'ipv6', 'unknown'),
row('b', 'ipv6', 'unknown'),
row('b', 'ipv4', 'unavailable'),
row('c', 'ipv4', 'unknown')
row('c', 'ipv4', 'unknown'),
// A chain member has no server address for a TCP connect probe; that row measured nothing.
{...row('d', 'ipv4', 'unavailable'), error: 'no_node_address'}
]
} as unknown as Parameters<typeof probeSummary>[0]);
expect(summary).toBe('Available: 1, unavailable: 1, unknown: 1 (1 unresolved), selection: unchanged');
+2 -2
View File
@@ -3,7 +3,7 @@ import {compareNames} from '../../i18n/format';
import {enumLabel} from '../../i18n/enum';
import type {Group, HealthObservation, JsonPatch, Node, ProbeResult, Provider} from '../../api/model';
import type {Key} from '../../i18n';
import {compareLatency, foldFamilies, healthMillis, safeHttpUrl, type MessageRef} from '../../api/selectors';
import {compareLatency, foldFamilies, healthMillis, measured, safeHttpUrl, type MessageRef} from '../../api/selectors';
import {groupPolicyText} from '../shared/policyText';
import {formatList, formatNumber, type Lang, type Translator} from '../../i18n';
import type {Help, NodeStatus, KvItem} from '../../ui/ui';
@@ -115,7 +115,7 @@ const unknownReasons = new Map<string | null, Key>([
// of the row that decided its state.
export function probeSummary(result: ProbeResult, t: Translator, lang: Lang): string {
const rows = new Map<string, ProbeResult['results']>();
for (const item of result.results) rows.set(item.member_id, [...(rows.get(item.member_id) ?? []), item]);
for (const item of result.results.filter(measured)) rows.set(item.member_id, [...(rows.get(item.member_id) ?? []), item]);
const folded = [...rows.values()].map(items => foldFamilies(items));
const states = folded.map(row => row?.state);
const unknown = folded.filter(row => row?.state === 'unknown').map(row => unknownReasons.get(row!.error) ?? 'policy.probeReason.other');
+5 -5
View File
@@ -73,10 +73,10 @@ it('offers edits only at writable sources and preserves source locations when pa
const api = createMockApi();
const [rules, config, flows, groups] = await Promise.all([api.rules(), api.config(), api.flows(), api.groups()]);
const first = rules.rules[0];
expect(first.source).toMatchObject({source_id: 'src-main', line: 149, column: 3});
expect(first.source).toMatchObject({source_id: 'src-main', line: 150, column: 3});
const view = dictionaryView(rules.rules, rules.generation_id, flows, config.sources, groups, t, 'en');
expect(view.rows[0].position).toBe('config.dae:149');
expect(view.rows[0].sourceQuery).toBe('tab=source&source=src-main&line=149');
expect(view.rows[0].position).toBe('config.dae:150');
expect(view.rows[0].sourceQuery).toBe('tab=source&source=src-main&line=150');
expect(view.positions[0].id).toBe('end');
expect(view.rows.at(-1)?.number).toBe('—');
expect(view.rows.at(-1)?.removable).toBe(false);
@@ -243,7 +243,7 @@ it('does not infer a source from its display name when the ID is unknown', async
const explicit = {...rule, rule_id: 'explicit', source: {...rule.source!, file: 'config.dae', source_id: 'b'}};
const view = dictionaryView([unknown, explicit], undefined, undefined, sources, [], t, 'en');
expect(view.rows[0]).toMatchObject({sourceQuery: null, removable: false});
expect(view.rows[1]).toMatchObject({sourceQuery: 'tab=source&source=b&line=149', removable: true});
expect(view.rows[1]).toMatchObject({sourceQuery: 'tab=source&source=b&line=150', removable: true});
});
it('tips why a rule cannot be added: no writable place first, then a change still being applied', () => {
@@ -325,7 +325,7 @@ it('lists DNS request and response rules with their actions, locations and inser
'qname(geosite: cn)',
'fallback: cloudflare'
]);
expect(request.rows[0]).toMatchObject({number: '1', position: 'config.dae:29', removable: true, hits: '—', must: false});
expect(request.rows[0]).toMatchObject({number: '1', position: 'config.dae:30', removable: true, hits: '—', must: false});
expect(request.rows.at(-1)).toMatchObject({number: '—', removable: false});
expect(request.positions.map(position => position.id)).toEqual(['end', ...dns.request.slice(0, -1).map(rule => rule.rule_id)]);
// A request rule sends the query to an upstream or answers it itself; a response rule never sends it as is.
+4 -1
View File
@@ -80,7 +80,10 @@ const known: Record<string, Key> = {
quic_probe_disabled: 'ui.backend.quicProbeDisabled',
// Codes honk sets on config diagnostics.
'legacy-config-warning': 'ui.backend.legacyConfigWarning',
'duplicate-subscription-entry': 'ui.backend.duplicateSubscriptionEntry'
'duplicate-subscription-entry': 'ui.backend.duplicateSubscriptionEntry',
'invalid-chain-hop-reference': 'ui.backend.invalidChainHopReference',
'ambiguous-chain-hop-reference': 'ui.backend.ambiguousChainHopReference',
'unsupported-chain-hop': 'ui.backend.unsupportedChainHop'
};
const configurationRefusals = new Set(['permission_denied', 'capability_not_supported', 'temporarily_unavailable', 'invalid_request']);
+20
View File
@@ -1133,6 +1133,23 @@
"nodes.probed": "{name}: {n} ms",
"nodes.provider": "Node source",
"nodes.providers": "Node sources",
"nodes.proxyChain.addHop": "Add hop",
"nodes.proxyChain.editTitle": "Edit proxy chain {name}",
"nodes.proxyChain.help": "Choose 2 to 4 nodes, from entry to exit. Hysteria2, TUIC, Juicity and AnyTLS can only be the entry. Later hops must be SOCKS5, Shadowsocks, Trojan, or VMess or VLESS without XHTTP.",
"nodes.proxyChain.hop": "Hop {n}",
"nodes.proxyChain.hopCount": "A proxy chain has 2 to 4 hops.",
"nodes.proxyChain.hopEmpty": "Choose a node for every hop",
"nodes.proxyChain.hops": "Hops, entry to exit",
"nodes.proxyChain.moveDown": "Move hop {n} down",
"nodes.proxyChain.moveUp": "Move hop {n} up",
"nodes.proxyChain.pickHop": "Choose a node",
"nodes.proxyChain.protocol": "Proxy chain",
"nodes.proxyChain.removeHop": "Remove hop {n}",
"nodes.proxyChain.udp": "UDP",
"nodes.proxyChain.udpDepends": "Depends on node settings",
"nodes.proxyChain.udpExit": "the exit {name} is not Trojan or VLESS",
"nodes.proxyChain.udpHop": "{name} cannot be dialed through another hop",
"nodes.proxyChain.unquotable": "Name contains an apostrophe",
"nodes.referenced": "Groups that filter on {name}: {groups}. Change their filters on the Policies page first.",
"nodes.referencedBy": "Still used by {names}. Change those references before removing {name}.",
"nodes.referrerDns": "DNS upstream {name}",
@@ -2151,6 +2168,7 @@
"ui.average": "Average",
"ui.back": "Back",
"ui.backend.activationUnconfirmed": "The backend could not confirm whether the configuration is active",
"ui.backend.ambiguousChainHopReference": "Several nodes share this proxy chain hop's name",
"ui.backend.assetTooLarge": "The downloaded file exceeds the size limit",
"ui.backend.assetValidationFailed": "The new geodata file failed validation: it could not be read or lacks categories the rules use. The current files are kept",
"ui.backend.authenticationRequired": "Authentication required",
@@ -2171,6 +2189,7 @@
"ui.backend.httpStatusRejected": "The server returned an HTTP status other than 200 or 404. Check the URL",
"ui.backend.idempotencyConflict": "Idempotency key conflicts with the original request",
"ui.backend.interfaceWatcherDisabled": "The interface watcher is not running, so interface changes apply after a restart",
"ui.backend.invalidChainHopReference": "No node has this proxy chain hop's name",
"ui.backend.invalidCredentials": "Invalid credentials",
"ui.backend.invalidRequest": "Invalid request",
"ui.backend.invalidSource": "No usable download URL: the list is empty or a URL is malformed. Check the sources",
@@ -2217,6 +2236,7 @@
"ui.backend.temporarilyUnavailable": "Backend temporarily unavailable",
"ui.backend.tlsFailed": "The TLS handshake with the server failed. Check the URL and the system clock, or use another route",
"ui.backend.udpTraceUnavailable": "Kernel UDP tracing is unavailable, so recorded UDP flows may lack kernel route details",
"ui.backend.unsupportedChainHop": "This node cannot be a proxy chain hop at this position",
"ui.backend.unsupportedMediaType": "Unsupported media type",
"ui.backend.unsupportedValue": "Unsupported value",
"ui.backendMessage": "Backend message: {message}",
+22 -2
View File
@@ -878,7 +878,7 @@
"nodes.edit": "编辑 {name}",
"nodes.editAction": "编辑…",
"nodes.editMissing": "配置文件中已找不到此订阅",
"nodes.editNodeHelp": "更新来源中的节点链接。重命名时,同时更新同一来源中的精确节点筛选、default、final、exit 和代理链各跳。",
"nodes.editNodeHelp": "更新来源中的节点链接。重命名时,同步更新同一来源中的精确节点筛选、default、final、exit 和代理链跃点。",
"nodes.editNodeMissing": "来源中的节点已移除,或分享链接已更改。",
"nodes.editNodeTitle": "编辑节点 {name}",
"nodes.editOptions": "其他选项(保持原样)",
@@ -980,8 +980,25 @@
"nodes.probed": "{name}:{n} ms",
"nodes.provider": "节点来源",
"nodes.providers": "节点来源",
"nodes.proxyChain.addHop": "添加跃点",
"nodes.proxyChain.editTitle": "编辑代理链 {name}",
"nodes.proxyChain.help": "从入口至出口依次选择 2 至 4 个节点。Hysteria2、TUIC、Juicity 和 AnyTLS 仅能作为入口。其后的跃点须为 SOCKS5、Shadowsocks、Trojan,或未使用 XHTTP 的 VMess、VLESS。",
"nodes.proxyChain.hop": "跃点 {n}",
"nodes.proxyChain.hopCount": "代理链须包含 2 至 4 个跃点。",
"nodes.proxyChain.hopEmpty": "每个跃点均须选择节点",
"nodes.proxyChain.hops": "跃点(入口至出口)",
"nodes.proxyChain.moveDown": "下移跃点 {n}",
"nodes.proxyChain.moveUp": "上移跃点 {n}",
"nodes.proxyChain.pickHop": "选择节点",
"nodes.proxyChain.protocol": "代理链",
"nodes.proxyChain.removeHop": "移除跃点 {n}",
"nodes.proxyChain.udp": "UDP",
"nodes.proxyChain.udpDepends": "取决于节点设置",
"nodes.proxyChain.udpExit": "出口 {name} 不是 Trojan 或 VLESS",
"nodes.proxyChain.udpHop": "{name} 不支持经由其他跃点建立连接",
"nodes.proxyChain.unquotable": "名称含单引号",
"nodes.referenced": "按 {name} 筛选节点的组:{groups}。请先在策略页修改这些筛选条件。",
"nodes.referencedBy": "{names} 仍在使用 {name}。请先修改这些引用,再移除。",
"nodes.referencedBy": "{names} 仍引用 {name}。请先修改这些引用,再移除该节点。",
"nodes.referrerDns": "DNS 上游 {name}",
"nodes.refresh": "更新 {name}",
"nodes.refreshFailed": "无法更新 {name}",
@@ -1935,6 +1952,7 @@
"ui.average": "平均",
"ui.back": "返回",
"ui.backend.activationUnconfirmed": "后端无法确认配置是否已生效",
"ui.backend.ambiguousChainHopReference": "多个节点与此代理链跃点同名",
"ui.backend.assetTooLarge": "下载的文件超过大小上限",
"ui.backend.assetValidationFailed": "新的地理数据文件未通过校验:文件无法解析,或缺少规则使用的分类。已沿用当前的文件",
"ui.backend.authenticationRequired": "需要验证身份",
@@ -1955,6 +1973,7 @@
"ui.backend.httpStatusRejected": "服务器返回了非 200 或 404 的 HTTP 状态码。请检查网址",
"ui.backend.idempotencyConflict": "重复请求与原请求冲突",
"ui.backend.interfaceWatcherDisabled": "接口监视未运行,接口变更需重启后生效",
"ui.backend.invalidChainHopReference": "找不到与此代理链跃点同名的节点",
"ui.backend.invalidCredentials": "凭据无效",
"ui.backend.invalidRequest": "请求内容无效",
"ui.backend.invalidSource": "没有可用的下载网址:列表为空或网址格式有误。请检查来源",
@@ -2001,6 +2020,7 @@
"ui.backend.temporarilyUnavailable": "后端暂时不可用",
"ui.backend.tlsFailed": "与服务器的 TLS 握手失败。请检查网址与系统时间,或改用其他下载路由",
"ui.backend.udpTraceUnavailable": "内核 UDP 跟踪不可用,记录的 UDP 流程可能缺少内核路由信息",
"ui.backend.unsupportedChainHop": "此节点不可作为代理链中此位置的跃点",
"ui.backend.unsupportedMediaType": "不支持此媒体类型",
"ui.backend.unsupportedValue": "不支持此设置值",
"ui.backendMessage": "后端消息:{message}",
+22 -2
View File
@@ -878,7 +878,7 @@
"nodes.edit": "編輯 {name}",
"nodes.editAction": "編輯…",
"nodes.editMissing": "設定檔中已找不到此訂閱",
"nodes.editNodeHelp": "更新來源中的節點連結。重新命名時,一併更新同一來源中的精確節點篩選、default、final、exit 與代理鏈各跳。",
"nodes.editNodeHelp": "更新來源中的節點連結。重新命名時,同步更新同一來源中的精確節點篩選、default、final、exit 與代理鏈跳點。",
"nodes.editNodeMissing": "來源中的節點已移除,或分享連結已變更。",
"nodes.editNodeTitle": "編輯節點 {name}",
"nodes.editOptions": "其他選項(保持原樣)",
@@ -980,8 +980,25 @@
"nodes.probed": "{name}:{n} ms",
"nodes.provider": "節點來源",
"nodes.providers": "節點來源",
"nodes.proxyChain.addHop": "新增跳點",
"nodes.proxyChain.editTitle": "編輯代理鏈 {name}",
"nodes.proxyChain.help": "從入口至出口依序選擇 2 至 4 個節點。Hysteria2、TUIC、Juicity 與 AnyTLS 僅能作為入口。其後的跳點須為 SOCKS5、Shadowsocks、Trojan,或未使用 XHTTP 的 VMess、VLESS。",
"nodes.proxyChain.hop": "跳點 {n}",
"nodes.proxyChain.hopCount": "代理鏈須包含 2 至 4 個跳點。",
"nodes.proxyChain.hopEmpty": "每個跳點皆須選擇節點",
"nodes.proxyChain.hops": "跳點(入口至出口)",
"nodes.proxyChain.moveDown": "下移跳點 {n}",
"nodes.proxyChain.moveUp": "上移跳點 {n}",
"nodes.proxyChain.pickHop": "選擇節點",
"nodes.proxyChain.protocol": "代理鏈",
"nodes.proxyChain.removeHop": "移除跳點 {n}",
"nodes.proxyChain.udp": "UDP",
"nodes.proxyChain.udpDepends": "取決於節點設定",
"nodes.proxyChain.udpExit": "出口 {name} 不是 Trojan 或 VLESS",
"nodes.proxyChain.udpHop": "{name} 不支援經由其他跳點建立連線",
"nodes.proxyChain.unquotable": "名稱含單引號",
"nodes.referenced": "按 {name} 篩選節點的群組:{groups}。請先在策略頁修改這些篩選條件。",
"nodes.referencedBy": "{names} 仍在使用 {name}。請先修改這些引用,再移除。",
"nodes.referencedBy": "{names} 仍引用 {name}。請先修改這些引用,再移除該節點。",
"nodes.referrerDns": "DNS 上游 {name}",
"nodes.refresh": "更新 {name}",
"nodes.refreshFailed": "無法更新 {name}",
@@ -1935,6 +1952,7 @@
"ui.average": "平均",
"ui.back": "返回",
"ui.backend.activationUnconfirmed": "後端無法確認組態是否已生效",
"ui.backend.ambiguousChainHopReference": "多個節點與此代理鏈跳點同名",
"ui.backend.assetTooLarge": "下載的檔案超過大小上限",
"ui.backend.assetValidationFailed": "新的地理資料檔未通過驗證:檔案無法解析,或缺少規則使用的分類。已沿用目前的檔案",
"ui.backend.authenticationRequired": "需要驗證身分",
@@ -1955,6 +1973,7 @@
"ui.backend.httpStatusRejected": "伺服器回傳非 200 或 404 的 HTTP 狀態碼。請檢查網址",
"ui.backend.idempotencyConflict": "重複請求與原請求衝突",
"ui.backend.interfaceWatcherDisabled": "介面監視未執行,介面變更需重新啟動後生效",
"ui.backend.invalidChainHopReference": "找不到與此代理鏈跳點同名的節點",
"ui.backend.invalidCredentials": "憑證無效",
"ui.backend.invalidRequest": "請求內容無效",
"ui.backend.invalidSource": "沒有可用的下載網址:清單為空或網址格式有誤。請檢查來源",
@@ -2001,6 +2020,7 @@
"ui.backend.temporarilyUnavailable": "後端暫時無法使用",
"ui.backend.tlsFailed": "與伺服器的 TLS 交握失敗。請檢查網址與系統時間,或改用其他下載路由",
"ui.backend.udpTraceUnavailable": "核心 UDP 追蹤無法使用,記錄的 UDP 流程可能缺少核心路由資訊",
"ui.backend.unsupportedChainHop": "此節點不可作為代理鏈中此位置的跳點",
"ui.backend.unsupportedMediaType": "不支援此媒體類型",
"ui.backend.unsupportedValue": "不支援此設定值",
"ui.backendMessage": "後端訊息:{message}",
+53 -9
View File
@@ -1,16 +1,32 @@
import {useRef} from 'react';
import {Button as RButton, Header, Label, ListBox, ListBoxItem, ListBoxSection, Popover, Select, SelectValue, Text, type Key} from 'react-aria-components';
import {useRef, type ReactNode} from 'react';
import {
Button as RButton,
ButtonContext,
FieldError,
Header,
Label,
ListBox,
ListBoxItem,
ListBoxSection,
Popover,
Select,
SelectValue,
Text,
type Key
} from 'react-aria-components';
import AlertTriangle from './icons/AlertTriangle';
import ChevronDown from './icons/ChevronDown';
import {Check} from './Check';
import {cx} from './cx';
import {usePopoverBoundary} from './hooks';
import {ItemLabel, ItemText, type Item} from './ItemText';
import {SearchList} from './SearchList';
import {Toolbar} from './Toolbar';
import {useControlSize, type ControlSize} from './controlSize';
// A choice whose description is a latency or a state, coloured by its tone as the node menus colour theirs.
// `keywords`: more text the filter matches besides the label, such as the rule a position is placed before.
export type SearchItem = Item & {tone?: 'ok' | 'warn' | 'err'; keywords?: string};
export type SearchItem = Item & {tone?: 'ok' | 'warn' | 'err'; keywords?: string; isDisabled?: boolean};
// A section without a title lists its items without a heading, such as a leading None.
export type SearchSection = {id: string; title?: string; items: SearchItem[]};
@@ -37,7 +53,10 @@ export function SearchSelect({
isDisabled,
description,
side,
size
size,
placeholder,
error,
action
}: {
label: string;
// Names the filter field in the popover.
@@ -50,34 +69,59 @@ export function SearchSelect({
// The label beside the trigger, as LabeledSelect's `side`, for a toolbar.
side?: boolean;
size?: ControlSize;
// The trigger's text while no item is chosen, as S2's Picker shows it.
placeholder?: string;
// Shown under the trigger as a text field shows its error.
error?: string | null;
// Controls beside the trigger, as a text field's action; the error then spans them too.
action?: ReactNode;
}) {
const fieldRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const controlSize = useControlSize(size);
const boundary = usePopoverBoundary();
const shown = sections.flatMap(section => section.items).find(item => item.id === value);
const trigger = (
<RButton ref={buttonRef} className="rp-selectbtn" data-size={controlSize}>
{/* The list is built only while the popover is open, so the trigger finds the chosen item itself. */}
<SelectValue>{() => (shown ? <ItemLabel i={shown} /> : value || placeholder)}</SelectValue>
<ChevronDown />
</RButton>
);
return (
<Select
className={cx('rp-picker', side ? 'rp-cluster' : 'rp-field')}
selectedKey={value}
disabledKeys={sections.flatMap(section => section.items.filter(item => item.isDisabled).map(item => item.id))}
onSelectionChange={(k: Key | null) => {
if (k != null) onChange(String(k));
}}
isDisabled={isDisabled}
{...(error ? {isInvalid: true, validationBehavior: 'aria' as const} : {})}
>
<div ref={fieldRef} className={side ? 'rp-cluster' : 'rp-field'}>
<Label className={side ? 'rp-label' : 'lbl'}>{label}</Label>
<RButton ref={buttonRef} className="rp-selectbtn" data-size={controlSize}>
{/* The list is built only while the popover is open, so the trigger finds the chosen item itself. */}
<SelectValue>{() => (shown ? <ItemLabel i={shown} /> : value)}</SelectValue>
<ChevronDown />
</RButton>
{action ? (
<Toolbar>
{trigger}
{/* Buttons of their own, not more triggers of this select. */}
<ButtonContext.Provider value={null}>{action}</ButtonContext.Provider>
</Toolbar>
) : (
trigger
)}
</div>
{description && (
<Text slot="description" className="rp-label">
{description}
</Text>
)}
{error && (
<FieldError className="rp-field-error">
<AlertTriangle />
{error}
</FieldError>
)}
{/* Include the label in the anchor so a flipped list clears both label and trigger. */}
<Popover className="rp-popover rp-search-popover" placement="bottom start" triggerRef={side ? buttonRef : fieldRef} boundaryElement={boundary}>
<SearchList label={searchLabel}>
+7
View File
@@ -345,6 +345,13 @@
cursor: pointer;
min-width: 120px;
}
/* A picker with controls beside it: the trigger takes what the controls leave of the row, which does not wrap. */
.rp-picker .rp-toolbar {
flex-wrap: nowrap;
}
.rp-picker .rp-toolbar > .rp-selectbtn {
flex: 1;
}
.rp-selectbtn[data-size='L'] {
height: var(--rp-control-lg);
padding-inline: var(--rp-lg-inset-field);