Files
doona/mock/activation.ts
T
Zakk 8d81ddb689 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
2026-11-25 17:58:58 +11:00

211 lines
9.7 KiB
TypeScript

import type {Group, Node, Provider} from '../src/api/model';
import {uuid} from '../src/api/hash';
import {blockFields, quote, scanConfig, unquote} from '../src/dae/text';
import {nestedIn, nameText, readGroupEntries, writeGroupEntry} from '../src/dae/groups';
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';
// honk's mapping: an absent or empty claim is raw TCP, splithttp is xhttp, anything else unknown reports nothing.
const canonicalTransports = new Map([
['', 'tcp'],
['tcp', 'tcp'],
['ws', 'ws'],
['grpc', 'grpc'],
['xhttp', 'xhttp'],
['splithttp', 'xhttp']
]);
function streamTransport(link: string, protocol: string) {
try {
if (protocol === 'vmess') return canonicalTransports.get(JSON.parse(atob(link.slice('vmess://'.length))).net ?? '') ?? null;
if (protocol === 'vless' || protocol === 'trojan') return canonicalTransports.get(new URL(link).searchParams.get('type') ?? '') ?? null;
} catch {
// An unparsable link carries no transport.
}
return null;
}
export function activateInventory(
text: string,
revision: string,
nodes: Node[],
groups: Group[],
providers: Provider[],
newGroupId: (name: string) => string = uuid
) {
const {blocks, tokens} = scanConfig(text);
const fields = (section: string) => blocks.filter(block => block.name === section).flatMap(block => blockFields(text, block, tokens));
const subscriptions = readSubscriptionEntries(text);
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 = 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});
else
nextNodes.push({id: field.name, name: field.name, protocol, stream_transport, provider_id: 'inline', subscription_tag: null, group_ids: [], health: []});
}
const nextProviders = providers.filter(provider => provider.kind === 'inline' || providerIds.has(provider.name));
for (const entry of subscriptions) {
const url_redacted = displayUrl(entry.url);
const existing = nextProviders.find(provider => provider.name === entry.tag);
if (existing) {
existing.url_redacted = url_redacted;
continue;
}
nextProviders.push({
id: entry.tag,
name: entry.tag,
kind: 'subscription',
url_redacted,
node_count: 0,
updated_at: null,
expires_at: null,
traffic: null,
status: 'stale',
last_error: null
});
}
const declarations = readGroupEntries(text);
// Only the last declaration of a name is visible, in configuration order.
const entries = declarations.filter((entry, index) => !declarations.slice(index + 1).some(later => later.name === entry.name));
const ids = new Map(entries.map(entry => [entry.name, groups.find(group => group.name === entry.name)?.id ?? newGroupId(entry.name)]));
const memberships = new Map(nextNodes.map(node => [node.id, [] as string[]]));
const nextGroups = entries.map((entry): Group => {
const previous = groups.find(group => group.name === entry.name);
const memberNodes = nextNodes.filter(node => groupAdmits(entry.filters, node));
const members: Group['members'] = [
...nestedIn(entry)
.filter(name => entries.some(group => group.name === name))
.map(name => ({id: ids.get(name)!, name, kind: 'group' as const})),
...memberNodes.map(node => ({id: node.id, name: node.name, kind: 'node' as const}))
];
for (const node of memberNodes) memberships.get(node.id)!.push(ids.get(entry.name)!);
const native = entry.policy ?? 'fixed(0)';
const kind = policyKind(native) ?? 'selector';
const config = groupConfig(kind);
const block = blocks
.filter(block => block.name === 'group')
.flatMap(block => block.children)
.filter(block => block.name === entry.name)
.at(-1)!;
for (const field of blockFields(text, block, tokens)) {
// honk's own keys: `default` names a member by its tag, `final` an outbound.
if (field.name === 'default') config.default_member_id = members.find(member => member.name === unquote(field.value))?.id ?? null;
if (field.name === 'final') config.final_outbound = unquote(field.value);
if (!(field.name in config)) continue;
const value = unquote(field.value);
Object.assign(config, {
[field.name]:
value === 'null'
? null
: field.name === 'interrupt_connections'
? value === 'true'
: ['check_interval', 'tolerance', 'idle_timeout'].includes(field.name)
? Number(value)
: value
});
}
// Without a default, a fixed policy starts on the member it numbers.
const fastest =
kind !== 'selector'
? memberNodes
.filter(node => node.health.some(h => h.transport === 'tcp' && h.state === 'healthy'))
.sort(
(a, b) =>
(a.health.find(h => h.transport === 'tcp')?.latency_ms ?? Infinity) - (b.health.find(h => h.transport === 'tcp')?.latency_ms ?? Infinity)
)[0]?.id
: undefined;
const fixed = kind === 'selector' ? members[Number(/^fixed\((\d+)\)$/.exec(native)?.[1] ?? 0)]?.id : undefined;
const selection: Group['runtime']['selection'] = {tcp: null, udp: null};
for (const network of ['tcp', 'udp'] as const) {
const old = previous?.runtime.selection[network];
const id = old && members.some(member => member.id === old.member_id) ? old.member_id : (config.default_member_id ?? fixed ?? fastest ?? members[0]?.id);
if (id) selection[network] = {member_id: id, resolved_leaf_node_id: id, source: kind === 'selector' ? 'runtime' : 'policy'};
}
return {
id: ids.get(entry.name)!,
name: entry.name,
icon: previous?.icon ?? null,
config_revision: revision,
policy: {kind, native},
config,
members,
runtime: {
selection,
health: memberNodes.flatMap(node =>
node.health.map(health => ({
// Without a probe of the group's own, honk lists each member node's samples with their averages.
...health,
member_id: node.id,
resolved_leaf_node_id: node.id,
sorting_latency_ms: health.latency_ms,
ranking: null
}))
)
},
capabilities: groupCapabilities(kind)
};
});
for (const group of nextGroups) {
for (const network of ['tcp', 'udp'] as const) {
const selection = group.runtime.selection[network];
if (selection) selection.resolved_leaf_node_id = resolveLeaf(selection.member_id, network, nextNodes, nextGroups)?.id ?? null;
}
}
for (const node of nextNodes) node.group_ids = memberships.get(node.id)!;
for (const provider of nextProviders) provider.node_count = nextNodes.filter(node => node.provider_id === provider.id).length;
// Like honk, a subscription reports the route its fetches take: empty or `routing` follows the rules, `direct` goes
// straight out, and anything else names a group.
const routes = new Map(subscriptions.map(entry => [entry.tag, entry.route]));
for (const provider of nextProviders) {
if (provider.kind !== 'subscription') continue;
const route = routes.get(provider.name) || 'routing';
provider.download =
route === 'routing' || route === 'direct'
? {route, group_id: null}
: {route: 'group', group_id: nextGroups.find(group => group.name === route)?.id ?? null};
}
nodes.splice(0, nodes.length, ...nextNodes);
groups.splice(0, groups.length, ...nextGroups);
providers.splice(0, providers.length, ...nextProviders);
}
export function writeGroupConfig(text: string, name: string, update: Pick<Group, 'policy' | 'config' | 'members'>): string {
const entry = readGroupEntries(text)
.filter(entry => entry.name === name)
.at(-1)!;
// The API's default_member_id and final_outbound are the native `default` member tag and `final` outbound.
const {default_member_id, final_outbound, ...config} = update.config;
const member = update.members.find(member => member.id === default_member_id)?.name ?? null;
text = writeGroupEntry(text, name, {
filters: entry.filters,
policy: update.policy.native,
default: nameText(member, entry.default),
final: nameText(final_outbound, entry.final)
});
const {blocks, tokens} = scanConfig(text);
const block = blocks
.filter(block => block.name === 'group')
.flatMap(block => block.children)
.filter(block => block.name === name)
.at(-1)!;
const existing = blockFields(text, block, tokens).filter(field => field.name in config);
const values = Object.entries(config)
.map(([key, value]) => `${key}: ${typeof value === 'string' ? quote(value) : String(value)}`)
.join('\n ');
text = text.slice(0, block.close) + '\n ' + values + '\n ' + text.slice(block.close);
for (const field of existing.reverse()) text = text.slice(0, field.from) + text.slice(field.to);
return text;
}