proxylang 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -16
- package/dist/cli.js +67 -57
- package/dist/index.d.ts +19 -1
- package/dist/index.js +3 -3
- package/dist/{profile-build-Cokl8MBF.js → profile-build-oexsfBwW.js} +126 -64
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ npm install --save-exact proxylang@0.3.0
|
|
|
28
28
|
npx proxylang --help
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
将下面的 Usage 示例保存为 `
|
|
31
|
+
将下面的 Usage 示例保存为 `proxylang.config.ts`,即可执行 `npx proxylang check`。
|
|
32
32
|
|
|
33
33
|
若要运行仓库里的完整示例,另需 **Vite+ 1.3.0**:
|
|
34
34
|
|
|
@@ -39,15 +39,16 @@ vp install --frozen-lockfile
|
|
|
39
39
|
vp run build
|
|
40
40
|
|
|
41
41
|
# 检查现成的四客户端示例,不读取密码
|
|
42
|
-
|
|
42
|
+
cd examples/clients
|
|
43
|
+
vp exec node ../../dist/cli.js check
|
|
43
44
|
|
|
44
45
|
# 用测试密码生成配置,不会启动代理
|
|
45
|
-
DEMO_PASSWORD=example-only vp exec node dist/cli.js build
|
|
46
|
+
DEMO_PASSWORD=example-only vp exec node ../../dist/cli.js build
|
|
46
47
|
```
|
|
47
48
|
|
|
48
49
|
仓库开发统一使用 Vite+:`vp run dev` 监听构建,`vp run check` 检查源码,`vp run verify` 完成源码与隔离安装包验收。`vp add` / `vp remove` 管理依赖,提交更新后的 `package-lock.json`。
|
|
49
50
|
|
|
50
|
-
[四客户端示例](examples/clients.ts)展示完整配置;下面从规则开始,逐步写出自己的版本。
|
|
51
|
+
[四客户端示例](examples/clients/proxylang.config.ts)展示完整配置;下面从规则开始,逐步写出自己的版本。
|
|
51
52
|
|
|
52
53
|
## 直接组合设备配置
|
|
53
54
|
|
|
@@ -82,7 +83,7 @@ const laptop = defineProfile({
|
|
|
82
83
|
|
|
83
84
|
## Usage
|
|
84
85
|
|
|
85
|
-
将下面三个 TypeScript 代码块按顺序保存为项目中的 `
|
|
86
|
+
将下面三个 TypeScript 代码块按顺序保存为项目中的 `proxylang.config.ts`。
|
|
86
87
|
|
|
87
88
|
### 1. 组合规则,给出口留一个位置
|
|
88
89
|
|
|
@@ -200,6 +201,7 @@ const program = (engine: Engine): Program => ({
|
|
|
200
201
|
});
|
|
201
202
|
|
|
202
203
|
export default defineConfig({
|
|
204
|
+
outDir: "out",
|
|
203
205
|
programs: {
|
|
204
206
|
desktop: program("surge"),
|
|
205
207
|
backup: program("sing-box"),
|
|
@@ -225,14 +227,14 @@ export default defineConfig({
|
|
|
225
227
|
|
|
226
228
|
```sh
|
|
227
229
|
# 检查所有目标和请求案例
|
|
228
|
-
npx proxylang check
|
|
230
|
+
npx proxylang check
|
|
229
231
|
|
|
230
232
|
# 查看请求命中了哪条规则,以及规则来自哪个模板
|
|
231
|
-
npx proxylang explain
|
|
233
|
+
npx proxylang explain --target backup \
|
|
232
234
|
--request '{"network":"tcp","domain":"github.com","port":443}'
|
|
233
235
|
|
|
234
236
|
# 用测试密码构建;实际使用时由环境提供真实凭据
|
|
235
|
-
PROXY_PASSWORD=example-only npx proxylang build
|
|
237
|
+
PROXY_PASSWORD=example-only npx proxylang build
|
|
236
238
|
```
|
|
237
239
|
|
|
238
240
|
`explain` 展示条件匹配与逻辑出口,不模拟节点测速或网络连通性。`build` 生成原生配置,整批成功后更新 `out/active.json`,其中列出各目标文件路径;一个目标失败不会替换上一批结果。
|
|
@@ -246,7 +248,7 @@ PROXY_PASSWORD=example-only npx proxylang build proxy.config.ts --out out
|
|
|
246
248
|
把请求元数据保存为 UTF-8 JSON,避免 shell 转义:
|
|
247
249
|
|
|
248
250
|
```sh
|
|
249
|
-
npx proxylang explain
|
|
251
|
+
npx proxylang explain --target backup --request-file request.json
|
|
250
252
|
npx proxylang build --help
|
|
251
253
|
```
|
|
252
254
|
|
|
@@ -276,7 +278,7 @@ const mediaRule = rule("media", match.all(match.network("tcp"), media), direct()
|
|
|
276
278
|
|
|
277
279
|
Surge 顶层引用可设置 `intervalSeconds`;嵌套逻辑使用客户端默认更新间隔,显式间隔暂报不支持。sing-box 与 Mihomo 的更新间隔是必填项,嵌套组合仍引用独立声明的资源。Stash 原生外部规则入口尚未实现。
|
|
278
280
|
|
|
279
|
-
完整的三平台组合与构建示例见 [examples/rule-sets.ts](examples/rule-sets.ts)。示例 URL 仅展示语法,实际使用时替换为自己的规则源。更完整的平台逃生舱边界见[设计说明](docs/engineering/composable-rule-sets/README.md)。
|
|
281
|
+
完整的三平台组合与构建示例见 [examples/rule-sets/proxylang.config.ts](examples/rule-sets/proxylang.config.ts)。示例 URL 仅展示语法,实际使用时替换为自己的规则源。更完整的平台逃生舱边界见[设计说明](docs/engineering/composable-rule-sets/README.md)。
|
|
280
282
|
|
|
281
283
|
## 定义代理节点
|
|
282
284
|
|
|
@@ -383,12 +385,13 @@ const backup: Program = {
|
|
|
383
385
|
|
|
384
386
|
构建只生成配置,不加入 tailnet、不创建身份目录、不启用 MagicDNS。状态目录应由单个运行实例独占,并独立于构建产物;端点暂不能放进策略组或作为 `via`。这是本机显式代理配置,尚不是 TUN 网关或已验收的整机备份。
|
|
385
387
|
|
|
386
|
-
[完整节点与 Tailscale 示例](examples/proxies.ts)包含五个构建目标和共用规则,可直接检查:
|
|
388
|
+
[完整节点与 Tailscale 示例](examples/proxies/proxylang.config.ts)包含五个构建目标和共用规则,可直接检查:
|
|
387
389
|
|
|
388
390
|
```sh
|
|
389
|
-
|
|
391
|
+
cd examples/proxies
|
|
392
|
+
vp exec node ../../dist/cli.js check
|
|
390
393
|
DEMO_PASSWORD=example-only DEMO_UUID=11111111-2222-4333-8444-555555555555 \
|
|
391
|
-
vp exec node dist/cli.js build
|
|
394
|
+
vp exec node ../../dist/cli.js build
|
|
392
395
|
```
|
|
393
396
|
|
|
394
397
|
## 当前支持
|
|
@@ -408,9 +411,23 @@ Stash 当前拒绝来源 IP/端口、端口范围和组级 URLTest。完整配
|
|
|
408
411
|
|
|
409
412
|
## 更多示例与文档
|
|
410
413
|
|
|
411
|
-
- [代理协议与 Tailscale](examples/proxies.ts):SS/VMess/VLESS 节点和独立家庭网络端点。
|
|
412
|
-
- [四客户端共用规则](examples/clients.ts):同一个 policy,不同平台策略。
|
|
414
|
+
- [代理协议与 Tailscale](examples/proxies/proxylang.config.ts):SS/VMess/VLESS 节点和独立家庭网络端点。
|
|
415
|
+
- [四客户端共用规则](examples/clients/proxylang.config.ts):同一个 policy,不同平台策略。
|
|
413
416
|
- [家庭与开发环境规则](examples/policies.ts):规则模块、守卫与出口绑定。
|
|
414
|
-
- [多设备配置与请求案例](examples/home.ts):节点筛选、代理链和路由回归案例。
|
|
417
|
+
- [多设备配置与请求案例](examples/home/proxylang.config.ts):节点筛选、代理链和路由回归案例。
|
|
415
418
|
- [设计与使用文档](docs/README.md):规则组合、平台机制、CLI 与构建边界。
|
|
416
419
|
- [开发工作流](docs/engineering/development/README.md):Concord 管理 Feature 与 Use Case,`vp` 负责构建和测试。
|
|
420
|
+
|
|
421
|
+
### 按域名指定 DNS
|
|
422
|
+
|
|
423
|
+
同一服务器的多个域名可以一起声明,Profile 的 `dns` 支持数组片段组合:
|
|
424
|
+
|
|
425
|
+
```ts
|
|
426
|
+
import { dnsRule } from "proxylang";
|
|
427
|
+
|
|
428
|
+
const domestic = dnsRule(["*.example.cn", "example.cn"], "https://223.5.5.5/dns-query");
|
|
429
|
+
const tailnet = dnsRule("*.ts.net", "100.100.100.100");
|
|
430
|
+
// defineProfile({ ..., dns: [domestic, tailnet] })
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
`*.example.cn` 仅匹配子域,根域需单独列出。函数保留输入顺序,沿用既有 DNS 冲突检查;`DnsRule` 类型仍可用于类型标注。
|
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import { open } from "node:fs/promises";
|
|
2
|
+
import { H as StaticRuleSetUnknownError, N as compile, P as explain, R as targetCatalog, i as buildToDirectory, n as defineBuild, q as requestSchema, r as runBuild, t as checkBuild } from "./profile-build-oexsfBwW.js";
|
|
3
|
+
import { lstat, open, stat } from "node:fs/promises";
|
|
4
4
|
import { resolve } from "node:path";
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
6
|
import { constants } from "node:fs";
|
|
@@ -15,11 +15,10 @@ const failure = (code) => {
|
|
|
15
15
|
return 1;
|
|
16
16
|
};
|
|
17
17
|
const usages = {
|
|
18
|
-
"profile-build": ["proxylang profile-build config.ts --out DIRECTORY [--validation]"],
|
|
19
18
|
targets: ["proxylang targets"],
|
|
20
|
-
check: ["proxylang check
|
|
21
|
-
explain: ["proxylang explain
|
|
22
|
-
build: ["proxylang build
|
|
19
|
+
check: ["proxylang check"],
|
|
20
|
+
explain: ["proxylang explain --target ID --request JSON", "proxylang explain --target ID --request-file FILE"],
|
|
21
|
+
build: ["proxylang build [--validation]"]
|
|
23
22
|
};
|
|
24
23
|
async function readRequestFile(path) {
|
|
25
24
|
const limit = 1048576;
|
|
@@ -71,39 +70,56 @@ function loadFailure(cause) {
|
|
|
71
70
|
return 1;
|
|
72
71
|
}
|
|
73
72
|
async function main(args) {
|
|
74
|
-
const
|
|
73
|
+
const root = process.cwd();
|
|
74
|
+
const [command, ...rest] = args;
|
|
75
75
|
if (command === "targets" && args.length === 1) {
|
|
76
76
|
print(targetCatalog);
|
|
77
77
|
return 0;
|
|
78
78
|
}
|
|
79
79
|
const help = (value) => value === "--help" || value === "-h";
|
|
80
|
-
if (!command || help(command) && args.length === 1 || Object.hasOwn(usages, command) && help(
|
|
80
|
+
if (!command || help(command) && args.length === 1 || Object.hasOwn(usages, command) && help(rest[0]) && rest.length === 1) {
|
|
81
81
|
print({
|
|
82
82
|
usage: command && Object.hasOwn(usages, command) ? usages[command] : Object.values(usages).flat(),
|
|
83
|
+
configFile: "proxylang.config.ts",
|
|
83
84
|
trustedConfig: true
|
|
84
85
|
});
|
|
85
86
|
return 0;
|
|
86
87
|
}
|
|
87
|
-
if (command === "profile-build") return profileBuildCommand(file, rest);
|
|
88
88
|
if (![
|
|
89
89
|
"check",
|
|
90
90
|
"explain",
|
|
91
91
|
"build"
|
|
92
|
-
].includes(command)
|
|
92
|
+
].includes(command)) return failure("INVALID_ARGUMENTS");
|
|
93
93
|
const options = /* @__PURE__ */ new Map();
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
if (
|
|
98
|
-
|
|
94
|
+
let validation = false;
|
|
95
|
+
if (command === "build") {
|
|
96
|
+
if (rest.length === 1 && rest[0] === "--validation" || rest.length === 2 && rest[0] === "--" && rest[1] === "--validation") validation = true;
|
|
97
|
+
else if (rest.length) return failure("INVALID_ARGUMENTS");
|
|
98
|
+
} else if (command === "check") {
|
|
99
|
+
if (rest.length) return failure("INVALID_ARGUMENTS");
|
|
100
|
+
} else {
|
|
101
|
+
for (let i = 0; i < rest.length; i += 2) {
|
|
102
|
+
const key = rest[i];
|
|
103
|
+
const value = rest[i + 1];
|
|
104
|
+
if (![
|
|
105
|
+
"--target",
|
|
106
|
+
"--request",
|
|
107
|
+
"--request-file"
|
|
108
|
+
].includes(key) || !value?.trim() || value.startsWith("--") || options.has(key)) return failure("INVALID_ARGUMENTS");
|
|
109
|
+
options.set(key, value);
|
|
110
|
+
}
|
|
111
|
+
if (!options.has("--target") || options.has("--request") === options.has("--request-file")) return failure("INVALID_ARGUMENTS");
|
|
112
|
+
}
|
|
113
|
+
const file = resolve(root, "proxylang.config.ts");
|
|
114
|
+
let found = false;
|
|
115
|
+
try {
|
|
116
|
+
const info = await lstat(file);
|
|
117
|
+
found = true;
|
|
118
|
+
if (!(info.isSymbolicLink() ? (await stat(file)).isFile() : info.isFile())) return loadFailure({ code: "INVALID_CONFIG_FILE" });
|
|
119
|
+
} catch (cause) {
|
|
120
|
+
if (!found && cause && typeof cause === "object" && Object.getOwnPropertyDescriptor(cause, "code")?.value === "ENOENT") return failure("CONFIG_NOT_FOUND");
|
|
121
|
+
return loadFailure(cause);
|
|
99
122
|
}
|
|
100
|
-
const allowed = command === "check" ? [] : command === "build" ? ["--out"] : [
|
|
101
|
-
"--target",
|
|
102
|
-
"--request",
|
|
103
|
-
"--request-file"
|
|
104
|
-
];
|
|
105
|
-
const required = command === "check" ? [] : command === "build" ? ["--out"] : ["--target"];
|
|
106
|
-
if ([...options.keys()].some((key) => !allowed.includes(key)) || required.some((key) => !options.has(key)) || command === "explain" && options.has("--request") === options.has("--request-file")) return failure("INVALID_ARGUMENTS");
|
|
107
123
|
let config;
|
|
108
124
|
try {
|
|
109
125
|
const loaded = await tsImport(pathToFileURL(resolve(file)).href, import.meta.url);
|
|
@@ -111,6 +127,31 @@ async function main(args) {
|
|
|
111
127
|
} catch (cause) {
|
|
112
128
|
return loadFailure(cause);
|
|
113
129
|
}
|
|
130
|
+
if (config && typeof config === "object" ? Object.getOwnPropertyDescriptor(config, "profiles") : void 0) {
|
|
131
|
+
let definition;
|
|
132
|
+
try {
|
|
133
|
+
definition = defineBuild(config);
|
|
134
|
+
if (definition.outDir !== void 0) definition = {
|
|
135
|
+
...definition,
|
|
136
|
+
outDir: resolve(root, definition.outDir)
|
|
137
|
+
};
|
|
138
|
+
} catch {
|
|
139
|
+
return failure("INVALID_BUILD_DEFINITION");
|
|
140
|
+
}
|
|
141
|
+
if (command !== "build") {
|
|
142
|
+
const checked = checkBuild(definition);
|
|
143
|
+
if (!checked.ok || command === "check") {
|
|
144
|
+
print(checked);
|
|
145
|
+
return checked.ok ? 0 : 1;
|
|
146
|
+
}
|
|
147
|
+
return failure("EXPLAIN_PROFILE_UNSUPPORTED");
|
|
148
|
+
}
|
|
149
|
+
if (definition.outDir === void 0) return failure("OUTPUT_DIRECTORY_REQUIRED");
|
|
150
|
+
const built = await runBuild(definition, definition.outDir, { validation });
|
|
151
|
+
print(built);
|
|
152
|
+
return built.exitCode;
|
|
153
|
+
}
|
|
154
|
+
if (validation) return failure("VALIDATION_PROFILE_REQUIRED");
|
|
114
155
|
const result = compile(config);
|
|
115
156
|
if (!result.ok) {
|
|
116
157
|
print({
|
|
@@ -139,7 +180,7 @@ async function main(args) {
|
|
|
139
180
|
if (command === "explain") {
|
|
140
181
|
let source = options.get("--request");
|
|
141
182
|
if (options.has("--request-file")) try {
|
|
142
|
-
source = await readRequestFile(options.get("--request-file"));
|
|
183
|
+
source = await readRequestFile(resolve(root, options.get("--request-file")));
|
|
143
184
|
} catch (cause) {
|
|
144
185
|
return failure(cause instanceof Error && cause.message === "REQUEST_FILE_TOO_LARGE" ? "REQUEST_FILE_TOO_LARGE" : "REQUEST_FILE_READ_FAILED");
|
|
145
186
|
}
|
|
@@ -158,46 +199,15 @@ async function main(args) {
|
|
|
158
199
|
});
|
|
159
200
|
return 0;
|
|
160
201
|
}
|
|
161
|
-
const
|
|
202
|
+
const outDir = Object.getOwnPropertyDescriptor(config, "outDir")?.value;
|
|
203
|
+
if (outDir === void 0) return failure("OUTPUT_DIRECTORY_REQUIRED");
|
|
204
|
+
const built = await buildToDirectory(result, resolve(root, outDir));
|
|
162
205
|
print({
|
|
163
206
|
...built,
|
|
164
207
|
diagnostics: result.diagnostics
|
|
165
208
|
});
|
|
166
209
|
return built.exitCode;
|
|
167
210
|
}
|
|
168
|
-
async function profileBuildCommand(file, args) {
|
|
169
|
-
const invalid = () => {
|
|
170
|
-
print(profileBuildFailure("INVALID_ARGUMENTS"));
|
|
171
|
-
return 1;
|
|
172
|
-
};
|
|
173
|
-
if (!file?.trim() || file.startsWith("-")) return invalid();
|
|
174
|
-
let output;
|
|
175
|
-
let validation = false;
|
|
176
|
-
for (let i = 0; i < args.length; i++) {
|
|
177
|
-
const arg = args[i];
|
|
178
|
-
if (arg === "--out" && output === void 0) {
|
|
179
|
-
const value = args[++i];
|
|
180
|
-
if (!value?.trim() || value.startsWith("-")) return invalid();
|
|
181
|
-
output = value;
|
|
182
|
-
} else if (arg === "--validation" && !validation) validation = true;
|
|
183
|
-
else if (arg === "--" && output !== void 0 && !validation && i === args.length - 2 && args[i + 1] === "--validation") {
|
|
184
|
-
validation = true;
|
|
185
|
-
i++;
|
|
186
|
-
} else return invalid();
|
|
187
|
-
}
|
|
188
|
-
if (output === void 0) return invalid();
|
|
189
|
-
let config;
|
|
190
|
-
try {
|
|
191
|
-
const loaded = await tsImport(pathToFileURL(resolve(file)).href, import.meta.url);
|
|
192
|
-
config = loaded.default?.__esModule === true ? loaded.default.default : loaded.default;
|
|
193
|
-
} catch {
|
|
194
|
-
print(profileBuildFailure("PROFILE_DEFINITION_FAILED", validation));
|
|
195
|
-
return 1;
|
|
196
|
-
}
|
|
197
|
-
const result = await runBuild(config, output, { validation });
|
|
198
|
-
print(result);
|
|
199
|
-
return result.exitCode;
|
|
200
|
-
}
|
|
201
211
|
try {
|
|
202
212
|
process.exitCode = await main(process.argv.slice(2));
|
|
203
213
|
} catch (cause) {
|
package/dist/index.d.ts
CHANGED
|
@@ -281,6 +281,7 @@ export type PolicyCase = {
|
|
|
281
281
|
};
|
|
282
282
|
};
|
|
283
283
|
export type Config = {
|
|
284
|
+
readonly outDir?: string;
|
|
284
285
|
readonly programs: Readonly<Record<string, Program>>;
|
|
285
286
|
readonly targets: readonly Target[];
|
|
286
287
|
readonly cases?: readonly PolicyCase[];
|
|
@@ -736,6 +737,8 @@ declare function proxyBuilder<N extends ProxyNode>(node: N): ProxyBuilder<Extrac
|
|
|
736
737
|
}>>;
|
|
737
738
|
//#endregion
|
|
738
739
|
//#region src/dsl.d.ts
|
|
740
|
+
export declare function dnsRule(pattern: string, server: string): DnsRule;
|
|
741
|
+
export declare function dnsRule(patterns: readonly string[], server: string): DnsRule[];
|
|
739
742
|
export declare const ruleSet: (definition: Omit<NamedRuleSet, "type">) => NamedRuleSet;
|
|
740
743
|
type DomainOptions = {
|
|
741
744
|
readonly extendedMatching?: boolean;
|
|
@@ -1121,10 +1124,25 @@ export declare function compileProxyNodes(input: unknown): ProxyNodeCompilation;
|
|
|
1121
1124
|
export declare function renderProxyNodes(compilation: ProxyNodeCompilation, resolveSecret: (token: Secret) => string | undefined): ProxyNodeArtifact;
|
|
1122
1125
|
//#endregion
|
|
1123
1126
|
//#region src/profile-build.d.ts
|
|
1127
|
+
type ProfileCheckResult = {
|
|
1128
|
+
readonly ok: boolean;
|
|
1129
|
+
readonly code: string;
|
|
1130
|
+
readonly profileCount: number;
|
|
1131
|
+
readonly outputDirectoryChecked: boolean;
|
|
1132
|
+
readonly profiles: readonly {
|
|
1133
|
+
readonly id: string;
|
|
1134
|
+
readonly engine: "surge" | "sing-box" | "invalid";
|
|
1135
|
+
readonly ok: boolean;
|
|
1136
|
+
readonly code?: string;
|
|
1137
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
1138
|
+
}[];
|
|
1139
|
+
};
|
|
1140
|
+
export declare function checkBuild(input: BuildDefinition): ProfileCheckResult;
|
|
1124
1141
|
type BuildContext = {
|
|
1125
1142
|
readonly validation: boolean;
|
|
1126
1143
|
};
|
|
1127
1144
|
type BuildDefinition = {
|
|
1145
|
+
readonly outDir?: string;
|
|
1128
1146
|
readonly profiles: Readonly<Record<string, Profile | ProfileDefinition>>;
|
|
1129
1147
|
readonly preflight?: () => readonly string[];
|
|
1130
1148
|
readonly resolveSecret?: (token: Secret, context: BuildContext) => string | undefined;
|
|
@@ -1145,4 +1163,4 @@ export declare function runBuild(input: BuildDefinition, output: string, options
|
|
|
1145
1163
|
/** Stable identity independent of engine and mutable metadata. */
|
|
1146
1164
|
export declare function proxyId(provider: string, label: string): string;
|
|
1147
1165
|
//#endregion
|
|
1148
|
-
export type { Artifact, BuildContext, BuildDefinition, BuildResult, CaseResult, Compilation, DeepReadonly, Fragments, Profile, ProfileBuildResult, ProfileCompilation, ProfileCondition, ProfileDefinition, ProfileDestination, ProfileProxy, ProxyBuilder, ProxyGroupDefinition, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, RouteDefinition, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeConfig, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
|
|
1166
|
+
export type { Artifact, BuildContext, BuildDefinition, BuildResult, CaseResult, Compilation, DeepReadonly, Fragments, Profile, ProfileBuildResult, ProfileCheckResult, ProfileCompilation, ProfileCondition, ProfileDefinition, ProfileDestination, ProfileProxy, ProxyBuilder, ProxyGroupDefinition, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, RouteDefinition, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeConfig, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
1
|
+
import { $ as selectProxies, A as renderSurgeProfile, B as surgeProxy, C as slot, D as compileProfile, E as use, F as compileStrategyGroups, G as idSchema, H as StaticRuleSetUnknownError, I as isReservedNativeName, J as ProfileDefinitionError, K as nodeSchema, L as nativeNameSchema, M as secretReader, N as compile, O as defineProfile, P as explain, Q as outbound, R as targetCatalog, S as singbox, T as surge, U as assertData, V as validateProxyOptions, W as deepFreeze, X as defineRoute, Y as defineProxyGroup, Z as defineRoutes, _ as rule, a as render, b as selectNodes, c as direct, d as match, f as mihomo, g as route, h as reject, i as buildToDirectory, j as renderSurgeProfiles, k as compileSurgeProfile, l as dnsRule, m as proxy, n as defineBuild, o as block, p as policy, r as runBuild, s as defineConfig, t as checkBuild, u as group, v as ruleSet, w as strategy, x as sequence, y as secret, z as RenderError } from "./profile-build-oexsfBwW.js";
|
|
3
2
|
import { z } from "zod";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
4
|
//#region src/proxy-fragments.ts
|
|
5
5
|
const inputSchema = z.strictObject({
|
|
6
6
|
target: z.strictObject({
|
|
@@ -137,4 +137,4 @@ function proxyId(provider, label) {
|
|
|
137
137
|
return `node-${createHash("sha256").update(JSON.stringify([provider, label])).digest("hex").slice(0, 16)}`;
|
|
138
138
|
}
|
|
139
139
|
//#endregion
|
|
140
|
-
export { ProfileDefinitionError, RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProfile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineBuild, defineConfig, defineProfile, defineProxyGroup, defineRoute, defineRoutes, direct, explain, group, match, mihomo, outbound, policy, proxy, proxyId, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, runBuild, secret, selectNodes, selectProxies, sequence, singbox, slot, strategy, surge, targetCatalog, use };
|
|
140
|
+
export { ProfileDefinitionError, RenderError, StaticRuleSetUnknownError, block, buildToDirectory, checkBuild, compile, compileProfile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineBuild, defineConfig, defineProfile, defineProxyGroup, defineRoute, defineRoutes, direct, dnsRule, explain, group, match, mihomo, outbound, policy, proxy, proxyId, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, runBuild, secret, selectNodes, selectProxies, sequence, singbox, slot, strategy, surge, targetCatalog, use };
|
|
@@ -1,10 +1,56 @@
|
|
|
1
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
2
1
|
import { isIP } from "node:net";
|
|
3
2
|
import { z } from "zod";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import ipaddr from "ipaddr.js";
|
|
5
5
|
import { stringify } from "yaml";
|
|
6
6
|
import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
|
|
7
7
|
import { join, resolve } from "node:path";
|
|
8
|
+
//#region src/dns.ts
|
|
9
|
+
const domain$2 = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
10
|
+
function dohUrl(value) {
|
|
11
|
+
const url = new URL(value);
|
|
12
|
+
if (!/^https:\/\/[^/]+\//.test(value)) url.pathname = "/dns-query";
|
|
13
|
+
return url;
|
|
14
|
+
}
|
|
15
|
+
const server = z.string().max(2048).refine((value) => {
|
|
16
|
+
if (isIP(value) && !value.includes("%")) return true;
|
|
17
|
+
if (!value.startsWith("https://") || /[\s\p{C},()\\"'?#]/u.test(value)) return false;
|
|
18
|
+
try {
|
|
19
|
+
const url = new URL(value);
|
|
20
|
+
const authority = value.slice(8).split("/")[0];
|
|
21
|
+
const path = value.slice(8 + authority.length);
|
|
22
|
+
return !url.username && !url.password && !authority.endsWith(":") && !!url.hostname && (!path || url.pathname === path);
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
const dnsRulesSchema = z.array(z.strictObject({
|
|
28
|
+
pattern: z.string().min(1).max(253).refine((value) => domain$2.test(value.startsWith("*.") ? value.slice(2) : value)),
|
|
29
|
+
server
|
|
30
|
+
})).max(2e3).superRefine((rules, ctx) => {
|
|
31
|
+
if (rules.length > 2e3 || rules.some((rule) => rule.pattern.length > 253 || rule.server.length > 2048)) return;
|
|
32
|
+
for (let i = 0; i < rules.length; i++) for (let j = 0; j < i; j++) {
|
|
33
|
+
const a = rules[i], b = rules[j];
|
|
34
|
+
const x = a.pattern.toLowerCase(), y = b.pattern.toLowerCase();
|
|
35
|
+
if (x === y || overlap(x, y) && a.server !== b.server) {
|
|
36
|
+
ctx.addIssue({
|
|
37
|
+
code: "custom",
|
|
38
|
+
message: "DNS_RULE_CONFLICT"
|
|
39
|
+
});
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
function overlap(a, b) {
|
|
45
|
+
const wildA = a.startsWith("*."), wildB = b.startsWith("*.");
|
|
46
|
+
if (wildA && wildB) return a.slice(1).endsWith(b.slice(1)) || b.slice(1).endsWith(a.slice(1));
|
|
47
|
+
return wildA ? b.endsWith(a.slice(1)) : wildB && a.endsWith(b.slice(1));
|
|
48
|
+
}
|
|
49
|
+
function dnsCondition(rule) {
|
|
50
|
+
const pattern = rule.pattern.toLowerCase();
|
|
51
|
+
return pattern.startsWith("*.") ? { domain_regex: [`^.+\\.${pattern.slice(2).replaceAll(".", "\\.")}$`] } : { domain: [pattern] };
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
8
54
|
//#region src/surge-definitions.ts
|
|
9
55
|
var ProfileDefinitionError = class extends Error {
|
|
10
56
|
code;
|
|
@@ -343,52 +389,6 @@ const surgeMatch = {
|
|
|
343
389
|
}
|
|
344
390
|
};
|
|
345
391
|
//#endregion
|
|
346
|
-
//#region src/dns.ts
|
|
347
|
-
const domain$2 = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
348
|
-
function dohUrl(value) {
|
|
349
|
-
const url = new URL(value);
|
|
350
|
-
if (!/^https:\/\/[^/]+\//.test(value)) url.pathname = "/dns-query";
|
|
351
|
-
return url;
|
|
352
|
-
}
|
|
353
|
-
const server = z.string().max(2048).refine((value) => {
|
|
354
|
-
if (isIP(value) && !value.includes("%")) return true;
|
|
355
|
-
if (!value.startsWith("https://") || /[\s\p{C},()\\"'?#]/u.test(value)) return false;
|
|
356
|
-
try {
|
|
357
|
-
const url = new URL(value);
|
|
358
|
-
const authority = value.slice(8).split("/")[0];
|
|
359
|
-
const path = value.slice(8 + authority.length);
|
|
360
|
-
return !url.username && !url.password && !authority.endsWith(":") && !!url.hostname && (!path || url.pathname === path);
|
|
361
|
-
} catch {
|
|
362
|
-
return false;
|
|
363
|
-
}
|
|
364
|
-
});
|
|
365
|
-
const dnsRulesSchema = z.array(z.strictObject({
|
|
366
|
-
pattern: z.string().min(1).max(253).refine((value) => domain$2.test(value.startsWith("*.") ? value.slice(2) : value)),
|
|
367
|
-
server
|
|
368
|
-
})).max(2e3).superRefine((rules, ctx) => {
|
|
369
|
-
if (rules.length > 2e3 || rules.some((rule) => rule.pattern.length > 253 || rule.server.length > 2048)) return;
|
|
370
|
-
for (let i = 0; i < rules.length; i++) for (let j = 0; j < i; j++) {
|
|
371
|
-
const a = rules[i], b = rules[j];
|
|
372
|
-
const x = a.pattern.toLowerCase(), y = b.pattern.toLowerCase();
|
|
373
|
-
if (x === y || overlap(x, y) && a.server !== b.server) {
|
|
374
|
-
ctx.addIssue({
|
|
375
|
-
code: "custom",
|
|
376
|
-
message: "DNS_RULE_CONFLICT"
|
|
377
|
-
});
|
|
378
|
-
return;
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
});
|
|
382
|
-
function overlap(a, b) {
|
|
383
|
-
const wildA = a.startsWith("*."), wildB = b.startsWith("*.");
|
|
384
|
-
if (wildA && wildB) return a.slice(1).endsWith(b.slice(1)) || b.slice(1).endsWith(a.slice(1));
|
|
385
|
-
return wildA ? b.endsWith(a.slice(1)) : wildB && a.endsWith(b.slice(1));
|
|
386
|
-
}
|
|
387
|
-
function dnsCondition(rule) {
|
|
388
|
-
const pattern = rule.pattern.toLowerCase();
|
|
389
|
-
return pattern.startsWith("*.") ? { domain_regex: [`^.+\\.${pattern.slice(2).replaceAll(".", "\\.")}$`] } : { domain: [pattern] };
|
|
390
|
-
}
|
|
391
|
-
//#endregion
|
|
392
392
|
//#region src/schema.ts
|
|
393
393
|
const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
|
|
394
394
|
const domain$1 = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/);
|
|
@@ -698,6 +698,7 @@ const requestSchema = z.strictObject({
|
|
|
698
698
|
sourcePort: port$1.optional()
|
|
699
699
|
});
|
|
700
700
|
const configSchema = z.strictObject({
|
|
701
|
+
outDir: z.string().min(1).refine((value) => value.trim() === value && !value.includes("\0")).optional(),
|
|
701
702
|
programs: z.record(idSchema, z.strictObject({
|
|
702
703
|
engine: z.enum([
|
|
703
704
|
"surge",
|
|
@@ -2697,6 +2698,21 @@ function proxyBuilder(node) {
|
|
|
2697
2698
|
}
|
|
2698
2699
|
//#endregion
|
|
2699
2700
|
//#region src/dsl.ts
|
|
2701
|
+
function dnsRule(pattern, server) {
|
|
2702
|
+
inspectDefinition({
|
|
2703
|
+
pattern,
|
|
2704
|
+
server
|
|
2705
|
+
});
|
|
2706
|
+
const batch = Array.isArray(pattern);
|
|
2707
|
+
const patterns = batch ? pattern : [pattern];
|
|
2708
|
+
if (patterns.length > 2e3) throw new ProfileDefinitionError("INVALID_DNS_RULE");
|
|
2709
|
+
const checked = dnsRulesSchema.safeParse(patterns.map((value) => ({
|
|
2710
|
+
pattern: value,
|
|
2711
|
+
server
|
|
2712
|
+
})));
|
|
2713
|
+
if (!checked.success) throw new ProfileDefinitionError("INVALID_DNS_RULE");
|
|
2714
|
+
return batch ? checked.data : checked.data[0];
|
|
2715
|
+
}
|
|
2700
2716
|
const ruleSet = (definition) => ({
|
|
2701
2717
|
...definition,
|
|
2702
2718
|
type: "ruleSet"
|
|
@@ -3388,26 +3404,67 @@ async function publishProfiles(files, surgeDirectory, io = { rename }) {
|
|
|
3388
3404
|
}
|
|
3389
3405
|
//#endregion
|
|
3390
3406
|
//#region src/profile-build.ts
|
|
3391
|
-
|
|
3407
|
+
function compileBatch(profiles, output) {
|
|
3408
|
+
const entries = Object.entries(profiles);
|
|
3409
|
+
const compiled = [];
|
|
3410
|
+
let outputDirectoryChecked = false;
|
|
3411
|
+
const result = (code) => ({
|
|
3412
|
+
ok: code === "CHECKED",
|
|
3413
|
+
code,
|
|
3414
|
+
entries,
|
|
3415
|
+
compiled,
|
|
3416
|
+
outputDirectoryChecked
|
|
3417
|
+
});
|
|
3418
|
+
if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return result("INVALID_PROFILE_FILENAMES");
|
|
3419
|
+
compiled.push(...entries.map(([, profile]) => compileProfile(profile)));
|
|
3420
|
+
const invalid = compiled.find((profile) => !profile.ok);
|
|
3421
|
+
if (invalid) return result(invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED");
|
|
3422
|
+
if (output !== void 0) {
|
|
3423
|
+
outputDirectoryChecked = true;
|
|
3424
|
+
if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(output, endpoint.stateDirectory))))) return result("ENDPOINT_STATE_OVERLAP");
|
|
3425
|
+
}
|
|
3426
|
+
return result("CHECKED");
|
|
3427
|
+
}
|
|
3428
|
+
function checkBuild(input) {
|
|
3429
|
+
const root = process.cwd();
|
|
3430
|
+
let definition;
|
|
3392
3431
|
try {
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
code: "
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
if (invalid) return {
|
|
3402
|
-
published: false,
|
|
3403
|
-
exitCode: 1,
|
|
3404
|
-
code: invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED"
|
|
3432
|
+
definition = defineBuild(input);
|
|
3433
|
+
} catch {
|
|
3434
|
+
return {
|
|
3435
|
+
ok: false,
|
|
3436
|
+
code: "INVALID_BUILD_DEFINITION",
|
|
3437
|
+
profileCount: 0,
|
|
3438
|
+
outputDirectoryChecked: false,
|
|
3439
|
+
profiles: []
|
|
3405
3440
|
};
|
|
3406
|
-
|
|
3441
|
+
}
|
|
3442
|
+
const checked = compileBatch(definition.profiles, definition.outDir === void 0 ? void 0 : resolve(root, definition.outDir));
|
|
3443
|
+
return {
|
|
3444
|
+
ok: checked.ok,
|
|
3445
|
+
code: checked.code,
|
|
3446
|
+
profileCount: checked.entries.length,
|
|
3447
|
+
outputDirectoryChecked: checked.outputDirectoryChecked,
|
|
3448
|
+
profiles: checked.compiled.map((profile, index) => ({
|
|
3449
|
+
id: checked.entries[index][0],
|
|
3450
|
+
engine: profile.engine,
|
|
3451
|
+
ok: profile.ok,
|
|
3452
|
+
...profile.engine === "invalid" ? {
|
|
3453
|
+
code: profile.code,
|
|
3454
|
+
diagnostics: []
|
|
3455
|
+
} : { diagnostics: profile.compilation.diagnostics }
|
|
3456
|
+
}))
|
|
3457
|
+
};
|
|
3458
|
+
}
|
|
3459
|
+
async function publish(profiles, output, resolver) {
|
|
3460
|
+
try {
|
|
3461
|
+
const checked = compileBatch(profiles, output);
|
|
3462
|
+
if (!checked.ok) return {
|
|
3407
3463
|
published: false,
|
|
3408
3464
|
exitCode: 1,
|
|
3409
|
-
code:
|
|
3465
|
+
code: checked.code
|
|
3410
3466
|
};
|
|
3467
|
+
const { entries, compiled } = checked;
|
|
3411
3468
|
const read = secretReader(resolver);
|
|
3412
3469
|
const files = /* @__PURE__ */ new Map();
|
|
3413
3470
|
for (const [index, profile] of compiled.entries()) {
|
|
@@ -3450,11 +3507,14 @@ function defineBuild(input) {
|
|
|
3450
3507
|
record(input, [
|
|
3451
3508
|
"profiles",
|
|
3452
3509
|
"preflight",
|
|
3453
|
-
"resolveSecret"
|
|
3510
|
+
"resolveSecret",
|
|
3511
|
+
"outDir"
|
|
3454
3512
|
]);
|
|
3513
|
+
if (input.outDir !== void 0 && (typeof input.outDir !== "string" || !input.outDir.trim() || input.outDir.trim() !== input.outDir || input.outDir.includes("\0"))) throw new Error();
|
|
3455
3514
|
record(input.profiles);
|
|
3456
3515
|
for (const callback of [input.preflight, input.resolveSecret]) if (callback !== void 0 && typeof callback !== "function") throw new Error();
|
|
3457
3516
|
return Object.freeze({
|
|
3517
|
+
...input.outDir === void 0 ? {} : { outDir: input.outDir },
|
|
3458
3518
|
profiles: snapshotProfile(input.profiles),
|
|
3459
3519
|
...input.preflight === void 0 ? {} : { preflight: input.preflight },
|
|
3460
3520
|
...input.resolveSecret === void 0 ? {} : { resolveSecret: input.resolveSecret }
|
|
@@ -3475,6 +3535,7 @@ function profileBuildFailure(code, validation = false, profileCount = 0) {
|
|
|
3475
3535
|
}
|
|
3476
3536
|
/** Pure orchestration result; the CLI owns stdout and process exit status. */
|
|
3477
3537
|
async function runBuild(input, output, options = {}) {
|
|
3538
|
+
const root = process.cwd();
|
|
3478
3539
|
let validation;
|
|
3479
3540
|
try {
|
|
3480
3541
|
record(options, ["validation"]);
|
|
@@ -3492,6 +3553,7 @@ async function runBuild(input, output, options = {}) {
|
|
|
3492
3553
|
const profileCount = Object.keys(definition.profiles).length;
|
|
3493
3554
|
const failure = (code) => profileBuildFailure(code, validation, profileCount);
|
|
3494
3555
|
if (typeof output !== "string" || !output.trim()) return failure("INVALID_OUTPUT_DIRECTORY");
|
|
3556
|
+
output = resolve(root, output);
|
|
3495
3557
|
if (validation && !definition.resolveSecret) return failure("VALIDATION_RESOLVER_REQUIRED");
|
|
3496
3558
|
let codes;
|
|
3497
3559
|
try {
|
|
@@ -3517,4 +3579,4 @@ async function runBuild(input, output, options = {}) {
|
|
|
3517
3579
|
};
|
|
3518
3580
|
}
|
|
3519
3581
|
//#endregion
|
|
3520
|
-
export {
|
|
3582
|
+
export { selectProxies as $, renderSurgeProfile as A, surgeProxy as B, slot as C, compileProfile as D, use as E, compileStrategyGroups as F, idSchema as G, StaticRuleSetUnknownError as H, isReservedNativeName as I, ProfileDefinitionError as J, nodeSchema as K, nativeNameSchema as L, secretReader as M, compile as N, defineProfile as O, explain as P, outbound as Q, targetCatalog as R, singbox$1 as S, surge$1 as T, assertData as U, validateProxyOptions as V, deepFreeze as W, defineRoute as X, defineProxyGroup as Y, defineRoutes as Z, rule as _, render as a, selectNodes as b, direct as c, match as d, mihomo as f, route as g, reject as h, buildToDirectory as i, renderSurgeProfiles as j, compileSurgeProfile as k, dnsRule as l, proxy as m, defineBuild as n, block as o, policy as p, requestSchema as q, runBuild as r, defineConfig as s, checkBuild as t, group as u, ruleSet as v, strategy as w, sequence as x, secret as y, RenderError as z };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "proxylang",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Composable routing policies in TypeScript with explicit platform targets",
|
|
5
5
|
"homepage": "https://github.com/CorrectRoadH/proxylang#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -36,8 +36,8 @@
|
|
|
36
36
|
"check": "vp pack && vp check && vp run typecheck && vp test run",
|
|
37
37
|
"docs:check": "concord check --fresh",
|
|
38
38
|
"docs:gaps": "concord trace gaps --fresh",
|
|
39
|
-
"example:check": "vp exec node dist/cli.js check
|
|
40
|
-
"example:build": "vp exec node dist/cli.js build
|
|
39
|
+
"example:check": "cd examples/home && vp exec node ../../dist/cli.js check",
|
|
40
|
+
"example:build": "cd examples/home && vp exec node ../../dist/cli.js build",
|
|
41
41
|
"test:package": "vp pack && vp exec node scripts/verify-package.mjs"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|