diff --git a/changes/feat-proxy-chain-ui.md b/changes/feat-proxy-chain-ui.md new file mode 100644 index 00000000..76916384 --- /dev/null +++ b/changes/feat-proxy-chain-ui.md @@ -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. diff --git a/e2e/dns-rules.spec.ts b/e2e/dns-rules.spec.ts index 8d69d2b6..abfc37a9 100644 --- a/e2e/dns-rules.spec.ts +++ b/e2e/dns-rules.spec.ts @@ -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}) => { diff --git a/e2e/dns.spec.ts b/e2e/dns.spec.ts index 7e9062f1..21ab269d 100644 --- a/e2e/dns.spec.ts +++ b/e2e/dns.spec.ts @@ -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(); diff --git a/e2e/group-conditions.spec.ts b/e2e/group-conditions.spec.ts index 6d89fdc2..68fc0151 100644 --- a/e2e/group-conditions.spec.ts +++ b/e2e/group-conditions.spec.ts @@ -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}) => { diff --git a/e2e/group-includes.spec.ts b/e2e/group-includes.spec.ts index cccd3f5c..b506701a 100644 --- a/e2e/group-includes.spec.ts +++ b/e2e/group-includes.spec.ts @@ -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); }); diff --git a/e2e/nodes.spec.ts b/e2e/nodes.spec.ts index b45364c7..63839409 100644 --- a/e2e/nodes.spec.ts +++ b/e2e/nodes.spec.ts @@ -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'); }); diff --git a/e2e/rule-editor.spec.ts b/e2e/rule-editor.spec.ts index 88b73f19..8da5b105 100644 --- a/e2e/rule-editor.spec.ts +++ b/e2e/rule-editor.spec.ts @@ -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); }); diff --git a/e2e/rule-review.spec.ts b/e2e/rule-review.spec.ts index aff06c10..88fe7f69 100644 --- a/e2e/rule-review.spec.ts +++ b/e2e/rule-review.spec.ts @@ -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) { diff --git a/mock/activation.ts b/mock/activation.ts index b7464947..4b1f3598 100644 --- a/mock/activation.ts +++ b/mock/activation.ts @@ -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}); diff --git a/mock/fixtures/configuration.ts b/mock/fixtures/configuration.ts index bd0ba3c3..94215d72 100644 --- a/mock/fixtures/configuration.ts +++ b/mock/fixtures/configuration.ts @@ -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 { diff --git a/mock/fixtures/inventory.ts b/mock/fixtures/inventory.ts index 2e747995..01908ecd 100644 --- a/mock/fixtures/inventory.ts +++ b/mock/fixtures/inventory.ts @@ -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'}); diff --git a/src/api/selectors.ts b/src/api/selectors.ts index e5a16837..adfc0f53 100644 --- a/src/api/selectors.ts +++ b/src/api/selectors.ts @@ -45,8 +45,11 @@ const measurementRank: Record = { 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) => h.error !== 'no_node_address'; export function preferredObservation(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(health: T[]) { const kinds = new Map(); - 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); diff --git a/src/dae/nodes.test.ts b/src/dae/nodes.test.ts index 6dbf8896..2a566a4b 100644 --- a/src/dae/nodes.test.ts +++ b/src/dae/nodes.test.ts @@ -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); +}); diff --git a/src/dae/nodes.ts b/src/dae/nodes.ts index 5f8ef1aa..d5c0ddf0 100644 --- a/src/dae/nodes.ts +++ b/src/dae/nodes.ts @@ -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; +const tunneled = new Set(['socks5', 'ss', 'shadowsocks', 'trojan', 'vmess', 'vless']); +export const chainHopCandidate = (node: Pick) => !['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) => 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>) { + 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); } diff --git a/src/dae/probes.test.ts b/src/dae/probes.test.ts index dd1e36fe..ce690d77 100644 --- a/src/dae/probes.test.ts +++ b/src/dae/probes.test.ts @@ -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], diff --git a/src/dae/probes.ts b/src/dae/probes.ts index bd055710..8106ddec 100644 --- a/src/dae/probes.ts +++ b/src/dae/probes.ts @@ -12,6 +12,8 @@ const protocols: Record; + 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 ( + <> + {t('nodes.proxyChain.help')} + + {hops.map((hop, index) => { + const n = index + 1; + const last = index === hops.length - 1; + return ( + onHops(hops.map((other, i) => (i === index ? value : other)))} + action={ + <> + + + + + } + /> + ); + })} + + + + + ); +} diff --git a/src/features/nodes/NodeTable.tsx b/src/features/nodes/NodeTable.tsx index 052f18e8..cce0287b 100644 --- a/src/features/nodes/NodeTable.tsx +++ b/src/features/nodes/NodeTable.tsx @@ -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(null); +// A proxy chain's hops and UDP, read by its details without rebuilding the rows. +const Chains = createContext(new Map()); +function ChainFacts({id}: {id: string}) { + const t = useT(); + const chain = useContext(Chains).get(id); + if (!chain) return null; + return ( + <> +
+ {t('nodes.proxyChain.hops')} + [hop.label, {hop.value}])} /> +
+ + + ); +} 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] ]} /> + {/* 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. */}
@@ -211,7 +228,7 @@ export function NodeTable({model: m}: {model: NodeTableView}) { [settings, t] ); return ( - <> + {m.probeOptions && } {m.writable && m.sourceTip &&

{m.sourceTip}

} {m.scope ? ( @@ -262,6 +279,6 @@ export function NodeTable({model: m}: {model: NodeTableView}) { detail={detail} /> - +
); } diff --git a/src/features/nodes/Nodes.tsx b/src/features/nodes/Nodes.tsx index f02a2376..832e8719 100644 --- a/src/features/nodes/Nodes.tsx +++ b/src/features/nodes/Nodes.tsx @@ -34,6 +34,7 @@ import {preloadable} from '../../ui/preloadable'; const xhttpOptions = preloadable>(() => 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 && ( + + + + ); const blocked = referenced && ( {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) { )} )} - {(dialog?.kind === 'node' || dialog?.kind === 'editNode') && ( + {(dialog?.kind === 'node' || dialog?.kind === 'editNode' || dialog?.kind === 'editChain') && (
{dialog.kind === 'editNode' ? ( linkTab + ) : dialog.kind === 'editChain' ? ( + chainFields ) : ( setAddMode(id === 'manual' ? 'manual' : 'link')} + onChange={id => setAddMode(id === 'manual' || id === 'chain' ? id : 'link')} items={[ {id: 'link', label: t('nodes.manual.link'), content:
{linkTab}
}, { @@ -297,7 +307,8 @@ export function Nodes(props: PageProps) {
) - } + }, + ...(chainCreate ? [{id: 'chain', label: t('nodes.proxyChain.protocol'), content:
{chainFields}
}] : []) ]} /> )} diff --git a/src/features/nodes/latencyGroups.test.ts b/src/features/nodes/latencyGroups.test.ts index c0f22385..e8f48ab9 100644 --- a/src/features/nodes/latencyGroups.test.ts +++ b/src/features/nodes/latencyGroups.test.ts @@ -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)); diff --git a/src/features/nodes/nav.ts b/src/features/nodes/nav.ts index bca203eb..cf6caa4f 100644 --- a/src/features/nodes/nav.ts +++ b/src/features/nodes/nav.ts @@ -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 ] : []) diff --git a/src/features/nodes/useNodeTable.test.ts b/src/features/nodes/useNodeTable.test.ts index 04e40917..bf5b73f1 100644 --- a/src/features/nodes/useNodeTable.test.ts +++ b/src/features/nodes/useNodeTable.test.ts @@ -36,6 +36,7 @@ const input: Parameters[0] = { nodes, all: nodes, sourceOf: () => 'inline', + chainHops: () => null, providers: [], names: new Map(), loading: false, diff --git a/src/features/nodes/useNodeTable.ts b/src/features/nodes/useNodeTable.ts index 0bac0323..0e27c546 100644 --- a/src/features/nodes/useNodeTable.ts +++ b/src/features/nodes/useNodeTable.ts @@ -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()}), [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>; selection: {keys: Set; onChange: (keys: Selection) => void}; clearSelection: () => void; removeSelected: () => void; diff --git a/src/features/nodes/useNodesPage.ts b/src/features/nodes/useNodesPage.ts index 13206294..f885b1d9 100644 --- a/src/features/nodes/useNodesPage.ts +++ b/src/features/nodes/useNodesPage.ts @@ -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(null); const [form, setForm] = useState(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(emptyNode); + const [hops, setHops] = useState(['', '']); 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(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, diff --git a/src/features/nodes/view.test.ts b/src/features/nodes/view.test.ts index b360a78c..4a04dfc4 100644 --- a/src/features/nodes/view.test.ts +++ b/src/features/nodes/view.test.ts @@ -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)'); + }); +}); diff --git a/src/features/nodes/view.ts b/src/features/nodes/view.ts index 24bf01e8..4a02c4da 100644 --- a/src/features/nodes/view.ts +++ b/src/features/nodes/view.ts @@ -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, 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, 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(); + 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 & {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 { diff --git a/src/features/policies/group/groupIncludes.test.ts b/src/features/policies/group/groupIncludes.test.ts index 977ee70c..330200eb 100644 --- a/src/features/policies/group/groupIncludes.test.ts +++ b/src/features/policies/group/groupIncludes.test.ts @@ -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']); diff --git a/src/features/policies/usePolicyGroup.test.ts b/src/features/policies/usePolicyGroup.test.ts index 2d412420..04a58056 100644 --- a/src/features/policies/usePolicyGroup.test.ts +++ b/src/features/policies/usePolicyGroup.test.ts @@ -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}, diff --git a/src/features/policies/usePolicyGroup.ts b/src/features/policies/usePolicyGroup.ts index ea45df68..3bb12485 100644 --- a/src/features/policies/usePolicyGroup.ts +++ b/src/features/policies/usePolicyGroup.ts @@ -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) ); } diff --git a/src/features/policies/view.test.ts b/src/features/policies/view.test.ts index f7e0f893..138af95f 100644 --- a/src/features/policies/view.test.ts +++ b/src/features/policies/view.test.ts @@ -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[0]); expect(summary).toBe('Available: 1, unavailable: 1, unknown: 1 (1 unresolved), selection: unchanged'); diff --git a/src/features/policies/view.ts b/src/features/policies/view.ts index a5c42333..20a174c4 100644 --- a/src/features/policies/view.ts +++ b/src/features/policies/view.ts @@ -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([ // of the row that decided its state. export function probeSummary(result: ProbeResult, t: Translator, lang: Lang): string { const rows = new Map(); - 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'); diff --git a/src/features/rules/view.test.ts b/src/features/rules/view.test.ts index 6f94075a..88a0d838 100644 --- a/src/features/rules/view.test.ts +++ b/src/features/rules/view.test.ts @@ -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. diff --git a/src/i18n/backend.ts b/src/i18n/backend.ts index 06fbf21b..96e3dbfb 100644 --- a/src/i18n/backend.ts +++ b/src/i18n/backend.ts @@ -80,7 +80,10 @@ const known: Record = { 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']); diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 96be018e..1cfc5fd9 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -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}", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index f6672f59..0371f94c 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -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}", diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index 32e99725..4cfef1e3 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -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}", diff --git a/src/ui/SearchSelect.tsx b/src/ui/SearchSelect.tsx index d0e56df5..4fa2b388 100644 --- a/src/ui/SearchSelect.tsx +++ b/src/ui/SearchSelect.tsx @@ -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(null); const buttonRef = useRef(null); const controlSize = useControlSize(size); const boundary = usePopoverBoundary(); const shown = sections.flatMap(section => section.items).find(item => item.id === value); + const trigger = ( + + {/* The list is built only while the popover is open, so the trigger finds the chosen item itself. */} + {() => (shown ? : value || placeholder)} + + + ); return (