Compare commits
3 Commits
260dcbb652
...
88fa8d3ad0
| Author | SHA1 | Date | |
|---|---|---|---|
| 88fa8d3ad0 | |||
| f21297fa3a | |||
| 653e808ee1 |
43
package-lock.json
generated
43
package-lock.json
generated
@ -10,16 +10,20 @@
|
||||
"dependencies": {
|
||||
"@xyflow/react": "^12.10.0",
|
||||
"base64-js": "^1.5.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-hot-toast": "^2.6.0",
|
||||
"react-select": "^5.10.2",
|
||||
"react-switch": "^7.1.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"tweetnacl": "^1.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@types/base64-js": "^1.3.2",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/react": "^19.2.5",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
@ -61,7 +65,6 @@
|
||||
"integrity": "sha512-H3mcG6ZDLTlYfaSNi0iOKkigqMFvkTKlGUYlD8GW7nNOYRrevuA46iTypPyv+06V3fEmvvazfntkBU34L0azAw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.28.6",
|
||||
"@babel/generator": "^7.28.6",
|
||||
@ -1564,6 +1567,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/crypto-js": {
|
||||
"version": "4.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.2.2.tgz",
|
||||
"integrity": "sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-color": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
|
||||
@ -1638,7 +1648,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.9.tgz",
|
||||
"integrity": "sha512-Lpo8kgb/igvMIPeNV2rsYKTgaORYdO1XGVZ4Qz3akwOj0ySGYMPlQWa8BaLn0G63D1aSaAQ5ldR06wCpChQCjA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
@ -1721,7 +1730,6 @@
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@ -1861,7 +1869,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
@ -1923,6 +1930,12 @@
|
||||
"url": "https://github.com/chalk/chalk?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/class-transformer": {
|
||||
"version": "0.5.1",
|
||||
"resolved": "https://registry.npmjs.org/class-transformer/-/class-transformer-0.5.1.tgz",
|
||||
"integrity": "sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/classcat": {
|
||||
"version": "5.0.5",
|
||||
"resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",
|
||||
@ -2003,12 +2016,17 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/crypto-js": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
|
||||
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/d3-color": {
|
||||
"version": "3.1.0",
|
||||
@ -2067,7 +2085,6 @@
|
||||
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
|
||||
"integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
|
||||
"license": "ISC",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
@ -2236,7 +2253,6 @@
|
||||
"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.8.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@ -3055,7 +3071,6 @@
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@ -3128,7 +3143,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
|
||||
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@ -3138,7 +3152,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
|
||||
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
@ -3229,6 +3242,12 @@
|
||||
"react-dom": ">=16.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/reflect-metadata": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
|
||||
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/resolve": {
|
||||
"version": "1.22.11",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",
|
||||
@ -3524,7 +3543,6 @@
|
||||
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.27.0",
|
||||
"fdir": "^6.5.0",
|
||||
@ -3646,7 +3664,6 @@
|
||||
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
||||
@ -12,16 +12,20 @@
|
||||
"dependencies": {
|
||||
"@xyflow/react": "^12.10.0",
|
||||
"base64-js": "^1.5.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-hot-toast": "^2.6.0",
|
||||
"react-select": "^5.10.2",
|
||||
"react-switch": "^7.1.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"tweetnacl": "^1.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@types/base64-js": "^1.3.2",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/react": "^19.2.5",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
|
||||
83
src/App.tsx
83
src/App.tsx
@ -18,15 +18,20 @@ import {
|
||||
EdgeMouseHandler
|
||||
} from '@xyflow/react';
|
||||
import '@xyflow/react/dist/style.css';
|
||||
import { AppNode, AppEdge, NodeData, EdgeData, NodeDataUpdate, EdgeDataUpdate, Settings, initialSettings, SettingsContext } from './types/graph';
|
||||
import { AppNode, AppEdge, NodeData, EdgeData, NodeDataUpdate, EdgeDataUpdate } from './types/graph';
|
||||
import {Settings, SettingsContext} from './types/settings'
|
||||
import CustomNode from './components/CustomNode';
|
||||
import NodeEditor from './components/NodeEditor';
|
||||
import EdgeEditor from './components/EdgeEditor'
|
||||
import SettingsEditor from './components/SettingsEditor'
|
||||
import Toggle from "./components/Toggle"
|
||||
import { generateWireGuardPrivateKey } from './utils/wireguardConfig';
|
||||
import CryptoJS from 'crypto-js';
|
||||
import './App.css';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import toast, { Toaster } from 'react-hot-toast';
|
||||
import SaveConfig from './types/saveConfig'
|
||||
import { plainToInstance, instanceToPlain } from 'class-transformer';
|
||||
|
||||
|
||||
const initialNodes: AppNode[] = [];
|
||||
const initialEdges: AppEdge[] = [];
|
||||
@ -48,7 +53,7 @@ function generateNodeData(count: number) : NodeData | null {
|
||||
function FlowContent(): ReactNode {
|
||||
const [nodes, setNodes] = useState<AppNode[]>(initialNodes);
|
||||
const [edges, setEdges] = useState<AppEdge[]>(initialEdges);
|
||||
const [settings, setSettings] = useState<Settings>(initialSettings);
|
||||
const [settings, setSettings] = useState<Settings>(new Settings());
|
||||
|
||||
const [editingNode, setEditingNode] = useState<NodeData | undefined>(undefined);
|
||||
const [editingEdge, setEditingEdge] = useState<EdgeData | undefined>(undefined);
|
||||
@ -142,6 +147,70 @@ function FlowContent(): ReactNode {
|
||||
);
|
||||
};
|
||||
|
||||
const handleSaveConfig = async (): Promise<void> => {
|
||||
try {
|
||||
const pass = window.prompt('输入用于加密私钥的密码(留空则不加密):');
|
||||
const saveConfig: SaveConfig = {settings: settings, nodes: [], edges: [], encrypted: false}
|
||||
if(pass) saveConfig.encrypted = true;
|
||||
|
||||
nodes.forEach(node => {
|
||||
const nodeData = node.data;
|
||||
let privateKey = nodeData.privateKey;
|
||||
if(pass) privateKey = CryptoJS.AES.encrypt(privateKey, pass).toString();
|
||||
saveConfig.nodes.push({...node, data: {...nodeData, privateKey: privateKey}});
|
||||
});
|
||||
|
||||
edges.forEach(edge => {
|
||||
saveConfig.edges.push(edge);
|
||||
});
|
||||
|
||||
const json = instanceToPlain(saveConfig);
|
||||
const blob = new Blob([JSON.stringify(json, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'wg-config.json';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
toast.error('保存失败: ' + e);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLoadConfig = async (): Promise<void> => {
|
||||
try {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'application/json';
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
const jsonString = await file.text();
|
||||
const plainObject = JSON.parse(jsonString);
|
||||
const saveConfig: SaveConfig = plainToInstance(SaveConfig, plainObject);
|
||||
|
||||
if (saveConfig.encrypted) {
|
||||
const pass = window.prompt('输入用于解密私钥的密码:');
|
||||
if (!pass) { toast.error('需要密码以解密私钥'); return; }
|
||||
try {
|
||||
for(let node of saveConfig.nodes) {
|
||||
node.data.privateKey = CryptoJS.AES.decrypt(node.data.privateKey, pass).toString(CryptoJS.enc.Utf8);
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error('解密失败: ' + err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setSettings(saveConfig.settings);
|
||||
setNodes(saveConfig.nodes);
|
||||
setEdges(saveConfig.edges);
|
||||
};
|
||||
input.click();
|
||||
} catch (e) {
|
||||
toast.error('加载失败: ' + e);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ width: '100vw', height: '100vh' }}>
|
||||
<Toaster/>
|
||||
@ -187,6 +256,14 @@ function FlowContent(): ReactNode {
|
||||
📋 设置
|
||||
</button>
|
||||
|
||||
<button className="toolbar-btn" onClick={handleSaveConfig} title="保存配置">
|
||||
💾 保存配置
|
||||
</button>
|
||||
|
||||
<button className="toolbar-btn" onClick={handleLoadConfig} title="加载配置">
|
||||
📂 加载配置
|
||||
</button>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
import { ReactNode, useContext } from 'react';
|
||||
import { Handle, Position, NodeProps, useReactFlow} from '@xyflow/react';
|
||||
import { AppNode, AppEdge, AppGraph, NodeData } from '../types/graph';
|
||||
import {Settings, SettingsContext} from '../types/settings'
|
||||
import {Settings, SettingsContext, SubnetInfo} from '../types/settings'
|
||||
import StringBuilder from '../utils/StringBuilder';
|
||||
|
||||
import { Result } from '../utils/Result';
|
||||
import { CIDR, IPUtils } from '../utils/iputils';
|
||||
import { tryDerivePublicKey } from '../utils/wireguardConfig'
|
||||
import './CustomNode.css';
|
||||
@ -17,26 +17,6 @@ class ConfigResult {
|
||||
) {}
|
||||
}
|
||||
|
||||
// function mapAddressToCIDR(nodeIds : string[], getAddress: GetAddress) : Record<string, CIDR> {
|
||||
// const nodeIdToCIDR : Record<string, CIDR> = {};
|
||||
// for(const nodeId of nodeIds) {
|
||||
// const address = getAddress(nodeId);
|
||||
// if(!address) continue;
|
||||
// const result = IPUtils.parse(address);
|
||||
// const cidr = result.cidr;
|
||||
// if(!cidr) {
|
||||
// throw new Error("节点地址无效");
|
||||
// }
|
||||
// if(cidr.version === 'IPv4') {
|
||||
// cidr.mask = 32;
|
||||
// } else if(cidr.version === 'IPv6') {
|
||||
// cidr.mask = 128;
|
||||
// }
|
||||
// nodeIdToCIDR[nodeId] = cidr;
|
||||
// }
|
||||
// return nodeIdToCIDR;
|
||||
// }
|
||||
|
||||
function generateInterfaceConfig(settings: Settings, data: NodeData) : StringBuilder {
|
||||
const address = [data.ipv4Address, data.ipv6Address].flatMap(p => p ? [p] : []).join(', ');
|
||||
const config = new StringBuilder();
|
||||
@ -52,8 +32,65 @@ function generateInterfaceConfig(settings: Settings, data: NodeData) : StringBui
|
||||
return config;
|
||||
}
|
||||
|
||||
function generateConfig(settings: Settings, data: NodeData, graph: AppGraph) : ConfigResult {
|
||||
const config = generateInterfaceConfig(settings, data);
|
||||
function getFromChildRouterMapper(subnet: SubnetInfo, graph: AppGraph, nodeId: string, disallowCIDRs: CIDR[]) : Result<Map<string, CIDR[]>> {
|
||||
const subGraph = graph.getConnectedSubgraph(subnet.nodes.map(kv => kv.nodeId));
|
||||
|
||||
if(!subGraph)
|
||||
return Result.Error(`图不连通,无法生存子网路由:${subnet.subnet.toString()}`);
|
||||
|
||||
|
||||
const fromChildMapper: Map<string, string[]> = new Map();
|
||||
const visited: Set<string> = new Set();
|
||||
visited.add(nodeId);
|
||||
const queue : string[] = [];
|
||||
const children = subGraph.getChildren(nodeId);
|
||||
children.forEach(child => {
|
||||
fromChildMapper.set(child, [child]);
|
||||
visited.add(child);
|
||||
queue.push(child);
|
||||
});
|
||||
|
||||
const allNodes = [];
|
||||
while(queue.length > 0) {
|
||||
const curr = queue.shift()!;
|
||||
const fromChild = fromChildMapper.get(curr);
|
||||
if(!fromChild) continue;
|
||||
allNodes.push(curr);
|
||||
const nexts = subGraph.getChildren(curr);
|
||||
for(const next of nexts) {
|
||||
if(visited.has(next)) continue;
|
||||
fromChild.push(next);
|
||||
visited.add(next);
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
|
||||
const allCIDRs = allNodes.flatMap((nodeId: string) => {
|
||||
const cidr = subnet.nodes.find(n => n.nodeId === nodeId)?.cidr;
|
||||
return cidr ? [cidr] : [];
|
||||
});
|
||||
|
||||
const result: Map<string, CIDR[]> = new Map();
|
||||
for (const [fromChild, nodes] of fromChildMapper) {
|
||||
const targetCIDRs = nodes.flatMap((nodeId: string) => {
|
||||
const cidr = subnet.nodes.find(n => n.nodeId === nodeId)?.cidr;
|
||||
if(!cidr || disallowCIDRs.some(disallow => disallow.contains(cidr))) return [];
|
||||
return [cidr];
|
||||
});
|
||||
|
||||
const mergeResult = IPUtils.mergeCIDRs(allCIDRs, targetCIDRs);
|
||||
if(!mergeResult) {
|
||||
return Result.Error("无法生成路由配置");
|
||||
}
|
||||
result.set(fromChild, mergeResult);
|
||||
}
|
||||
|
||||
return Result.Result(result);
|
||||
}
|
||||
|
||||
|
||||
function generateConfig(settings: Settings, data: NodeData, graph: AppGraph, subnets: SubnetInfo[]) : ConfigResult {
|
||||
const config: StringBuilder = generateInterfaceConfig(settings, data);
|
||||
|
||||
const disallowCIDRs : CIDR[] = [];
|
||||
if(data.disallowIPs) {
|
||||
@ -67,119 +104,126 @@ function generateConfig(settings: Settings, data: NodeData, graph: AppGraph) : C
|
||||
}
|
||||
}
|
||||
|
||||
const belongsToEdge : Record<string, string | undefined> = {[node.id]: node.id};
|
||||
const allowIPsConfig: Map<string, string[]> = new Map();
|
||||
|
||||
const queue : AppNode[] = [];
|
||||
const nearEdges = getNearEdges(node);
|
||||
nearEdges.forEach(edge => {
|
||||
const nextNode = getNextNode(edge, node)!;
|
||||
belongsToEdge[nextNode.id] = edge.id;
|
||||
queue.push(nextNode);
|
||||
});
|
||||
for(const subnet of subnets) {
|
||||
const result = getFromChildRouterMapper(subnet, graph, data.id, disallowCIDRs);
|
||||
const mapper = result.result;
|
||||
if(!mapper) return new ConfigResult(false, undefined, `路由生成失败:${result.errorInfo()}`);
|
||||
|
||||
while(queue.length > 0) {
|
||||
const currentNode = queue.shift()!;
|
||||
const fromEdgeId = belongsToEdge[currentNode.id];
|
||||
if(!fromEdgeId) continue;
|
||||
|
||||
getNearEdges(currentNode).forEach(edge => {
|
||||
const nextNode = getNextNode(edge, currentNode)!;
|
||||
if(!belongsToEdge[nextNode.id]) {
|
||||
belongsToEdge[nextNode.id] = fromEdgeId;
|
||||
queue.push(nextNode);
|
||||
for(const [fromChild, cidrs] of mapper) {
|
||||
if(!allowIPsConfig.has(fromChild)) allowIPsConfig.set(fromChild, []);
|
||||
const allowIPs = allowIPsConfig.get(fromChild)!;
|
||||
for(const cidr of cidrs) {
|
||||
allowIPs.push(cidr.toString());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const groupedByEdge: Record<string, string[] | undefined> = {};
|
||||
const nodeIds : string[] = [];
|
||||
for (const nodeId in belongsToEdge) {
|
||||
const edgeId = belongsToEdge[nodeId];
|
||||
if(edgeId === nodeId) continue; // 跳过起始节点
|
||||
nodeIds.push(nodeId);
|
||||
if(!edgeId) continue;
|
||||
if (!groupedByEdge[edgeId]) {
|
||||
groupedByEdge[edgeId] = [];
|
||||
}
|
||||
groupedByEdge[edgeId].push(nodeId);
|
||||
}
|
||||
const nexts = graph.getChildren(data.id);
|
||||
for(const next of nexts) {
|
||||
const nextData = graph.queryNode(next)!.data;
|
||||
|
||||
for(const edgeId in groupedByEdge) {
|
||||
const groupNodeIds = groupedByEdge[edgeId]!;
|
||||
const edge = getEdge(edgeId)!;
|
||||
const nextNode = getNextNode(edge, node)!;
|
||||
const nextNodeData = nextNode.data;
|
||||
const edge = graph.queryEdge(data.id, next)!;
|
||||
|
||||
const publicKey = tryDerivePublicKey(nextNodeData.privateKey);
|
||||
const publicKey = tryDerivePublicKey(nextData.privateKey);
|
||||
if(!publicKey) return new ConfigResult(false, undefined, "无法从私钥派生公钥");
|
||||
|
||||
config.appendLine("");
|
||||
config.appendLine("[Peer]");
|
||||
config.appendLine(`# ${nextNodeData.label}`);
|
||||
config.appendLine(`# ${nextData.label}`);
|
||||
config.appendLine(`PublicKey = ${ publicKey}`);
|
||||
|
||||
if(edge.data?.isTwoWayEdge || edge.source === node.id) {
|
||||
if(edge.data?.persistentKeepalive) {
|
||||
config.appendLine(`PersistentKeepalive = ${edge.data.persistentKeepalive}`);
|
||||
const edgeData = edge.data;
|
||||
if(edgeData && (edgeData.isTwoWayEdge || edge.source === data.id)) {
|
||||
if(edgeData.persistentKeepalive) {
|
||||
config.appendLine(`PersistentKeepalive = ${edgeData.persistentKeepalive}`);
|
||||
}
|
||||
|
||||
if(!nextNodeData.listenAddress) {
|
||||
return new ConfigResult(false, undefined, `节点 ${nextNodeData.label} 未设置监听地址,无法生成配置`);
|
||||
let listenAddress = nextData.listenAddress;
|
||||
if(listenAddress) {
|
||||
if(listenAddress.includes(":")) listenAddress = `[${listenAddress}]`;
|
||||
const listenPort = nextData.listenPort || settings.listenPort;
|
||||
listenAddress = `${listenAddress}:${listenPort}`
|
||||
}
|
||||
|
||||
const parse = IPUtils.parse(`${nextNodeData.listenAddress}/0`);
|
||||
if(!parse.cidr) {
|
||||
return new ConfigResult(false, undefined, `节点 ${nextNodeData.label} 的监听地址无效`);
|
||||
if(!edgeData.isTwoWayEdge && edge.source === data.id && edgeData.endPint) {
|
||||
listenAddress = edgeData.endPint;
|
||||
}
|
||||
|
||||
const listenAddress = parse.cidr.version === 'IPv4' ? nextNodeData.listenAddress : `[${nextNodeData.listenAddress}]`;
|
||||
const listenPort = nextNodeData.listenPort || settings.listenPort;
|
||||
config.appendLine(`EndPoint = ${listenAddress}:${listenPort}`);
|
||||
if(!listenAddress) {
|
||||
return new ConfigResult(false, undefined, `节点 ${nextData.label} 未设置监听地址,无法生成配置`);
|
||||
}
|
||||
|
||||
const subnets : Record<string, CIDR>[] = [];
|
||||
config.appendLine(`EndPoint = ${listenAddress}`);
|
||||
}
|
||||
|
||||
try {
|
||||
subnets.push(mapAddressToCIDR(nodeIds, nodeId => node.data.ipv4Address && getNode(nodeId)?.data.ipv4Address));
|
||||
subnets.push(mapAddressToCIDR(nodeIds, nodeId => node.data.ipv6Address && getNode(nodeId)?.data.ipv6Address));
|
||||
} catch(e) {
|
||||
if(e instanceof Error) {
|
||||
return new ConfigResult(false, undefined, e.message);
|
||||
}
|
||||
}
|
||||
const allowIPs : string[] = [];
|
||||
for(const subnetMap of subnets) {
|
||||
const allCIDRs = nodeIds.flatMap(id => subnetMap[id] ? [subnetMap[id]] : []);
|
||||
const targetCIDRs = groupNodeIds.flatMap(id => {
|
||||
const cidr = subnetMap[id];
|
||||
if(!cidr || disallowCIDRs.some(disallow => disallow.contains(cidr))) return [];
|
||||
return [cidr];
|
||||
});
|
||||
const mergeResult = IPUtils.mergeCIDRs(allCIDRs, targetCIDRs);
|
||||
if(!mergeResult) {
|
||||
return new ConfigResult(false, undefined, `无法生成路由配置`);
|
||||
}
|
||||
mergeResult.forEach(cidr => {allowIPs.push(cidr.toString())});
|
||||
}
|
||||
if(allowIPs.length > 0) {
|
||||
const allowIPs = allowIPsConfig.get(next);
|
||||
if(allowIPs && allowIPs.length > 0) {
|
||||
config.appendLine(`AllowedIPs = ${allowIPs.join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
// console.log(config.toString());
|
||||
|
||||
console.log(config.toString())
|
||||
return new ConfigResult(true, config.toString());
|
||||
}
|
||||
|
||||
function getSubnet(nodes: AppNode[], version: 'ipv4' | 'ipv6'): Result<SubnetInfo | undefined> {
|
||||
const addresses: {nodeId: string, cidr: CIDR}[] = [];
|
||||
|
||||
for(const node of nodes) {
|
||||
const address = version === 'ipv4' ? node.data.ipv4Address : node.data.ipv6Address;
|
||||
if(!address) continue;
|
||||
const result = IPUtils.parse(address);
|
||||
const cidr = result.cidr;
|
||||
if(!cidr) return Result.Error(result.error);
|
||||
addresses.push({nodeId: node.id, cidr: cidr});
|
||||
}
|
||||
|
||||
if(addresses.length === 0) return Result.Result(undefined);
|
||||
|
||||
const subnet: SubnetInfo = {subnet: addresses[0].cidr, nodes: []}
|
||||
for(const address of addresses) {
|
||||
const cidr = address.cidr;
|
||||
if(!subnet.subnet.contains(cidr)) {
|
||||
return Result.Error("不在同一子网下");
|
||||
}
|
||||
|
||||
subnet.nodes.push({...address, cidr: new CIDR(cidr.version, cidr.binary, version === 'ipv4' ? 32 : 128)});
|
||||
}
|
||||
return Result.Result(subnet);
|
||||
}
|
||||
|
||||
|
||||
export default function CustomNode({
|
||||
data,
|
||||
selected
|
||||
}: NodeProps<AppNode>): ReactNode {
|
||||
const settings = useContext(SettingsContext);
|
||||
const { getNode, getEdge, getEdges } = useReactFlow<AppNode, AppEdge>();
|
||||
const { getNodes, getEdges } = useReactFlow<AppNode, AppEdge>();
|
||||
|
||||
const handleGenerate = (node : NodeData) => {
|
||||
const result = generateConfig(settings, node, getEdges, getEdge, getNode);
|
||||
const graph = new AppGraph(getNodes, getEdges);
|
||||
const nodes = getNodes();
|
||||
let subnets: SubnetInfo[] = [];
|
||||
|
||||
const v4 = getSubnet(nodes, 'ipv4');
|
||||
const v6 = getSubnet(nodes, 'ipv6');
|
||||
if(!v4.isValid()) {
|
||||
toast.error(`ipv4子网配置有误:${v4.errorInfo()}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if(!v6.isValid()) {
|
||||
toast.error(`ipv6子网配置有误:${v6.errorInfo()}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if(v4.result) subnets.push(v4.result);
|
||||
if(v6.result) subnets.push(v6.result);
|
||||
subnets = subnets.concat(settings.subnets);
|
||||
|
||||
const result = generateConfig(settings, node, graph, subnets);
|
||||
if(result.success && result.config) {
|
||||
navigator.clipboard.writeText(result.config).then(() => {
|
||||
toast.success("配置已复制到剪贴板");
|
||||
|
||||
@ -16,10 +16,12 @@ export default function NodeEditor({
|
||||
}: EdgeEditorProps): ReactNode {
|
||||
|
||||
const [keepalive, setKeepalive] = useState(edge.persistentKeepalive);
|
||||
const [endpoint, setEndPoint] = useState(edge.endPint);
|
||||
|
||||
const { getNode, getEdge } = useReactFlow<AppNode, AppEdge>();
|
||||
|
||||
const handleSave = (): void => {
|
||||
onUpdate({persistentKeepalive : keepalive});
|
||||
onUpdate({persistentKeepalive : keepalive, endPint: endpoint});
|
||||
onClose();
|
||||
};
|
||||
|
||||
@ -58,6 +60,19 @@ export default function NodeEditor({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!edge.isTwoWayEdge && (
|
||||
<div className="form-group">
|
||||
<label>EndPoint</label>
|
||||
<input
|
||||
type="text"
|
||||
value={endpoint || ''}
|
||||
onChange={e => setEndPoint(e.target.value)}
|
||||
placeholder={`留空使用节点上配置的监听地址`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
<div className="editor-actions">
|
||||
<button className="btn-save" onClick={handleSave}>保存</button>
|
||||
<button className="btn-cancel" onClick={onClose}>取消</button>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { useState, ReactNode } from 'react';
|
||||
import { NodeData, Settings, NodeDataUpdate } from '../types/graph';
|
||||
import { NodeData, NodeDataUpdate } from '../types/graph';
|
||||
import { Settings } from '../types/settings';
|
||||
import { generateWireGuardPrivateKey } from '../utils/wireguardConfig'
|
||||
import { IPUtils} from '../utils/iputils'
|
||||
import './FormEditor.css';
|
||||
@ -12,7 +13,7 @@ interface NodeEditorProps {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function Validate(updateData : NodeDataUpdate, settings : Settings) : string[] {
|
||||
function Validate(updateData : NodeDataUpdate) : string[] {
|
||||
const errors: string[] = [];
|
||||
const {ipv4Address, ipv6Address, mtu, listenPort} = updateData;
|
||||
|
||||
@ -95,7 +96,7 @@ export default function NodeEditor({
|
||||
notes: notes
|
||||
}
|
||||
|
||||
const validation = Validate(updateData, settings);
|
||||
const validation = Validate(updateData);
|
||||
setErrors(validation);
|
||||
if(validation.length > 0) {
|
||||
return ;
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import 'reflect-metadata';
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
|
||||
@ -30,6 +30,7 @@ export type EdgeData = {
|
||||
|
||||
export type EdgeDataUpdate = {
|
||||
persistentKeepalive?: number;
|
||||
endPint?: string;
|
||||
}
|
||||
|
||||
type GetEdges = () => AppEdge[];
|
||||
@ -40,8 +41,8 @@ export class AppGraph {
|
||||
private readonly _getNextNodeIds = new Map<string, string[]>();
|
||||
|
||||
constructor(
|
||||
public readonly getNodes: GetNodes,
|
||||
public readonly getEdges: GetEdges,
|
||||
public readonly getNodes: GetNodes
|
||||
) {
|
||||
const getNextNodeIds = this._getNextNodeIds;
|
||||
const nodeIds = getNodes().map(node => node.id);
|
||||
@ -57,9 +58,21 @@ export class AppGraph {
|
||||
}
|
||||
}
|
||||
|
||||
queryNode(nodeId: string): AppNode | undefined {
|
||||
return this.getNodes().find(n => n.id === nodeId);
|
||||
}
|
||||
|
||||
private static checkConnected(graph: AppGraph): boolean {
|
||||
const nodes = graph.getNodes();
|
||||
queryEdge(source: string, target: string): AppEdge | undefined {
|
||||
return this.getEdges().find(e =>
|
||||
(e.source === source && e.target === target) || (e.target === source && e.source === target));
|
||||
}
|
||||
|
||||
getChildren(nodeId: string) : string[] {
|
||||
return this._getNextNodeIds.get(nodeId) ?? [];
|
||||
}
|
||||
|
||||
private checkConnected(): boolean {
|
||||
const nodes = this.getNodes();
|
||||
if(nodes.length === 0) return true;
|
||||
|
||||
const visited = new Set<string>();
|
||||
@ -68,7 +81,7 @@ export class AppGraph {
|
||||
queue.push(first.id);
|
||||
visited.add(first.id);
|
||||
|
||||
const getNextNodeIds = graph._getNextNodeIds;
|
||||
const getNextNodeIds = this._getNextNodeIds;
|
||||
while(queue.length > 0) {
|
||||
const curr = queue.shift()!;
|
||||
const next = getNextNodeIds.get(curr);
|
||||
@ -83,7 +96,24 @@ export class AppGraph {
|
||||
return visited.size === nodes.length;
|
||||
}
|
||||
|
||||
|
||||
getConnectedSubgraph(nodeIds: string[]): AppGraph | undefined {
|
||||
const node
|
||||
let completed = false;
|
||||
let graph: AppGraph = this;
|
||||
|
||||
while(!completed) {
|
||||
completed = true;
|
||||
const nodes = graph.getNodes();
|
||||
|
||||
for(const node of nodes) {
|
||||
if(nodeIds.includes(node.id)) continue;
|
||||
const newGraph = new AppGraph(() => this.getNodes().filter(n => n.id !== node.id), this.getEdges);
|
||||
if(!newGraph.checkConnected()) continue;
|
||||
graph = newGraph;
|
||||
completed = false;
|
||||
}
|
||||
}
|
||||
|
||||
return graph;
|
||||
}
|
||||
}
|
||||
14
src/types/saveConfig.ts
Normal file
14
src/types/saveConfig.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { Type } from 'class-transformer';
|
||||
import { Settings } from './settings';
|
||||
import { AppNode, AppEdge } from './graph';
|
||||
|
||||
export default class SaveConfig {
|
||||
encrypted: boolean = false;
|
||||
|
||||
@Type(() => Settings)
|
||||
settings: Settings = new Settings();
|
||||
|
||||
nodes: AppNode[] = [];
|
||||
|
||||
edges: AppEdge[] = [];
|
||||
}
|
||||
@ -1,22 +1,28 @@
|
||||
import { Type } from 'class-transformer';
|
||||
import { createContext } from 'react';
|
||||
import { CIDR } from '../utils/iputils';
|
||||
|
||||
export interface SubnetInfo {
|
||||
subnet: CIDR;
|
||||
nodes: Array<{nodeId: string, cidr: CIDR | undefined}>;
|
||||
export class NodeToCIDR {
|
||||
nodeId: string = '';
|
||||
|
||||
@Type(() => CIDR) // 必须显式标记,即使是 undefined 也要处理
|
||||
cidr: CIDR | undefined;
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
listenPort: number;
|
||||
mtu: number;
|
||||
export class SubnetInfo {
|
||||
@Type(() => CIDR)
|
||||
subnet!: CIDR;
|
||||
|
||||
subnets: SubnetInfo[];
|
||||
@Type(() => NodeToCIDR)
|
||||
nodes: NodeToCIDR[] = [];
|
||||
}
|
||||
|
||||
export const initialSettings : Settings = {
|
||||
listenPort: 38894,
|
||||
mtu: 1420,
|
||||
subnets: []
|
||||
};
|
||||
export class Settings {
|
||||
listenPort: number = 38894;
|
||||
mtu: number = 1420;
|
||||
|
||||
export const SettingsContext = createContext<Settings>(initialSettings);
|
||||
@Type(() => SubnetInfo)
|
||||
subnets: SubnetInfo[] = [];
|
||||
}
|
||||
|
||||
export const SettingsContext = createContext<Settings>(new Settings());
|
||||
|
||||
26
src/utils/Result.ts
Normal file
26
src/utils/Result.ts
Normal file
@ -0,0 +1,26 @@
|
||||
export class Result<T> {
|
||||
private constructor(
|
||||
public readonly errors: string[],
|
||||
public readonly result?: T,
|
||||
) {}
|
||||
|
||||
isValid(): boolean {
|
||||
return this.errors.length === 0;
|
||||
}
|
||||
|
||||
errorInfo(): string {
|
||||
return this.errors.join("\n");
|
||||
}
|
||||
|
||||
static Error<T>(error: string): Result<T> {
|
||||
return new Result<T>([error]);
|
||||
}
|
||||
|
||||
static Errors<T>(errors: string[]): Result<T> {
|
||||
return new Result<T>(errors);
|
||||
}
|
||||
|
||||
static Result<T>(result: T) {
|
||||
return new Result<T>([], result);
|
||||
}
|
||||
}
|
||||
@ -20,7 +20,9 @@
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user