mirror of
https://github.com/sub-store-org/Sub-Store.git
synced 2025-08-10 00:52:40 +00:00
Compare commits
169 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33e5aeceb5 | ||
|
|
837667edc9 | ||
|
|
0069b0ce83 | ||
|
|
fcc9d047ae | ||
|
|
382d22e622 | ||
|
|
06f3e97af2 | ||
|
|
bd87e9231e | ||
|
|
d1d6d19542 | ||
|
|
08bf0b78bb | ||
|
|
9a3cd4f57c | ||
|
|
d015c7867e | ||
|
|
4713b63083 | ||
|
|
dbf9e7c360 | ||
|
|
4ea84118c4 | ||
|
|
dda8113a42 | ||
|
|
f16b2d34f1 | ||
|
|
5b28e1a4c9 | ||
|
|
8d0a71d983 | ||
|
|
815552d470 | ||
|
|
9d90369594 | ||
|
|
6aece471aa | ||
|
|
99396773f6 | ||
|
|
e229408a2d | ||
|
|
514414587b | ||
|
|
d4c419745e | ||
|
|
fe3da254f4 | ||
|
|
7d8132d7cd | ||
|
|
bc1247efaf | ||
|
|
dea937df66 | ||
|
|
cfb5a8e082 | ||
|
|
4790bf47d1 | ||
|
|
56fd495fb6 | ||
|
|
f4639d9a34 | ||
|
|
cc58a5541e | ||
|
|
772f431887 | ||
|
|
2b60c515cd | ||
|
|
c8c22c3901 | ||
|
|
d8f9466b84 | ||
|
|
d12ccad382 | ||
|
|
b4358663cc | ||
|
|
aba6264988 | ||
|
|
2320ab3838 | ||
|
|
542957d34a | ||
|
|
07e50175f9 | ||
|
|
e09d66060d | ||
|
|
b048ecdfff | ||
|
|
aac72fb9a3 | ||
|
|
baec193e5c | ||
|
|
8fe818f826 | ||
|
|
72286984ec | ||
|
|
27e693c308 | ||
|
|
6cf8080cd3 | ||
|
|
839fcacf63 | ||
|
|
a2e45bcb10 | ||
|
|
ea0eb91691 | ||
|
|
1f0ddf2d28 | ||
|
|
a660c6ff90 | ||
|
|
71d9adbc07 | ||
|
|
97bec9183a | ||
|
|
ef85b6d0e9 | ||
|
|
8ffb060cb4 | ||
|
|
6d43961e96 | ||
|
|
f3200aea8c | ||
|
|
e2346d16a2 | ||
|
|
dc320eaa6c | ||
|
|
02031019f7 | ||
|
|
5d09fe782f | ||
|
|
6e425e5908 | ||
|
|
d10c9233c0 | ||
|
|
cc556b641d | ||
|
|
de2813b035 | ||
|
|
c9158ceb1d | ||
|
|
5cf0c98f5f | ||
|
|
7d0414f8ca | ||
|
|
bee1d62a1a | ||
|
|
72bc9b9456 | ||
|
|
3b4c14e7d0 | ||
|
|
59d93483bb | ||
|
|
75d88c02c7 | ||
|
|
99d5868cff | ||
|
|
e1489a3cf7 | ||
|
|
59fe16a7b0 | ||
|
|
562d349629 | ||
|
|
9ce14351c5 | ||
|
|
76e781c711 | ||
|
|
f0acf4a2a7 | ||
|
|
9abeb4ce7b | ||
|
|
153802c7c4 | ||
|
|
19418b631f | ||
|
|
97caeed208 | ||
|
|
dd8d1d85e8 | ||
|
|
14ed56b5d5 | ||
|
|
9785271c5b | ||
|
|
05bdf95a29 | ||
|
|
317a804b36 | ||
|
|
10ec8a25a2 | ||
|
|
aa0943a909 | ||
|
|
a0c1bbbf70 | ||
|
|
fea9de4fae | ||
|
|
cddd1818fe | ||
|
|
f94830b2df | ||
|
|
e02a26040e | ||
|
|
6906efdd55 | ||
|
|
9558b63261 | ||
|
|
4bfdef17ee | ||
|
|
9d29fc8a09 | ||
|
|
f524920c13 | ||
|
|
bfe072cbdf | ||
|
|
32dcca4a26 | ||
|
|
a5d77c39c8 | ||
|
|
6ea1b69a62 | ||
|
|
2b3b9177e5 | ||
|
|
91aab3ca7a | ||
|
|
c1a9fc6abc | ||
|
|
11d9ce7372 | ||
|
|
ad3d2270ac | ||
|
|
3ad42f2c10 | ||
|
|
ec06eb8659 | ||
|
|
4a23a4d8b6 | ||
|
|
913638a233 | ||
|
|
bf642ce0e6 | ||
|
|
1ecac9da92 | ||
|
|
c5a417da8f | ||
|
|
8cd0545023 | ||
|
|
b6f848a6e6 | ||
|
|
99d058bcf1 | ||
|
|
533103e765 | ||
|
|
cf82764171 | ||
|
|
7b783c1fe3 | ||
|
|
372eff9a44 | ||
|
|
d3b5a529d7 | ||
|
|
8049134bb5 | ||
|
|
3f620700a4 | ||
|
|
9e64a68481 | ||
|
|
9ce5916414 | ||
|
|
047c21fe70 | ||
|
|
47849dc6d0 | ||
|
|
af06086c1b | ||
|
|
4a6a147667 | ||
|
|
c6540d14cd | ||
|
|
3db71ec531 | ||
|
|
cf156c2f17 | ||
|
|
e28e2a78fb | ||
|
|
b0a2c709e8 | ||
|
|
5dc2c8ced7 | ||
|
|
d2a65ee0fe | ||
|
|
4dd4ae98ca | ||
|
|
0d41eb467f | ||
|
|
ba1c91a7a5 | ||
|
|
30fa87c172 | ||
|
|
1eaa33948b | ||
|
|
619e256ed8 | ||
|
|
b46209e164 | ||
|
|
a1ba4e273e | ||
|
|
bfc95ed92a | ||
|
|
32f591ec56 | ||
|
|
cea16d8c44 | ||
|
|
93a1ba7b50 | ||
|
|
e6d1aa1150 | ||
|
|
26e83798da | ||
|
|
b083d2d840 | ||
|
|
cf35afcab2 | ||
|
|
d073dfeef8 | ||
|
|
f970ea3361 | ||
|
|
630bac0575 | ||
|
|
7f3cb2b191 | ||
|
|
92e1e4a0fb | ||
|
|
3b85d313fe | ||
|
|
c91d8e28e4 |
10
.github/workflows/main.yml
vendored
10
.github/workflows/main.yml
vendored
@@ -76,8 +76,8 @@ jobs:
|
|||||||
git commit -m "release: ${{ steps.tag.outputs.release_tag }}"
|
git commit -m "release: ${{ steps.tag.outputs.release_tag }}"
|
||||||
git remote add origin "https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}"
|
git remote add origin "https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}"
|
||||||
git push -f -u origin release
|
git push -f -u origin release
|
||||||
- name: Sync to GitLab
|
# - name: Sync to GitLab
|
||||||
env:
|
# env:
|
||||||
GITLAB_PIPELINE_TOKEN: ${{ secrets.GITLAB_PIPELINE_TOKEN }}
|
# GITLAB_PIPELINE_TOKEN: ${{ secrets.GITLAB_PIPELINE_TOKEN }}
|
||||||
run: |
|
# run: |
|
||||||
curl -X POST --fail -F token=$GITLAB_PIPELINE_TOKEN -F ref=master https://gitlab.com/api/v4/projects/48891296/trigger/pipeline
|
# curl -X POST --fail -F token=$GITLAB_PIPELINE_TOKEN -F ref=master https://gitlab.com/api/v4/projects/48891296/trigger/pipeline
|
||||||
|
|||||||
28
README.md
28
README.md
@@ -7,13 +7,13 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p align="center" color="#6a737d">
|
<p align="center" color="#6a737d">
|
||||||
Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.
|
Advanced Subscription Manager for QX, Loon, Surge, Stash, Egern and Shadowrocket.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
[](https://github.com/sub-store-org/Sub-Store/actions/workflows/main.yml)     
|
[](https://github.com/sub-store-org/Sub-Store/actions/workflows/main.yml)     
|
||||||
|
<a href="https://trendshift.io/repositories/4572" target="_blank"><img src="https://trendshift.io/api/badge/repositories/4572" alt="sub-store-org%2FSub-Store | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
[](https://www.buymeacoffee.com/PengYM)
|
[](https://www.buymeacoffee.com/PengYM)
|
||||||
|
|
||||||
Core functionalities:
|
Core functionalities:
|
||||||
|
|
||||||
1. Conversion among various formats.
|
1. Conversion among various formats.
|
||||||
@@ -21,21 +21,26 @@ Core functionalities:
|
|||||||
3. Collect multiple subscriptions in one URL.
|
3. Collect multiple subscriptions in one URL.
|
||||||
|
|
||||||
> The following descriptions of features may not be updated in real-time. Please refer to the actual available features for accurate information.
|
> The following descriptions of features may not be updated in real-time. Please refer to the actual available features for accurate information.
|
||||||
|
|
||||||
## 1. Subscription Conversion
|
## 1. Subscription Conversion
|
||||||
|
|
||||||
### Supported Input Formats
|
### Supported Input Formats
|
||||||
|
|
||||||
|
> ⚠️ Do not use `Shadowrocket` to export URI and then import it as input. It is not a standard URI.
|
||||||
|
|
||||||
|
- [x] Normal Proxy(`socks5`, `socks5+tls`, `http`, `https`(it's ok))
|
||||||
|
|
||||||
|
example: `socks5+tls://user:pass@ip:port#name`
|
||||||
|
|
||||||
- [x] URI(SS, SSR, VMess, VLESS, Trojan, Hysteria, Hysteria 2, TUIC v5, WireGuard)
|
- [x] URI(SS, SSR, VMess, VLESS, Trojan, Hysteria, Hysteria 2, TUIC v5, WireGuard)
|
||||||
- [x] Clash Proxies YAML
|
- [x] Clash Proxies YAML
|
||||||
- [x] Clash Proxy JSON(single line)
|
- [x] Clash Proxy JSON(single line)
|
||||||
- [x] QX (SS, SSR, VMess, Trojan, HTTP, SOCKS5, VLESS)
|
- [x] QX (SS, SSR, VMess, Trojan, HTTP, SOCKS5, VLESS)
|
||||||
- [x] Loon (SS, SSR, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard, VLESS, Hysteria 2)
|
- [x] Loon (SS, SSR, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard, VLESS, Hysteria 2)
|
||||||
- [x] Surge (SS, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, TUIC, Snell, Hysteria 2, SSH(Password authentication only), SSR(external, only for macOS), External Proxy Program(only for macOS), WireGuard(Surge to Surge))
|
- [x] Surge (Direct, SS, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, TUIC, Snell, Hysteria 2, SSH(Password authentication only), External Proxy Program(only for macOS), WireGuard(Surge to Surge))
|
||||||
- [x] Surfboard (SS, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard(Surfboard to Surfboard))
|
- [x] Surfboard (SS, VMess, Trojan, HTTP, SOCKS5, SOCKS5-TLS, WireGuard(Surfboard to Surfboard))
|
||||||
- [x] Shadowrocket (SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, Hysteria 2, TUIC)
|
- [x] Clash.Meta (Direct, SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, Hysteria 2, TUIC)
|
||||||
- [x] Clash.Meta (SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, Hysteria 2, TUIC)
|
- [x] Stash (SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, TUIC, Juicity, SSH)
|
||||||
- [x] Stash (SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard, Hysteria, TUIC)
|
|
||||||
- [x] Clash (SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard)
|
- [x] Clash (SS, SSR, VMess, Trojan, HTTP, SOCKS5, Snell, VLESS, WireGuard)
|
||||||
|
|
||||||
### Supported Target Platforms
|
### Supported Target Platforms
|
||||||
@@ -46,7 +51,9 @@ Core functionalities:
|
|||||||
- [x] Clash
|
- [x] Clash
|
||||||
- [x] Surfboard
|
- [x] Surfboard
|
||||||
- [x] Surge
|
- [x] Surge
|
||||||
|
- [x] SurgeMac(Use mihomo to support protocols that are not supported by Surge itself)
|
||||||
- [x] Loon
|
- [x] Loon
|
||||||
|
- [x] Egern
|
||||||
- [x] Shadowrocket
|
- [x] Shadowrocket
|
||||||
- [x] QX
|
- [x] QX
|
||||||
- [x] sing-box
|
- [x] sing-box
|
||||||
@@ -98,7 +105,7 @@ or
|
|||||||
esbuild(experimental)
|
esbuild(experimental)
|
||||||
|
|
||||||
```
|
```
|
||||||
pnpm run --parallel "/^dev:.*/"
|
SUB_STORE_BACKEND_API_PORT=3000 pnpm run --parallel "/^dev:.*/"
|
||||||
```
|
```
|
||||||
|
|
||||||
## LICENSE
|
## LICENSE
|
||||||
@@ -111,7 +118,6 @@ This project is under the GPL V3 LICENSE.
|
|||||||
|
|
||||||
[](https://star-history.com/#sub-store-org/sub-store&Date)
|
[](https://star-history.com/#sub-store-org/sub-store&Date)
|
||||||
|
|
||||||
|
|
||||||
## Acknowledgements
|
## Acknowledgements
|
||||||
|
|
||||||
- Special thanks to @KOP-XIAO for his awesome resource-parser. Please give a [star](https://github.com/KOP-XIAO/QuantumultX) for his great work!
|
- Special thanks to @KOP-XIAO for his awesome resource-parser. Please give a [star](https://github.com/KOP-XIAO/QuantumultX) for his great work!
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "sub-store",
|
"name": "sub-store",
|
||||||
"version": "2.14.301",
|
"version": "2.14.448",
|
||||||
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and ShadowRocket.",
|
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and ShadowRocket.",
|
||||||
"main": "src/main.js",
|
"main": "src/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -17,19 +17,23 @@
|
|||||||
"author": "Peng-YM",
|
"author": "Peng-YM",
|
||||||
"license": "GPL-3.0",
|
"license": "GPL-3.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@maxmind/geoip2-node": "^5.0.0",
|
||||||
"automerge": "1.0.1-preview.7",
|
"automerge": "1.0.1-preview.7",
|
||||||
"body-parser": "^1.19.0",
|
"body-parser": "^1.19.0",
|
||||||
|
"buffer": "^6.0.3",
|
||||||
"connect-history-api-fallback": "^2.0.0",
|
"connect-history-api-fallback": "^2.0.0",
|
||||||
"cron": "^3.1.6",
|
"cron": "^3.1.6",
|
||||||
|
"dns-packet": "^5.6.1",
|
||||||
"express": "^4.17.1",
|
"express": "^4.17.1",
|
||||||
"http-proxy-middleware": "^2.0.6",
|
"http-proxy-middleware": "^2.0.6",
|
||||||
|
"ip-address": "^9.0.5",
|
||||||
"js-base64": "^3.7.2",
|
"js-base64": "^3.7.2",
|
||||||
|
"jsrsasign": "^11.1.0",
|
||||||
"lodash": "^4.17.21",
|
"lodash": "^4.17.21",
|
||||||
|
"ms": "^2.1.3",
|
||||||
|
"nanoid": "^3.3.3",
|
||||||
"request": "^2.88.2",
|
"request": "^2.88.2",
|
||||||
"requests": "^0.3.0",
|
"static-js-yaml": "^1.0.0"
|
||||||
"semver": "^7.3.7",
|
|
||||||
"static-js-yaml": "^1.0.0",
|
|
||||||
"uuid": "^8.3.2"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "^7.18.0",
|
"@babel/core": "^7.18.0",
|
||||||
|
|||||||
14604
backend/pnpm-lock.yaml
generated
14604
backend/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -6,6 +6,7 @@ export const FILES_KEY = 'files';
|
|||||||
export const MODULES_KEY = 'modules';
|
export const MODULES_KEY = 'modules';
|
||||||
export const ARTIFACTS_KEY = 'artifacts';
|
export const ARTIFACTS_KEY = 'artifacts';
|
||||||
export const RULES_KEY = 'rules';
|
export const RULES_KEY = 'rules';
|
||||||
|
export const TOKENS_KEY = 'tokens';
|
||||||
export const GIST_BACKUP_KEY = 'Auto Generated Sub-Store Backup';
|
export const GIST_BACKUP_KEY = 'Auto Generated Sub-Store Backup';
|
||||||
export const GIST_BACKUP_FILE_NAME = 'Sub-Store';
|
export const GIST_BACKUP_FILE_NAME = 'Sub-Store';
|
||||||
export const ARTIFACT_REPOSITORY_KEY = 'Sub-Store Artifacts Repository';
|
export const ARTIFACT_REPOSITORY_KEY = 'Sub-Store Artifacts Repository';
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { Buffer } from 'buffer';
|
||||||
|
import rs from '@/utils/rs';
|
||||||
import YAML from '@/utils/yaml';
|
import YAML from '@/utils/yaml';
|
||||||
import download from '@/utils/download';
|
import download from '@/utils/download';
|
||||||
import {
|
import {
|
||||||
@@ -5,7 +7,9 @@ import {
|
|||||||
isIPv6,
|
isIPv6,
|
||||||
isValidPortNumber,
|
isValidPortNumber,
|
||||||
isNotBlank,
|
isNotBlank,
|
||||||
utf8ArrayToStr,
|
ipAddress,
|
||||||
|
getRandomPort,
|
||||||
|
numberToString,
|
||||||
} from '@/utils';
|
} from '@/utils';
|
||||||
import PROXY_PROCESSORS, { ApplyProcessor } from './processors';
|
import PROXY_PROCESSORS, { ApplyProcessor } from './processors';
|
||||||
import PROXY_PREPROCESSORS from './preprocessors';
|
import PROXY_PREPROCESSORS from './preprocessors';
|
||||||
@@ -15,7 +19,8 @@ import $ from '@/core/app';
|
|||||||
import { FILES_KEY, MODULES_KEY } from '@/constants';
|
import { FILES_KEY, MODULES_KEY } from '@/constants';
|
||||||
import { findByName } from '@/utils/database';
|
import { findByName } from '@/utils/database';
|
||||||
import { produceArtifact } from '@/restful/sync';
|
import { produceArtifact } from '@/restful/sync';
|
||||||
import { getFlag, getISO } from '@/utils/geo';
|
import { getFlag, removeFlag, getISO, MMDB } from '@/utils/geo';
|
||||||
|
import Gist from '@/utils/gist';
|
||||||
|
|
||||||
function preprocess(raw) {
|
function preprocess(raw) {
|
||||||
for (const processor of PROXY_PREPROCESSORS) {
|
for (const processor of PROXY_PREPROCESSORS) {
|
||||||
@@ -73,8 +78,24 @@ function parse(raw) {
|
|||||||
return proxies;
|
return proxies;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function processFn(proxies, operators = [], targetPlatform, source) {
|
async function processFn(
|
||||||
|
proxies,
|
||||||
|
operators = [],
|
||||||
|
targetPlatform,
|
||||||
|
source,
|
||||||
|
$options,
|
||||||
|
) {
|
||||||
for (const item of operators) {
|
for (const item of operators) {
|
||||||
|
if (item.disabled) {
|
||||||
|
$.log(
|
||||||
|
`Skipping disabled operator: "${
|
||||||
|
item.type
|
||||||
|
}" with arguments:\n >>> ${
|
||||||
|
JSON.stringify(item.args, null, 2) || 'None'
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
// process script
|
// process script
|
||||||
let script;
|
let script;
|
||||||
let $arguments = {};
|
let $arguments = {};
|
||||||
@@ -82,7 +103,7 @@ async function processFn(proxies, operators = [], targetPlatform, source) {
|
|||||||
const { mode, content } = item.args;
|
const { mode, content } = item.args;
|
||||||
if (mode === 'link') {
|
if (mode === 'link') {
|
||||||
let noCache;
|
let noCache;
|
||||||
let url = content;
|
let url = content || '';
|
||||||
if (url.endsWith('#noCache')) {
|
if (url.endsWith('#noCache')) {
|
||||||
url = url.replace(/#noCache$/, '');
|
url = url.replace(/#noCache$/, '');
|
||||||
noCache = true;
|
noCache = true;
|
||||||
@@ -172,6 +193,7 @@ async function processFn(proxies, operators = [], targetPlatform, source) {
|
|||||||
targetPlatform,
|
targetPlatform,
|
||||||
$arguments,
|
$arguments,
|
||||||
source,
|
source,
|
||||||
|
$options,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
processor = PROXY_PROCESSORS[item.type](item.args || {});
|
processor = PROXY_PROCESSORS[item.type](item.args || {});
|
||||||
@@ -198,6 +220,8 @@ function produce(proxies, targetPlatform, type, opts = {}) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
proxies = proxies.map((proxy) => {
|
proxies = proxies.map((proxy) => {
|
||||||
|
proxy._resolved = proxy.resolved;
|
||||||
|
|
||||||
if (!isNotBlank(proxy.name)) {
|
if (!isNotBlank(proxy.name)) {
|
||||||
proxy.name = `${proxy.type} ${proxy.server}:${proxy.port}`;
|
proxy.name = `${proxy.type} ${proxy.server}:${proxy.port}`;
|
||||||
}
|
}
|
||||||
@@ -213,26 +237,27 @@ function produce(proxies, targetPlatform, type, opts = {}) {
|
|||||||
delete proxy['tls-fingerprint'];
|
delete proxy['tls-fingerprint'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 处理 端口跳跃
|
||||||
|
if (proxy.ports) {
|
||||||
|
proxy.ports = String(proxy.ports);
|
||||||
|
if (!['ClashMeta'].includes(targetPlatform)) {
|
||||||
|
proxy.ports = proxy.ports.replace(/\//g, ',');
|
||||||
|
}
|
||||||
|
if (!proxy.port) {
|
||||||
|
proxy.port = getRandomPort(proxy.ports);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return proxy;
|
return proxy;
|
||||||
});
|
});
|
||||||
|
|
||||||
$.log(`Producing proxies for target: ${targetPlatform}`);
|
$.log(`Producing proxies for target: ${targetPlatform}`);
|
||||||
if (typeof producer.type === 'undefined' || producer.type === 'SINGLE') {
|
if (typeof producer.type === 'undefined' || producer.type === 'SINGLE') {
|
||||||
let localPort = 10000;
|
|
||||||
let list = proxies
|
let list = proxies
|
||||||
.map((proxy) => {
|
.map((proxy) => {
|
||||||
try {
|
try {
|
||||||
let line = producer.produce(proxy, type, opts);
|
return producer.produce(proxy, type, opts);
|
||||||
if (
|
|
||||||
line.length > 0 &&
|
|
||||||
line.includes('__SubStoreLocalPort__')
|
|
||||||
) {
|
|
||||||
line = line.replace(
|
|
||||||
/__SubStoreLocalPort__/g,
|
|
||||||
localPort++,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return line;
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
$.error(
|
$.error(
|
||||||
`Cannot produce proxy: ${JSON.stringify(
|
`Cannot produce proxy: ${JSON.stringify(
|
||||||
@@ -251,7 +276,7 @@ function produce(proxies, targetPlatform, type, opts = {}) {
|
|||||||
proxies.length > 0 &&
|
proxies.length > 0 &&
|
||||||
proxies.every((p) => p.type === 'wireguard')
|
proxies.every((p) => p.type === 'wireguard')
|
||||||
) {
|
) {
|
||||||
list = `#!name=${proxies[0]?.subName}
|
list = `#!name=${proxies[0]?._subName}
|
||||||
#!desc=${proxies[0]?._desc ?? ''}
|
#!desc=${proxies[0]?._desc ?? ''}
|
||||||
#!category=${proxies[0]?._category ?? ''}
|
#!category=${proxies[0]?._category ?? ''}
|
||||||
${list}`;
|
${list}`;
|
||||||
@@ -266,12 +291,18 @@ export const ProxyUtils = {
|
|||||||
parse,
|
parse,
|
||||||
process: processFn,
|
process: processFn,
|
||||||
produce,
|
produce,
|
||||||
|
ipAddress,
|
||||||
|
getRandomPort,
|
||||||
isIPv4,
|
isIPv4,
|
||||||
isIPv6,
|
isIPv6,
|
||||||
isIP,
|
isIP,
|
||||||
yaml: YAML,
|
yaml: YAML,
|
||||||
getFlag,
|
getFlag,
|
||||||
|
removeFlag,
|
||||||
getISO,
|
getISO,
|
||||||
|
MMDB,
|
||||||
|
Gist,
|
||||||
|
download,
|
||||||
};
|
};
|
||||||
|
|
||||||
function tryParse(parser, line) {
|
function tryParse(parser, line) {
|
||||||
@@ -292,7 +323,26 @@ function safeMatch(parser, line) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatTransportPath(path) {
|
||||||
|
if (typeof path === 'string' || typeof path === 'number') {
|
||||||
|
path = String(path).trim();
|
||||||
|
|
||||||
|
if (path === '') {
|
||||||
|
return '/';
|
||||||
|
} else if (!path.startsWith('/')) {
|
||||||
|
return '/' + path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
function lastParse(proxy) {
|
function lastParse(proxy) {
|
||||||
|
if (typeof proxy.cipher === 'string') {
|
||||||
|
proxy.cipher = proxy.cipher.toLowerCase();
|
||||||
|
}
|
||||||
|
if (typeof proxy.password === 'number') {
|
||||||
|
proxy.password = numberToString(proxy.password);
|
||||||
|
}
|
||||||
if (proxy.interface) {
|
if (proxy.interface) {
|
||||||
proxy['interface-name'] = proxy.interface;
|
proxy['interface-name'] = proxy.interface;
|
||||||
delete proxy.interface;
|
delete proxy.interface;
|
||||||
@@ -320,6 +370,17 @@ function lastParse(proxy) {
|
|||||||
delete proxy['ws-headers'];
|
delete proxy['ws-headers'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const transportPath = proxy[`${proxy.network}-opts`]?.path;
|
||||||
|
|
||||||
|
if (Array.isArray(transportPath)) {
|
||||||
|
proxy[`${proxy.network}-opts`].path = transportPath.map((item) =>
|
||||||
|
formatTransportPath(item),
|
||||||
|
);
|
||||||
|
} else if (transportPath != null) {
|
||||||
|
proxy[`${proxy.network}-opts`].path =
|
||||||
|
formatTransportPath(transportPath);
|
||||||
|
}
|
||||||
|
|
||||||
if (proxy.type === 'trojan') {
|
if (proxy.type === 'trojan') {
|
||||||
if (proxy.network === 'tcp') {
|
if (proxy.network === 'tcp') {
|
||||||
delete proxy.network;
|
delete proxy.network;
|
||||||
@@ -330,7 +391,11 @@ function lastParse(proxy) {
|
|||||||
proxy.network = 'tcp';
|
proxy.network = 'tcp';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (['trojan', 'tuic', 'hysteria', 'hysteria2'].includes(proxy.type)) {
|
if (
|
||||||
|
['trojan', 'tuic', 'hysteria', 'hysteria2', 'juicity'].includes(
|
||||||
|
proxy.type,
|
||||||
|
)
|
||||||
|
) {
|
||||||
proxy.tls = true;
|
proxy.tls = true;
|
||||||
}
|
}
|
||||||
if (proxy.network) {
|
if (proxy.network) {
|
||||||
@@ -356,20 +421,7 @@ function lastParse(proxy) {
|
|||||||
proxy['h2-opts'].path = path[0];
|
proxy['h2-opts'].path = path[0];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (proxy.tls && !proxy.sni) {
|
|
||||||
if (proxy.network) {
|
|
||||||
let transportHost = proxy[`${proxy.network}-opts`]?.headers?.Host;
|
|
||||||
transportHost = Array.isArray(transportHost)
|
|
||||||
? transportHost[0]
|
|
||||||
: transportHost;
|
|
||||||
if (transportHost) {
|
|
||||||
proxy.sni = transportHost;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!proxy.sni && !isIP(proxy.server)) {
|
|
||||||
proxy.sni = proxy.server;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 非 tls, 有 ws/http 传输层, 使用域名的节点, 将设置传输层 Host 防止之后域名解析后丢失域名(不覆盖现有的 Host)
|
// 非 tls, 有 ws/http 传输层, 使用域名的节点, 将设置传输层 Host 防止之后域名解析后丢失域名(不覆盖现有的 Host)
|
||||||
if (
|
if (
|
||||||
!proxy.tls &&
|
!proxy.tls &&
|
||||||
@@ -396,10 +448,51 @@ function lastParse(proxy) {
|
|||||||
proxy[`${proxy.network}-opts`].path = [transportPath];
|
proxy[`${proxy.network}-opts`].path = [transportPath];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (['hysteria', 'hysteria2'].includes(proxy.type) && !proxy.ports) {
|
if (proxy.tls && !proxy.sni) {
|
||||||
|
if (!isIP(proxy.server)) {
|
||||||
|
proxy.sni = proxy.server;
|
||||||
|
}
|
||||||
|
if (!proxy.sni && proxy.network) {
|
||||||
|
let transportHost = proxy[`${proxy.network}-opts`]?.headers?.Host;
|
||||||
|
transportHost = Array.isArray(transportHost)
|
||||||
|
? transportHost[0]
|
||||||
|
: transportHost;
|
||||||
|
if (transportHost) {
|
||||||
|
proxy.sni = transportHost;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// if (['hysteria', 'hysteria2', 'tuic'].includes(proxy.type)) {
|
||||||
|
if (proxy.ports) {
|
||||||
|
proxy.ports = String(proxy.ports).replace(/\//g, ',');
|
||||||
|
} else {
|
||||||
delete proxy.ports;
|
delete proxy.ports;
|
||||||
}
|
}
|
||||||
|
// }
|
||||||
|
if (
|
||||||
|
['hysteria2'].includes(proxy.type) &&
|
||||||
|
proxy.obfs &&
|
||||||
|
!['salamander'].includes(proxy.obfs) &&
|
||||||
|
!proxy['obfs-password']
|
||||||
|
) {
|
||||||
|
proxy['obfs-password'] = proxy.obfs;
|
||||||
|
proxy.obfs = 'salamander';
|
||||||
|
}
|
||||||
if (['vless'].includes(proxy.type)) {
|
if (['vless'].includes(proxy.type)) {
|
||||||
|
// 删除 reality-opts: {}
|
||||||
|
if (
|
||||||
|
proxy['reality-opts'] &&
|
||||||
|
Object.keys(proxy['reality-opts']).length === 0
|
||||||
|
) {
|
||||||
|
delete proxy['reality-opts'];
|
||||||
|
}
|
||||||
|
// 删除 grpc-opts: {}
|
||||||
|
if (
|
||||||
|
proxy['grpc-opts'] &&
|
||||||
|
Object.keys(proxy['grpc-opts']).length === 0
|
||||||
|
) {
|
||||||
|
delete proxy['grpc-opts'];
|
||||||
|
}
|
||||||
// 非 reality, 空 flow 没有意义
|
// 非 reality, 空 flow 没有意义
|
||||||
if (!proxy['reality-opts'] && !proxy.flow) {
|
if (!proxy['reality-opts'] && !proxy.flow) {
|
||||||
delete proxy.flow;
|
delete proxy.flow;
|
||||||
@@ -414,6 +507,7 @@ function lastParse(proxy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof proxy.name !== 'string') {
|
if (typeof proxy.name !== 'string') {
|
||||||
if (/^\d+$/.test(proxy.name)) {
|
if (/^\d+$/.test(proxy.name)) {
|
||||||
proxy.name = `${proxy.name}`;
|
proxy.name = `${proxy.name}`;
|
||||||
@@ -422,7 +516,7 @@ function lastParse(proxy) {
|
|||||||
if (proxy.name?.data) {
|
if (proxy.name?.data) {
|
||||||
proxy.name = Buffer.from(proxy.name.data).toString('utf8');
|
proxy.name = Buffer.from(proxy.name.data).toString('utf8');
|
||||||
} else {
|
} else {
|
||||||
proxy.name = utf8ArrayToStr(proxy.name);
|
proxy.name = Buffer.from(proxy.name).toString('utf8');
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
$.error(`proxy.name decode failed\nReason: ${e}`);
|
$.error(`proxy.name decode failed\nReason: ${e}`);
|
||||||
@@ -430,9 +524,46 @@ function lastParse(proxy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (['ws', 'http', 'h2'].includes(proxy.network)) {
|
||||||
|
if (
|
||||||
|
['ws', 'h2'].includes(proxy.network) &&
|
||||||
|
!proxy[`${proxy.network}-opts`]?.path
|
||||||
|
) {
|
||||||
|
proxy[`${proxy.network}-opts`] =
|
||||||
|
proxy[`${proxy.network}-opts`] || {};
|
||||||
|
proxy[`${proxy.network}-opts`].path = '/';
|
||||||
|
} else if (
|
||||||
|
proxy.network === 'http' &&
|
||||||
|
(!Array.isArray(proxy[`${proxy.network}-opts`]?.path) ||
|
||||||
|
proxy[`${proxy.network}-opts`]?.path.every((i) => !i))
|
||||||
|
) {
|
||||||
|
proxy[`${proxy.network}-opts`] =
|
||||||
|
proxy[`${proxy.network}-opts`] || {};
|
||||||
|
proxy[`${proxy.network}-opts`].path = ['/'];
|
||||||
|
}
|
||||||
|
}
|
||||||
if (['', 'off'].includes(proxy.sni)) {
|
if (['', 'off'].includes(proxy.sni)) {
|
||||||
proxy['disable-sni'] = true;
|
proxy['disable-sni'] = true;
|
||||||
}
|
}
|
||||||
|
let caStr = proxy['ca_str'];
|
||||||
|
if (proxy['ca-str']) {
|
||||||
|
caStr = proxy['ca-str'];
|
||||||
|
} else if (caStr) {
|
||||||
|
delete proxy['ca_str'];
|
||||||
|
proxy['ca-str'] = caStr;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if ($.env.isNode && !caStr && proxy['_ca']) {
|
||||||
|
caStr = $.node.fs.readFileSync(proxy['_ca'], {
|
||||||
|
encoding: 'utf8',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
$.error(`Read ca file failed\nReason: ${e}`);
|
||||||
|
}
|
||||||
|
if (!proxy['tls-fingerprint'] && caStr) {
|
||||||
|
proxy['tls-fingerprint'] = rs.generateFingerprint(caStr);
|
||||||
|
}
|
||||||
return proxy;
|
return proxy;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
isPresent,
|
isPresent,
|
||||||
isNotBlank,
|
isNotBlank,
|
||||||
getIfPresent,
|
getIfPresent,
|
||||||
|
getRandomPort,
|
||||||
} from '@/utils';
|
} from '@/utils';
|
||||||
import getSurgeParser from './peggy/surge';
|
import getSurgeParser from './peggy/surge';
|
||||||
import getLoonParser from './peggy/loon';
|
import getLoonParser from './peggy/loon';
|
||||||
@@ -13,9 +14,59 @@ import getTrojanURIParser from './peggy/trojan-uri';
|
|||||||
|
|
||||||
import { Base64 } from 'js-base64';
|
import { Base64 } from 'js-base64';
|
||||||
|
|
||||||
|
function surge_port_hopping(raw) {
|
||||||
|
const [parts, port_hopping] =
|
||||||
|
raw.match(
|
||||||
|
/,\s*?port-hopping\s*?=\s*?["']?\s*?((\d+(-\d+)?)([,;]\d+(-\d+)?)*)\s*?["']?\s*?/,
|
||||||
|
) || [];
|
||||||
|
return {
|
||||||
|
port_hopping: port_hopping
|
||||||
|
? port_hopping.replace(/;/g, ',')
|
||||||
|
: undefined,
|
||||||
|
line: parts ? raw.replace(parts, '') : raw,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function URI_PROXY() {
|
||||||
|
// socks5+tls
|
||||||
|
// socks5
|
||||||
|
// http, https(可以这么写)
|
||||||
|
const name = 'URI PROXY Parser';
|
||||||
|
const test = (line) => {
|
||||||
|
return /^(socks5\+tls|socks5|http|https):\/\//.test(line);
|
||||||
|
};
|
||||||
|
const parse = (line) => {
|
||||||
|
// parse url
|
||||||
|
// eslint-disable-next-line no-unused-vars
|
||||||
|
let [__, type, tls, username, password, server, port, query, name] =
|
||||||
|
line.match(
|
||||||
|
/^(socks5|http|http)(\+tls|s)?:\/\/(?:(.*?):(.*?)@)?(.*?):(\d+?)(\?.*?)?(?:#(.*?))?$/,
|
||||||
|
);
|
||||||
|
|
||||||
|
const proxy = {
|
||||||
|
name:
|
||||||
|
name != null
|
||||||
|
? decodeURIComponent(name)
|
||||||
|
: `${type} ${server}:${port}`,
|
||||||
|
type,
|
||||||
|
tls: tls ? true : false,
|
||||||
|
server,
|
||||||
|
port,
|
||||||
|
username:
|
||||||
|
username != null ? decodeURIComponent(username) : undefined,
|
||||||
|
password:
|
||||||
|
password != null ? decodeURIComponent(password) : undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
return proxy;
|
||||||
|
};
|
||||||
|
return { name, test, parse };
|
||||||
|
}
|
||||||
|
|
||||||
// Parse SS URI format (only supports new SIP002, legacy format is depreciated).
|
// Parse SS URI format (only supports new SIP002, legacy format is depreciated).
|
||||||
// reference: https://github.com/shadowsocks/shadowsocks-org/wiki/SIP002-URI-Scheme
|
// reference: https://github.com/shadowsocks/shadowsocks-org/wiki/SIP002-URI-Scheme
|
||||||
function URI_SS() {
|
function URI_SS() {
|
||||||
|
// TODO: 暂不支持 httpupgrade
|
||||||
const name = 'URI SS Parser';
|
const name = 'URI SS Parser';
|
||||||
const test = (line) => {
|
const test = (line) => {
|
||||||
return /^ss:\/\//.test(line);
|
return /^ss:\/\//.test(line);
|
||||||
@@ -31,7 +82,15 @@ function URI_SS() {
|
|||||||
content = content.split('#')[0]; // strip proxy name
|
content = content.split('#')[0]; // strip proxy name
|
||||||
// handle IPV4 and IPV6
|
// handle IPV4 and IPV6
|
||||||
let serverAndPortArray = content.match(/@([^/]*)(\/|$)/);
|
let serverAndPortArray = content.match(/@([^/]*)(\/|$)/);
|
||||||
let userInfoStr = Base64.decode(content.split('@')[0]);
|
|
||||||
|
let rawUserInfoStr = decodeURIComponent(content.split('@')[0]); // 其实应该分隔之后, 用户名和密码再 decodeURIComponent. 但是问题不大
|
||||||
|
let userInfoStr;
|
||||||
|
if (rawUserInfoStr?.startsWith('2022-blake3-')) {
|
||||||
|
userInfoStr = rawUserInfoStr;
|
||||||
|
} else {
|
||||||
|
userInfoStr = Base64.decode(rawUserInfoStr);
|
||||||
|
}
|
||||||
|
|
||||||
let query = '';
|
let query = '';
|
||||||
if (!serverAndPortArray) {
|
if (!serverAndPortArray) {
|
||||||
if (content.includes('?')) {
|
if (content.includes('?')) {
|
||||||
@@ -56,16 +115,21 @@ function URI_SS() {
|
|||||||
userInfoStr = content.split('@')[0];
|
userInfoStr = content.split('@')[0];
|
||||||
serverAndPortArray = content.match(/@([^/]*)(\/|$)/);
|
serverAndPortArray = content.match(/@([^/]*)(\/|$)/);
|
||||||
}
|
}
|
||||||
|
|
||||||
const serverAndPort = serverAndPortArray[1];
|
const serverAndPort = serverAndPortArray[1];
|
||||||
const portIdx = serverAndPort.lastIndexOf(':');
|
const portIdx = serverAndPort.lastIndexOf(':');
|
||||||
proxy.server = serverAndPort.substring(0, portIdx);
|
proxy.server = serverAndPort.substring(0, portIdx);
|
||||||
proxy.port = `${serverAndPort.substring(portIdx + 1)}`.match(
|
proxy.port = `${serverAndPort.substring(portIdx + 1)}`.match(
|
||||||
/\d+/,
|
/\d+/,
|
||||||
)?.[0];
|
)?.[0];
|
||||||
|
let userInfo = userInfoStr.match(/(^.*?):(.*$)/);
|
||||||
const userInfo = userInfoStr.match(/(^.*?):(.*$)/);
|
proxy.cipher = userInfo?.[1];
|
||||||
proxy.cipher = userInfo[1];
|
proxy.password = userInfo?.[2];
|
||||||
proxy.password = userInfo[2];
|
// if (!proxy.cipher || !proxy.password) {
|
||||||
|
// userInfo = rawUserInfoStr.match(/(^.*?):(.*$)/);
|
||||||
|
// proxy.cipher = userInfo?.[1];
|
||||||
|
// proxy.password = userInfo?.[2];
|
||||||
|
// }
|
||||||
|
|
||||||
// handle obfs
|
// handle obfs
|
||||||
const idx = content.indexOf('?plugin=');
|
const idx = content.indexOf('?plugin=');
|
||||||
@@ -157,7 +221,7 @@ function URI_SSR() {
|
|||||||
for (const item of line) {
|
for (const item of line) {
|
||||||
let [key, val] = item.split('=');
|
let [key, val] = item.split('=');
|
||||||
val = val.trim();
|
val = val.trim();
|
||||||
if (val.length > 0) {
|
if (val.length > 0 && val !== '(null)') {
|
||||||
other_params[key] = val;
|
other_params[key] = val;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -295,21 +359,40 @@ function URI_VMess() {
|
|||||||
? !params.verify_cert
|
? !params.verify_cert
|
||||||
: undefined,
|
: undefined,
|
||||||
};
|
};
|
||||||
|
if (!proxy['skip-cert-verify'] && isPresent(params.allowInsecure)) {
|
||||||
|
proxy['skip-cert-verify'] = /(TRUE)|1/i.test(
|
||||||
|
params.allowInsecure,
|
||||||
|
);
|
||||||
|
}
|
||||||
// https://github.com/2dust/v2rayN/wiki/%E5%88%86%E4%BA%AB%E9%93%BE%E6%8E%A5%E6%A0%BC%E5%BC%8F%E8%AF%B4%E6%98%8E(ver-2)
|
// https://github.com/2dust/v2rayN/wiki/%E5%88%86%E4%BA%AB%E9%93%BE%E6%8E%A5%E6%A0%BC%E5%BC%8F%E8%AF%B4%E6%98%8E(ver-2)
|
||||||
if (proxy.tls && proxy.sni) {
|
if (proxy.tls && params.sni && params.sni !== '') {
|
||||||
proxy.sni = params.sni;
|
proxy.sni = params.sni;
|
||||||
}
|
}
|
||||||
|
let httpupgrade = false;
|
||||||
// handle obfs
|
// handle obfs
|
||||||
if (params.net === 'ws' || params.obfs === 'websocket') {
|
if (params.net === 'ws' || params.obfs === 'websocket') {
|
||||||
proxy.network = 'ws';
|
proxy.network = 'ws';
|
||||||
} else if (
|
} else if (
|
||||||
['tcp', 'http'].includes(params.net) ||
|
['http'].includes(params.net) ||
|
||||||
params.obfs === 'http'
|
['http'].includes(params.obfs) ||
|
||||||
|
['http'].includes(params.type)
|
||||||
) {
|
) {
|
||||||
proxy.network = 'http';
|
proxy.network = 'http';
|
||||||
} else if (['grpc'].includes(params.net)) {
|
} else if (['grpc'].includes(params.net)) {
|
||||||
proxy.network = 'grpc';
|
proxy.network = 'grpc';
|
||||||
|
} else if (
|
||||||
|
params.net === 'httpupgrade' ||
|
||||||
|
proxy.network === 'httpupgrade'
|
||||||
|
) {
|
||||||
|
proxy.network = 'ws';
|
||||||
|
httpupgrade = true;
|
||||||
|
} else if (params.net === 'h2' || proxy.network === 'h2') {
|
||||||
|
proxy.network = 'h2';
|
||||||
}
|
}
|
||||||
|
// 暂不支持 tcp + host + path
|
||||||
|
// else if (params.net === 'tcp' || proxy.network === 'tcp') {
|
||||||
|
// proxy.network = 'tcp';
|
||||||
|
// }
|
||||||
if (proxy.network) {
|
if (proxy.network) {
|
||||||
let transportHost = params.host ?? params.obfsParam;
|
let transportHost = params.host ?? params.obfsParam;
|
||||||
try {
|
try {
|
||||||
@@ -324,6 +407,10 @@ function URI_VMess() {
|
|||||||
|
|
||||||
if (proxy.network === 'http') {
|
if (proxy.network === 'http') {
|
||||||
if (transportHost) {
|
if (transportHost) {
|
||||||
|
// 1)http(tcp)->host中间逗号(,)隔开
|
||||||
|
transportHost = transportHost
|
||||||
|
.split(',')
|
||||||
|
.map((i) => i.trim());
|
||||||
transportHost = Array.isArray(transportHost)
|
transportHost = Array.isArray(transportHost)
|
||||||
? transportHost[0]
|
? transportHost[0]
|
||||||
: transportHost;
|
: transportHost;
|
||||||
@@ -332,29 +419,32 @@ function URI_VMess() {
|
|||||||
transportPath = Array.isArray(transportPath)
|
transportPath = Array.isArray(transportPath)
|
||||||
? transportPath[0]
|
? transportPath[0]
|
||||||
: transportPath;
|
: transportPath;
|
||||||
|
} else {
|
||||||
|
transportPath = '/';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 传输层应该有配置, 暂时不考虑兼容不给配置的节点
|
||||||
if (transportPath || transportHost) {
|
if (transportPath || transportHost) {
|
||||||
if (['grpc'].includes(proxy.network)) {
|
if (['grpc'].includes(proxy.network)) {
|
||||||
proxy[`${proxy.network}-opts`] = {
|
proxy[`${proxy.network}-opts`] = {
|
||||||
'grpc-service-name': getIfNotBlank(transportPath),
|
'grpc-service-name': getIfNotBlank(transportPath),
|
||||||
'_grpc-type': getIfNotBlank(params.type),
|
'_grpc-type': getIfNotBlank(params.type),
|
||||||
|
'_grpc-authority': getIfNotBlank(params.authority),
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
proxy[`${proxy.network}-opts`] = {
|
const opts = {
|
||||||
path: getIfNotBlank(transportPath),
|
path: getIfNotBlank(transportPath),
|
||||||
headers: { Host: getIfNotBlank(transportHost) },
|
headers: { Host: getIfNotBlank(transportHost) },
|
||||||
};
|
};
|
||||||
|
if (httpupgrade) {
|
||||||
|
opts['v2ray-http-upgrade'] = true;
|
||||||
|
opts['v2ray-http-upgrade-fast-open'] = true;
|
||||||
|
}
|
||||||
|
proxy[`${proxy.network}-opts`] = opts;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
delete proxy.network;
|
delete proxy.network;
|
||||||
}
|
}
|
||||||
|
|
||||||
// https://github.com/MetaCubeX/Clash.Meta/blob/Alpha/docs/config.yaml#L413
|
|
||||||
// sni 优先级应高于 host
|
|
||||||
if (proxy.tls && !proxy.sni && transportHost) {
|
|
||||||
proxy.sni = transportHost;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return proxy;
|
return proxy;
|
||||||
}
|
}
|
||||||
@@ -444,10 +534,13 @@ function URI_VLESS() {
|
|||||||
proxy[`${params.security}-opts`] = opts;
|
proxy[`${params.security}-opts`] = opts;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let httpupgrade = false;
|
||||||
proxy.network = params.type;
|
proxy.network = params.type;
|
||||||
if (proxy.network === 'tcp' && params.headerType === 'http') {
|
if (proxy.network === 'tcp' && params.headerType === 'http') {
|
||||||
proxy.network = 'http';
|
proxy.network = 'http';
|
||||||
|
} else if (proxy.network === 'httpupgrade') {
|
||||||
|
proxy.network = 'ws';
|
||||||
|
httpupgrade = true;
|
||||||
}
|
}
|
||||||
if (!proxy.network && isShadowrocket && params.obfs) {
|
if (!proxy.network && isShadowrocket && params.obfs) {
|
||||||
proxy.network = params.obfs;
|
proxy.network = params.obfs;
|
||||||
@@ -472,6 +565,9 @@ function URI_VLESS() {
|
|||||||
}
|
}
|
||||||
if (params.serviceName) {
|
if (params.serviceName) {
|
||||||
opts[`${proxy.network}-service-name`] = params.serviceName;
|
opts[`${proxy.network}-service-name`] = params.serviceName;
|
||||||
|
if (['grpc'].includes(proxy.network) && params.authority) {
|
||||||
|
opts['_grpc-authority'] = params.authority;
|
||||||
|
}
|
||||||
} else if (isShadowrocket && params.path) {
|
} else if (isShadowrocket && params.path) {
|
||||||
if (!['ws', 'http', 'h2'].includes(proxy.network)) {
|
if (!['ws', 'http', 'h2'].includes(proxy.network)) {
|
||||||
opts[`${proxy.network}-service-name`] = params.path;
|
opts[`${proxy.network}-service-name`] = params.path;
|
||||||
@@ -485,17 +581,20 @@ function URI_VLESS() {
|
|||||||
if (['grpc'].includes(proxy.network)) {
|
if (['grpc'].includes(proxy.network)) {
|
||||||
opts['_grpc-type'] = params.mode || 'gun';
|
opts['_grpc-type'] = params.mode || 'gun';
|
||||||
}
|
}
|
||||||
|
if (httpupgrade) {
|
||||||
|
opts['v2ray-http-upgrade'] = true;
|
||||||
|
opts['v2ray-http-upgrade-fast-open'] = true;
|
||||||
|
}
|
||||||
if (Object.keys(opts).length > 0) {
|
if (Object.keys(opts).length > 0) {
|
||||||
proxy[`${proxy.network}-opts`] = opts;
|
proxy[`${proxy.network}-opts`] = opts;
|
||||||
}
|
}
|
||||||
}
|
if (proxy.network === 'kcp') {
|
||||||
|
// mKCP 种子。省略时不使用种子,但不可以为空字符串。建议 mKCP 用户使用 seed。
|
||||||
if (proxy.tls && !proxy.sni) {
|
if (params.seed) {
|
||||||
if (proxy.network === 'ws') {
|
proxy.seed = params.seed;
|
||||||
proxy.sni = proxy['ws-opts']?.headers?.Host;
|
}
|
||||||
} else if (proxy.network === 'http') {
|
// mKCP 的伪装头部类型。当前可选值有 none / srtp / utp / wechat-video / dtls / wireguard。省略时默认值为 none,即不使用伪装头部,但不可以为空字符串。
|
||||||
let httpHost = proxy['http-opts']?.headers?.Host;
|
proxy.headerType = params.headerType || 'none';
|
||||||
proxy.sni = Array.isArray(httpHost) ? httpHost[0] : httpHost;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -510,13 +609,42 @@ function URI_Hysteria2() {
|
|||||||
};
|
};
|
||||||
const parse = (line) => {
|
const parse = (line) => {
|
||||||
line = line.split(/(hysteria2|hy2):\/\//)[2];
|
line = line.split(/(hysteria2|hy2):\/\//)[2];
|
||||||
// eslint-disable-next-line no-unused-vars
|
// 端口跳跃有两种写法:
|
||||||
let [__, password, server, ___, port, ____, addons = '', name] =
|
// 1. 服务器的地址和可选端口。如果省略端口,则默认为 443。
|
||||||
/^(.*?)@(.*?)(:(\d+))?\/?(\?(.*?))?(?:#(.*?))?$/.exec(line);
|
// 端口部分支持 端口跳跃 的「多端口地址格式」。
|
||||||
port = parseInt(`${port}`, 10);
|
// https://hysteria.network/zh/docs/advanced/Port-Hopping
|
||||||
if (isNaN(port)) {
|
// 2. 参数 mport
|
||||||
|
let ports;
|
||||||
|
/* eslint-disable no-unused-vars */
|
||||||
|
let [
|
||||||
|
__,
|
||||||
|
password,
|
||||||
|
server,
|
||||||
|
___,
|
||||||
|
port,
|
||||||
|
____,
|
||||||
|
_____,
|
||||||
|
______,
|
||||||
|
_______,
|
||||||
|
________,
|
||||||
|
addons = '',
|
||||||
|
name,
|
||||||
|
] = /^(.*?)@(.*?)(:((\d+(-\d+)?)([,;]\d+(-\d+)?)*))?\/?(\?(.*?))?(?:#(.*?))?$/.exec(
|
||||||
|
line,
|
||||||
|
);
|
||||||
|
/* eslint-enable no-unused-vars */
|
||||||
|
if (/^\d+$/.test(port)) {
|
||||||
|
port = parseInt(`${port}`, 10);
|
||||||
|
if (isNaN(port)) {
|
||||||
|
port = 443;
|
||||||
|
}
|
||||||
|
} else if (port) {
|
||||||
|
ports = port;
|
||||||
|
port = getRandomPort(ports);
|
||||||
|
} else {
|
||||||
port = 443;
|
port = 443;
|
||||||
}
|
}
|
||||||
|
|
||||||
password = decodeURIComponent(password);
|
password = decodeURIComponent(password);
|
||||||
if (name != null) {
|
if (name != null) {
|
||||||
name = decodeURIComponent(name);
|
name = decodeURIComponent(name);
|
||||||
@@ -528,6 +656,7 @@ function URI_Hysteria2() {
|
|||||||
name,
|
name,
|
||||||
server,
|
server,
|
||||||
port,
|
port,
|
||||||
|
ports,
|
||||||
password,
|
password,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -766,6 +895,11 @@ function URI_Trojan() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const parse = (line) => {
|
const parse = (line) => {
|
||||||
|
const matched = /^(trojan:\/\/.*?@.*?)(:(\d+))?\/?(\?.*?)?$/.exec(line);
|
||||||
|
const port = matched?.[2];
|
||||||
|
if (!port) {
|
||||||
|
line = line.replace(matched[1], `${matched[1]}:443`);
|
||||||
|
}
|
||||||
let [newLine, name] = line.split(/#(.+)/, 2);
|
let [newLine, name] = line.split(/#(.+)/, 2);
|
||||||
const parser = getTrojanURIParser();
|
const parser = getTrojanURIParser();
|
||||||
const proxy = parser.parse(newLine);
|
const proxy = parser.parse(newLine);
|
||||||
@@ -808,6 +942,7 @@ function Clash_All() {
|
|||||||
'hysteria2',
|
'hysteria2',
|
||||||
'wireguard',
|
'wireguard',
|
||||||
'ssh',
|
'ssh',
|
||||||
|
'direct',
|
||||||
].includes(proxy.type)
|
].includes(proxy.type)
|
||||||
) {
|
) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -819,18 +954,10 @@ function Clash_All() {
|
|||||||
if (['vmess', 'vless'].includes(proxy.type)) {
|
if (['vmess', 'vless'].includes(proxy.type)) {
|
||||||
proxy.sni = proxy.servername;
|
proxy.sni = proxy.servername;
|
||||||
delete proxy.servername;
|
delete proxy.servername;
|
||||||
if (proxy.tls && !proxy.sni) {
|
|
||||||
if (proxy.network === 'ws') {
|
|
||||||
proxy.sni = proxy['ws-opts']?.headers?.Host;
|
|
||||||
} else if (proxy.network === 'http') {
|
|
||||||
let httpHost = proxy['http-opts']?.headers?.Host;
|
|
||||||
proxy.sni = Array.isArray(httpHost)
|
|
||||||
? httpHost[0]
|
|
||||||
: httpHost;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
if (proxy['server-cert-fingerprint']) {
|
||||||
|
proxy['tls-fingerprint'] = proxy['server-cert-fingerprint'];
|
||||||
|
}
|
||||||
if (proxy.fingerprint) {
|
if (proxy.fingerprint) {
|
||||||
proxy['tls-fingerprint'] = proxy.fingerprint;
|
proxy['tls-fingerprint'] = proxy.fingerprint;
|
||||||
}
|
}
|
||||||
@@ -1114,6 +1241,14 @@ function Loon_WireGuard() {
|
|||||||
return { name, test, parse };
|
return { name, test, parse };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Surge_Direct() {
|
||||||
|
const name = 'Surge Direct Parser';
|
||||||
|
const test = (line) => {
|
||||||
|
return /^.*=\s*direct/.test(line.split(',')[0]);
|
||||||
|
};
|
||||||
|
const parse = (line) => getSurgeParser().parse(line);
|
||||||
|
return { name, test, parse };
|
||||||
|
}
|
||||||
function Surge_SSH() {
|
function Surge_SSH() {
|
||||||
const name = 'Surge SSH Parser';
|
const name = 'Surge SSH Parser';
|
||||||
const test = (line) => {
|
const test = (line) => {
|
||||||
@@ -1257,7 +1392,12 @@ function Surge_Tuic() {
|
|||||||
const test = (line) => {
|
const test = (line) => {
|
||||||
return /^.*=\s*tuic(-v5)?/.test(line.split(',')[0]);
|
return /^.*=\s*tuic(-v5)?/.test(line.split(',')[0]);
|
||||||
};
|
};
|
||||||
const parse = (line) => getSurgeParser().parse(line);
|
const parse = (raw) => {
|
||||||
|
const { port_hopping, line } = surge_port_hopping(raw);
|
||||||
|
const proxy = getSurgeParser().parse(line);
|
||||||
|
proxy['ports'] = port_hopping;
|
||||||
|
return proxy;
|
||||||
|
};
|
||||||
return { name, test, parse };
|
return { name, test, parse };
|
||||||
}
|
}
|
||||||
function Surge_WireGuard() {
|
function Surge_WireGuard() {
|
||||||
@@ -1274,7 +1414,12 @@ function Surge_Hysteria2() {
|
|||||||
const test = (line) => {
|
const test = (line) => {
|
||||||
return /^.*=\s*hysteria2/.test(line.split(',')[0]);
|
return /^.*=\s*hysteria2/.test(line.split(',')[0]);
|
||||||
};
|
};
|
||||||
const parse = (line) => getSurgeParser().parse(line);
|
const parse = (raw) => {
|
||||||
|
const { port_hopping, line } = surge_port_hopping(raw);
|
||||||
|
const proxy = getSurgeParser().parse(line);
|
||||||
|
proxy['ports'] = port_hopping;
|
||||||
|
return proxy;
|
||||||
|
};
|
||||||
return { name, test, parse };
|
return { name, test, parse };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1283,6 +1428,7 @@ function isIP(ip) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default [
|
export default [
|
||||||
|
URI_PROXY(),
|
||||||
URI_SS(),
|
URI_SS(),
|
||||||
URI_SSR(),
|
URI_SSR(),
|
||||||
URI_VMess(),
|
URI_VMess(),
|
||||||
@@ -1293,6 +1439,7 @@ export default [
|
|||||||
URI_Hysteria2(),
|
URI_Hysteria2(),
|
||||||
URI_Trojan(),
|
URI_Trojan(),
|
||||||
Clash_All(),
|
Clash_All(),
|
||||||
|
Surge_Direct(),
|
||||||
Surge_SSH(),
|
Surge_SSH(),
|
||||||
Surge_SS(),
|
Surge_SS(),
|
||||||
Surge_VMess(),
|
Surge_VMess(),
|
||||||
|
|||||||
@@ -54,31 +54,31 @@ shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs
|
|||||||
$set(proxy, "plugin-opts.path", obfs.path);
|
$set(proxy, "plugin-opts.path", obfs.path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/vmess_alterId/fast_open/udp_relay/others)* {
|
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/vmess_alterId/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "vmess";
|
proxy.type = "vmess";
|
||||||
proxy.cipher = proxy.cipher || "none";
|
proxy.cipher = proxy.cipher || "none";
|
||||||
proxy.alterId = proxy.alterId || 0;
|
proxy.alterId = proxy.alterId || 0;
|
||||||
handleTransport();
|
handleTransport();
|
||||||
}
|
}
|
||||||
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/fast_open/udp_relay/others)* {
|
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "vless";
|
proxy.type = "vless";
|
||||||
handleTransport();
|
handleTransport();
|
||||||
}
|
}
|
||||||
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/fast_open/udp_relay/others)* {
|
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "trojan";
|
proxy.type = "trojan";
|
||||||
handleTransport();
|
handleTransport();
|
||||||
}
|
}
|
||||||
hysteria2 = tag equals "hysteria2"i address password (tls_host/tls_verification/udp_relay/fast_open/download_bandwidth/ecn/others)* {
|
hysteria2 = tag equals "hysteria2"i address password (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/udp_relay/fast_open/download_bandwidth/salamander_password/ecn/others)* {
|
||||||
proxy.type = "hysteria2";
|
proxy.type = "hysteria2";
|
||||||
}
|
}
|
||||||
https = tag equals "https"i address (username password)? (tls_host/tls_verification/fast_open/udp_relay/others)* {
|
https = tag equals "https"i address (username password)? (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "http";
|
proxy.type = "http";
|
||||||
proxy.tls = true;
|
proxy.tls = true;
|
||||||
}
|
}
|
||||||
http = tag equals "http"i address (username password)? (fast_open/udp_relay/others)* {
|
http = tag equals "http"i address (username password)? (fast_open/udp_relay/others)* {
|
||||||
proxy.type = "http";
|
proxy.type = "http";
|
||||||
}
|
}
|
||||||
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_host/tls_verification/fast_open/udp_relay/others)* {
|
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "socks5";
|
proxy.type = "socks5";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,7 +120,7 @@ port = digits:[0-9]+ {
|
|||||||
method = comma cipher:cipher {
|
method = comma cipher:cipher {
|
||||||
proxy.cipher = cipher;
|
proxy.cipher = cipher;
|
||||||
}
|
}
|
||||||
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"auto"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"none"/"rc4-md5"/"rc4"/"salsa20"/"xchacha20-ietf-poly1305");
|
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"auto"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"none"/"rc4-md5"/"rc4"/"salsa20"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
|
||||||
|
|
||||||
username = & {
|
username = & {
|
||||||
let j = peg$currPos;
|
let j = peg$currPos;
|
||||||
@@ -172,12 +172,15 @@ vmess_alterId = comma "alterId" equals alterId:$[0-9]+ { proxy.alterId = parseIn
|
|||||||
over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
|
over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
|
||||||
tls_host = comma sni:("tls-name"/"sni") equals host:domain { proxy.sni = host; }
|
tls_host = comma sni:("tls-name"/"sni") equals host:domain { proxy.sni = host; }
|
||||||
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
|
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
|
||||||
|
tls_cert_sha256 = comma "tls-cert-sha256" equals match:[^,]+ { proxy["tls-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||||
|
tls_pubkey_sha256 = comma "tls-pubkey-sha256" equals match:[^,]+ { proxy["tls-pubkey-sha256"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||||
|
|
||||||
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
||||||
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
|
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
|
||||||
|
|
||||||
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
||||||
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
|
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
|
||||||
|
salamander_password = comma "salamander-password" equals match:[^,]+ { proxy['obfs-password'] = match.join(""); proxy.obfs = 'salamander'; }
|
||||||
|
|
||||||
tag = match:[^=,]* { proxy.name = match.join("").trim(); }
|
tag = match:[^=,]* { proxy.name = match.join("").trim(); }
|
||||||
comma = _ "," _
|
comma = _ "," _
|
||||||
|
|||||||
@@ -52,31 +52,31 @@ shadowsocks = tag equals "shadowsocks"i address method password (obfs_typev obfs
|
|||||||
$set(proxy, "plugin-opts.path", obfs.path);
|
$set(proxy, "plugin-opts.path", obfs.path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/vmess_alterId/fast_open/udp_relay/others)* {
|
vmess = tag equals "vmess"i address method uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/vmess_alterId/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "vmess";
|
proxy.type = "vmess";
|
||||||
proxy.cipher = proxy.cipher || "none";
|
proxy.cipher = proxy.cipher || "none";
|
||||||
proxy.alterId = proxy.alterId || 0;
|
proxy.alterId = proxy.alterId || 0;
|
||||||
handleTransport();
|
handleTransport();
|
||||||
}
|
}
|
||||||
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/fast_open/udp_relay/others)* {
|
vless = tag equals "vless"i address uuid (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "vless";
|
proxy.type = "vless";
|
||||||
handleTransport();
|
handleTransport();
|
||||||
}
|
}
|
||||||
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/fast_open/udp_relay/others)* {
|
trojan = tag equals "trojan"i address password (transport/transport_host/transport_path/over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "trojan";
|
proxy.type = "trojan";
|
||||||
handleTransport();
|
handleTransport();
|
||||||
}
|
}
|
||||||
hysteria2 = tag equals "hysteria2"i address password (tls_host/tls_verification/udp_relay/fast_open/download_bandwidth/ecn/others)* {
|
hysteria2 = tag equals "hysteria2"i address password (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/udp_relay/fast_open/download_bandwidth/salamander_password/ecn/others)* {
|
||||||
proxy.type = "hysteria2";
|
proxy.type = "hysteria2";
|
||||||
}
|
}
|
||||||
https = tag equals "https"i address (username password)? (tls_host/tls_verification/fast_open/udp_relay/others)* {
|
https = tag equals "https"i address (username password)? (tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "http";
|
proxy.type = "http";
|
||||||
proxy.tls = true;
|
proxy.tls = true;
|
||||||
}
|
}
|
||||||
http = tag equals "http"i address (username password)? (fast_open/udp_relay/others)* {
|
http = tag equals "http"i address (username password)? (fast_open/udp_relay/others)* {
|
||||||
proxy.type = "http";
|
proxy.type = "http";
|
||||||
}
|
}
|
||||||
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_host/tls_verification/fast_open/udp_relay/others)* {
|
socks5 = tag equals "socks5"i address (username password)? (over_tls/tls_host/tls_verification/tls_cert_sha256/tls_pubkey_sha256/fast_open/udp_relay/others)* {
|
||||||
proxy.type = "socks5";
|
proxy.type = "socks5";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +118,7 @@ port = digits:[0-9]+ {
|
|||||||
method = comma cipher:cipher {
|
method = comma cipher:cipher {
|
||||||
proxy.cipher = cipher;
|
proxy.cipher = cipher;
|
||||||
}
|
}
|
||||||
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"auto"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"none"/"rc4-md5"/"rc4"/"salsa20"/"xchacha20-ietf-poly1305");
|
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"auto"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"none"/"rc4-md5"/"rc4"/"salsa20"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
|
||||||
|
|
||||||
username = & {
|
username = & {
|
||||||
let j = peg$currPos;
|
let j = peg$currPos;
|
||||||
@@ -170,12 +170,15 @@ vmess_alterId = comma "alterId" equals alterId:$[0-9]+ { proxy.alterId = parseIn
|
|||||||
over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
|
over_tls = comma "over-tls" equals flag:bool { proxy.tls = flag; }
|
||||||
tls_host = comma sni:("tls-name"/"sni") equals host:domain { proxy.sni = host; }
|
tls_host = comma sni:("tls-name"/"sni") equals host:domain { proxy.sni = host; }
|
||||||
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
|
tls_verification = comma "skip-cert-verify" equals flag:bool { proxy["skip-cert-verify"] = flag; }
|
||||||
|
tls_cert_sha256 = comma "tls-cert-sha256" equals match:[^,]+ { proxy["tls-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||||
|
tls_pubkey_sha256 = comma "tls-pubkey-sha256" equals match:[^,]+ { proxy["tls-pubkey-sha256"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||||
|
|
||||||
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
||||||
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
|
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
|
||||||
|
|
||||||
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
||||||
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
|
download_bandwidth = comma "download-bandwidth" equals match:[^,]+ { proxy.down = match.join(""); }
|
||||||
|
salamander_password = comma "salamander-password" equals match:[^,]+ { proxy['obfs-password'] = match.join(""); proxy.obfs = 'salamander'; }
|
||||||
|
|
||||||
tag = match:[^=,]* { proxy.name = match.join("").trim(); }
|
tag = match:[^=,]* { proxy.name = match.join("").trim(); }
|
||||||
comma = _ "," _
|
comma = _ "," _
|
||||||
|
|||||||
@@ -50,8 +50,11 @@ trojan = "trojan" equals address
|
|||||||
|
|
||||||
shadowsocks = "shadowsocks" equals address
|
shadowsocks = "shadowsocks" equals address
|
||||||
(password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp/fast_open/tag/server_check_url/others)* {
|
(password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp/fast_open/tag/server_check_url/others)* {
|
||||||
if (proxy.protocol) {
|
if (proxy.protocol || proxy.type === "ssr") {
|
||||||
proxy.type = "ssr";
|
proxy.type = "ssr";
|
||||||
|
if (!proxy.protocol) {
|
||||||
|
proxy.protocol = "origin";
|
||||||
|
}
|
||||||
// handle ssr obfs
|
// handle ssr obfs
|
||||||
if (obfs.host) proxy["obfs-param"] = obfs.host;
|
if (obfs.host) proxy["obfs-param"] = obfs.host;
|
||||||
if (obfs.type) proxy.obfs = obfs.type;
|
if (obfs.type) proxy.obfs = obfs.type;
|
||||||
@@ -172,7 +175,7 @@ tls_no_session_reuse = comma "tls-no-session-reuse" equals flag:bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
obfs_ss = comma "obfs" equals type:("http"/"tls"/"wss"/"ws"/"over-tls") { obfs.type = type; return type; }
|
obfs_ss = comma "obfs" equals type:("http"/"tls"/"wss"/"ws"/"over-tls") { obfs.type = type; return type; }
|
||||||
obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { obfs.type = type; return type; }
|
obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { proxy.type = "ssr"; obfs.type = type; return type; }
|
||||||
obfs = comma "obfs" equals type:("wss"/"ws"/"over-tls"/"http") { obfs.type = type; return type; };
|
obfs = comma "obfs" equals type:("wss"/"ws"/"over-tls"/"http") { obfs.type = type; return type; };
|
||||||
|
|
||||||
obfs_host = comma "obfs-host" equals host:domain { obfs.host = host; }
|
obfs_host = comma "obfs-host" equals host:domain { obfs.host = host; }
|
||||||
|
|||||||
@@ -48,8 +48,11 @@ trojan = "trojan" equals address
|
|||||||
|
|
||||||
shadowsocks = "shadowsocks" equals address
|
shadowsocks = "shadowsocks" equals address
|
||||||
(password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp/fast_open/tag/server_check_url/others)* {
|
(password/method/obfs_ssr/obfs_ss/obfs_host/obfs_uri/ssr_protocol/ssr_protocol_param/tls_pubkey_sha256/tls_alpn/tls_no_session_ticket/tls_no_session_reuse/tls_fingerprint/tls_verification/udp_relay/udp_over_tcp/fast_open/tag/server_check_url/others)* {
|
||||||
if (proxy.protocol) {
|
if (proxy.protocol || proxy.type === "ssr") {
|
||||||
proxy.type = "ssr";
|
proxy.type = "ssr";
|
||||||
|
if (!proxy.protocol) {
|
||||||
|
proxy.protocol = "origin";
|
||||||
|
}
|
||||||
// handle ssr obfs
|
// handle ssr obfs
|
||||||
if (obfs.host) proxy["obfs-param"] = obfs.host;
|
if (obfs.host) proxy["obfs-param"] = obfs.host;
|
||||||
if (obfs.type) proxy.obfs = obfs.type;
|
if (obfs.type) proxy.obfs = obfs.type;
|
||||||
@@ -170,7 +173,7 @@ tls_no_session_reuse = comma "tls-no-session-reuse" equals flag:bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
obfs_ss = comma "obfs" equals type:("http"/"tls"/"wss"/"ws"/"over-tls") { obfs.type = type; return type; }
|
obfs_ss = comma "obfs" equals type:("http"/"tls"/"wss"/"ws"/"over-tls") { obfs.type = type; return type; }
|
||||||
obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { obfs.type = type; return type; }
|
obfs_ssr = comma "obfs" equals type:("plain"/"http_simple"/"http_post"/"random_head"/"tls1.2_ticket_auth"/"tls1.2_ticket_fastauth") { proxy.type = "ssr"; obfs.type = type; return type; }
|
||||||
obfs = comma "obfs" equals type:("wss"/"ws"/"over-tls"/"http") { obfs.type = type; return type; };
|
obfs = comma "obfs" equals type:("wss"/"ws"/"over-tls"/"http") { obfs.type = type; return type; };
|
||||||
|
|
||||||
obfs_host = comma "obfs-host" equals host:domain { obfs.host = host; }
|
obfs_host = comma "obfs-host" equals host:domain { obfs.host = host; }
|
||||||
|
|||||||
@@ -37,11 +37,11 @@ const grammars = String.raw`
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
start = (shadowsocks/vmess/trojan/https/http/snell/socks5/socks5_tls/tuic/tuic_v5/wireguard/hysteria2/ssh) {
|
start = (shadowsocks/vmess/trojan/https/http/snell/socks5/socks5_tls/tuic/tuic_v5/wireguard/hysteria2/ssh/direct) {
|
||||||
return proxy;
|
return proxy;
|
||||||
}
|
}
|
||||||
|
|
||||||
shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/udp_port/others)* {
|
||||||
proxy.type = "ss";
|
proxy.type = "ss";
|
||||||
// handle obfs
|
// handle obfs
|
||||||
if (obfs.type == "http" || obfs.type === "tls") {
|
if (obfs.type == "http" || obfs.type === "tls") {
|
||||||
@@ -91,11 +91,11 @@ snell = tag equals "snell" address (snell_version/snell_psk/obfs/obfs_host/obfs_
|
|||||||
}
|
}
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
tuic = tag equals "tuic" address (alpn/token/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
tuic = tag equals "tuic" address (alpn/token/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
|
||||||
proxy.type = "tuic";
|
proxy.type = "tuic";
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
tuic_v5 = tag equals "tuic-v5" address (alpn/passwordk/uuidk/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
tuic_v5 = tag equals "tuic-v5" address (alpn/passwordk/uuidk/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
|
||||||
proxy.type = "tuic";
|
proxy.type = "tuic";
|
||||||
proxy.version = 5;
|
proxy.version = 5;
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
@@ -104,19 +104,22 @@ wireguard = tag equals "wireguard" (section_name/no_error_alert/ip_version/under
|
|||||||
proxy.type = "wireguard-surge";
|
proxy.type = "wireguard-surge";
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
hysteria2 = tag equals "hysteria2" address (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_verification/passwordk/tls_fingerprint/download_bandwidth/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
hysteria2 = tag equals "hysteria2" address (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_verification/passwordk/tls_fingerprint/download_bandwidth/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
|
||||||
proxy.type = "hysteria2";
|
proxy.type = "hysteria2";
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||||
proxy.type = "socks5";
|
proxy.type = "socks5";
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_fingerprint/tls_verification/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_fingerprint/tls_verification/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||||
proxy.type = "socks5";
|
proxy.type = "socks5";
|
||||||
proxy.tls = true;
|
proxy.tls = true;
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
|
direct = tag equals "direct" (udp_relay/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/block_quic/others)* {
|
||||||
|
proxy.type = "direct";
|
||||||
|
}
|
||||||
|
|
||||||
address = comma server:server comma port:port {
|
address = comma server:server comma port:port {
|
||||||
proxy.server = server;
|
proxy.server = server;
|
||||||
@@ -151,6 +154,8 @@ port = digits:[0-9]+ {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
port_hopping_interval = comma "port-hopping-interval" equals match:$[0-9]+ { proxy["hop-interval"] = parseInt(match.trim()); }
|
||||||
|
|
||||||
username = & {
|
username = & {
|
||||||
let j = peg$currPos;
|
let j = peg$currPos;
|
||||||
let start, end;
|
let start, end;
|
||||||
@@ -191,14 +196,14 @@ snell_psk = comma "psk" equals match:[^,]+ { proxy.psk = match.join(""); }
|
|||||||
snell_version = comma "version" equals match:$[0-9]+ { proxy.version = parseInt(match.trim()); }
|
snell_version = comma "version" equals match:$[0-9]+ { proxy.version = parseInt(match.trim()); }
|
||||||
|
|
||||||
usernamek = comma "username" equals match:[^,]+ { proxy.username = match.join(""); }
|
usernamek = comma "username" equals match:[^,]+ { proxy.username = match.join(""); }
|
||||||
passwordk = comma "password" equals match:[^,]+ { proxy.password = match.join(""); }
|
passwordk = comma "password" equals match:[^,]+ { proxy.password = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
|
||||||
vmess_uuid = comma "username" equals match:[^,]+ { proxy.uuid = match.join(""); }
|
vmess_uuid = comma "username" equals match:[^,]+ { proxy.uuid = match.join(""); }
|
||||||
vmess_aead = comma "vmess-aead" equals flag:bool { proxy.aead = flag; }
|
vmess_aead = comma "vmess-aead" equals flag:bool { proxy.aead = flag; }
|
||||||
|
|
||||||
method = comma "encrypt-method" equals cipher:cipher {
|
method = comma "encrypt-method" equals cipher:cipher {
|
||||||
proxy.cipher = cipher;
|
proxy.cipher = cipher;
|
||||||
}
|
}
|
||||||
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"idea-cfb"/"none"/"rc2-cfb"/"rc4-md5"/"rc4"/"salsa20"/"seed-cfb"/"xchacha20-ietf-poly1305");
|
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"idea-cfb"/"none"/"rc2-cfb"/"rc4-md5"/"rc4"/"salsa20"/"seed-cfb"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
|
||||||
|
|
||||||
ws = comma "ws" equals flag:bool { obfs.type = "ws"; }
|
ws = comma "ws" equals flag:bool { obfs.type = "ws"; }
|
||||||
ws_headers = comma "ws-headers" equals headers:$[^,]+ {
|
ws_headers = comma "ws-headers" equals headers:$[^,]+ {
|
||||||
@@ -217,7 +222,7 @@ obfs_host = comma "obfs-host" equals host:domain { obfs.host = host; };
|
|||||||
obfs_uri = comma "obfs-uri" equals path:uri { obfs.path = path }
|
obfs_uri = comma "obfs-uri" equals path:uri { obfs.path = path }
|
||||||
uri = $[^,]+
|
uri = $[^,]+
|
||||||
|
|
||||||
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
|
udp_relay = comma "udp-relay" equals flag:bool { proxy.udp = flag; }
|
||||||
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
||||||
reuse = comma "reuse" equals flag:bool { proxy.reuse = flag; }
|
reuse = comma "reuse" equals flag:bool { proxy.reuse = flag; }
|
||||||
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
||||||
@@ -238,6 +243,7 @@ idle_timeout = comma "idle-timeout" equals match:$[0-9]+ { proxy["idle-timeout"]
|
|||||||
private_key = comma "private-key" equals match:[^,]+ { proxy["keystore-private-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
private_key = comma "private-key" equals match:[^,]+ { proxy["keystore-private-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||||
server_fingerprint = comma "server-fingerprint" equals match:[^,]+ { proxy["server-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
server_fingerprint = comma "server-fingerprint" equals match:[^,]+ { proxy["server-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||||
block_quic = comma "block-quic" equals match:[^,]+ { proxy["block-quic"] = match.join(""); }
|
block_quic = comma "block-quic" equals match:[^,]+ { proxy["block-quic"] = match.join(""); }
|
||||||
|
udp_port = comma "udp-port" equals match:$[0-9]+ { proxy["udp-port"] = parseInt(match.trim()); }
|
||||||
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
|
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
|
||||||
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
|
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
|
||||||
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }
|
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }
|
||||||
|
|||||||
@@ -35,11 +35,11 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
start = (shadowsocks/vmess/trojan/https/http/snell/socks5/socks5_tls/tuic/tuic_v5/wireguard/hysteria2/ssh) {
|
start = (shadowsocks/vmess/trojan/https/http/snell/socks5/socks5_tls/tuic/tuic_v5/wireguard/hysteria2/ssh/direct) {
|
||||||
return proxy;
|
return proxy;
|
||||||
}
|
}
|
||||||
|
|
||||||
shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
shadowsocks = tag equals "ss" address (method/passwordk/obfs/obfs_host/obfs_uri/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/udp_relay/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/udp_port/others)* {
|
||||||
proxy.type = "ss";
|
proxy.type = "ss";
|
||||||
// handle obfs
|
// handle obfs
|
||||||
if (obfs.type == "http" || obfs.type === "tls") {
|
if (obfs.type == "http" || obfs.type === "tls") {
|
||||||
@@ -89,11 +89,11 @@ snell = tag equals "snell" address (snell_version/snell_psk/obfs/obfs_host/obfs_
|
|||||||
}
|
}
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
tuic = tag equals "tuic" address (alpn/token/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
tuic = tag equals "tuic" address (alpn/token/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
|
||||||
proxy.type = "tuic";
|
proxy.type = "tuic";
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
tuic_v5 = tag equals "tuic-v5" address (alpn/passwordk/uuidk/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
tuic_v5 = tag equals "tuic-v5" address (alpn/passwordk/uuidk/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/tls_fingerprint/tls_verification/sni/fast_open/tfo/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
|
||||||
proxy.type = "tuic";
|
proxy.type = "tuic";
|
||||||
proxy.version = 5;
|
proxy.version = 5;
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
@@ -102,20 +102,22 @@ wireguard = tag equals "wireguard" (section_name/no_error_alert/ip_version/under
|
|||||||
proxy.type = "wireguard-surge";
|
proxy.type = "wireguard-surge";
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
hysteria2 = tag equals "hysteria2" address (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_verification/passwordk/tls_fingerprint/download_bandwidth/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
hysteria2 = tag equals "hysteria2" address (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_verification/passwordk/tls_fingerprint/download_bandwidth/ecn/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/port_hopping_interval/others)* {
|
||||||
proxy.type = "hysteria2";
|
proxy.type = "hysteria2";
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
socks5 = tag equals "socks5" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||||
proxy.type = "socks5";
|
proxy.type = "socks5";
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_fingerprint/tls_verification/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
socks5_tls = tag equals "socks5-tls" address (username password)? (usernamek passwordk)? (udp_relay/no_error_alert/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/sni/tls_fingerprint/tls_verification/fast_open/shadow_tls_version/shadow_tls_sni/shadow_tls_password/block_quic/others)* {
|
||||||
proxy.type = "socks5";
|
proxy.type = "socks5";
|
||||||
proxy.tls = true;
|
proxy.tls = true;
|
||||||
handleShadowTLS();
|
handleShadowTLS();
|
||||||
}
|
}
|
||||||
|
direct = tag equals "direct" (udp_relay/ip_version/underlying_proxy/tos/allow_other_interface/interface/test_url/test_udp/test_timeout/hybrid/no_error_alert/fast_open/block_quic/others)* {
|
||||||
|
proxy.type = "direct";
|
||||||
|
}
|
||||||
address = comma server:server comma port:port {
|
address = comma server:server comma port:port {
|
||||||
proxy.server = server;
|
proxy.server = server;
|
||||||
proxy.port = port;
|
proxy.port = port;
|
||||||
@@ -149,6 +151,8 @@ port = digits:[0-9]+ {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
port_hopping_interval = comma "port-hopping-interval" equals match:$[0-9]+ { proxy["hop-interval"] = parseInt(match.trim()); }
|
||||||
|
|
||||||
username = & {
|
username = & {
|
||||||
let j = peg$currPos;
|
let j = peg$currPos;
|
||||||
let start, end;
|
let start, end;
|
||||||
@@ -189,14 +193,14 @@ snell_psk = comma "psk" equals match:[^,]+ { proxy.psk = match.join(""); }
|
|||||||
snell_version = comma "version" equals match:$[0-9]+ { proxy.version = parseInt(match.trim()); }
|
snell_version = comma "version" equals match:$[0-9]+ { proxy.version = parseInt(match.trim()); }
|
||||||
|
|
||||||
usernamek = comma "username" equals match:[^,]+ { proxy.username = match.join(""); }
|
usernamek = comma "username" equals match:[^,]+ { proxy.username = match.join(""); }
|
||||||
passwordk = comma "password" equals match:[^,]+ { proxy.password = match.join(""); }
|
passwordk = comma "password" equals match:[^,]+ { proxy.password = match.join("").replace(/^"(.*?)"$/, '$1').replace(/^'(.*?)'$/, '$1'); }
|
||||||
vmess_uuid = comma "username" equals match:[^,]+ { proxy.uuid = match.join(""); }
|
vmess_uuid = comma "username" equals match:[^,]+ { proxy.uuid = match.join(""); }
|
||||||
vmess_aead = comma "vmess-aead" equals flag:bool { proxy.aead = flag; }
|
vmess_aead = comma "vmess-aead" equals flag:bool { proxy.aead = flag; }
|
||||||
|
|
||||||
method = comma "encrypt-method" equals cipher:cipher {
|
method = comma "encrypt-method" equals cipher:cipher {
|
||||||
proxy.cipher = cipher;
|
proxy.cipher = cipher;
|
||||||
}
|
}
|
||||||
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"idea-cfb"/"none"/"rc2-cfb"/"rc4-md5"/"rc4"/"salsa20"/"seed-cfb"/"xchacha20-ietf-poly1305");
|
cipher = ("aes-128-cfb"/"aes-128-ctr"/"aes-128-gcm"/"aes-192-cfb"/"aes-192-ctr"/"aes-192-gcm"/"aes-256-cfb"/"aes-256-ctr"/"aes-256-gcm"/"bf-cfb"/"camellia-128-cfb"/"camellia-192-cfb"/"camellia-256-cfb"/"cast5-cfb"/"chacha20-ietf-poly1305"/"chacha20-ietf"/"chacha20-poly1305"/"chacha20"/"des-cfb"/"idea-cfb"/"none"/"rc2-cfb"/"rc4-md5"/"rc4"/"salsa20"/"seed-cfb"/"xchacha20-ietf-poly1305"/"2022-blake3-aes-128-gcm"/"2022-blake3-aes-256-gcm");
|
||||||
|
|
||||||
ws = comma "ws" equals flag:bool { obfs.type = "ws"; }
|
ws = comma "ws" equals flag:bool { obfs.type = "ws"; }
|
||||||
ws_headers = comma "ws-headers" equals headers:$[^,]+ {
|
ws_headers = comma "ws-headers" equals headers:$[^,]+ {
|
||||||
@@ -215,7 +219,7 @@ obfs_host = comma "obfs-host" equals host:domain { obfs.host = host; };
|
|||||||
obfs_uri = comma "obfs-uri" equals path:uri { obfs.path = path }
|
obfs_uri = comma "obfs-uri" equals path:uri { obfs.path = path }
|
||||||
uri = $[^,]+
|
uri = $[^,]+
|
||||||
|
|
||||||
udp_relay = comma "udp" equals flag:bool { proxy.udp = flag; }
|
udp_relay = comma "udp-relay" equals flag:bool { proxy.udp = flag; }
|
||||||
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
fast_open = comma "fast-open" equals flag:bool { proxy.tfo = flag; }
|
||||||
reuse = comma "reuse" equals flag:bool { proxy.reuse = flag; }
|
reuse = comma "reuse" equals flag:bool { proxy.reuse = flag; }
|
||||||
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
ecn = comma "ecn" equals flag:bool { proxy.ecn = flag; }
|
||||||
@@ -236,6 +240,7 @@ idle_timeout = comma "idle-timeout" equals match:$[0-9]+ { proxy["idle-timeout"]
|
|||||||
private_key = comma "private-key" equals match:[^,]+ { proxy["keystore-private-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
private_key = comma "private-key" equals match:[^,]+ { proxy["keystore-private-key"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||||
server_fingerprint = comma "server-fingerprint" equals match:[^,]+ { proxy["server-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
server_fingerprint = comma "server-fingerprint" equals match:[^,]+ { proxy["server-fingerprint"] = match.join("").replace(/^"(.*)"$/, '$1'); }
|
||||||
block_quic = comma "block-quic" equals match:[^,]+ { proxy["block-quic"] = match.join(""); }
|
block_quic = comma "block-quic" equals match:[^,]+ { proxy["block-quic"] = match.join(""); }
|
||||||
|
udp_port = comma "udp-port" equals match:$[0-9]+ { proxy["udp-port"] = parseInt(match.trim()); }
|
||||||
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
|
shadow_tls_version = comma "shadow-tls-version" equals match:$[0-9]+ { proxy["shadow-tls-version"] = parseInt(match.trim()); }
|
||||||
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
|
shadow_tls_sni = comma "shadow-tls-sni" equals match:[^,]+ { proxy["shadow-tls-sni"] = match.join(""); }
|
||||||
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }
|
shadow_tls_password = comma "shadow-tls-password" equals match:[^,]+ { proxy["shadow-tls-password"] = match.join(""); }
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ port = digits:[0-9]+ {
|
|||||||
params = "?" head:param tail:("&"@param)* {
|
params = "?" head:param tail:("&"@param)* {
|
||||||
proxy["skip-cert-verify"] = toBool(params["allowInsecure"]);
|
proxy["skip-cert-verify"] = toBool(params["allowInsecure"]);
|
||||||
proxy.sni = params["sni"] || params["peer"];
|
proxy.sni = params["sni"] || params["peer"];
|
||||||
|
proxy['client-fingerprint'] = params.fp;
|
||||||
|
proxy.alpn = params.alpn ? decodeURIComponent(params.alpn).split(',') : undefined;
|
||||||
|
|
||||||
if (toBool(params["ws"])) {
|
if (toBool(params["ws"])) {
|
||||||
proxy.network = "ws";
|
proxy.network = "ws";
|
||||||
@@ -89,11 +91,17 @@ params = "?" head:param tail:("&"@param)* {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (params["type"]) {
|
if (params["type"]) {
|
||||||
|
let httpupgrade
|
||||||
proxy.network = params["type"]
|
proxy.network = params["type"]
|
||||||
|
if(proxy.network === 'httpupgrade') {
|
||||||
|
proxy.network = 'ws'
|
||||||
|
httpupgrade = true
|
||||||
|
}
|
||||||
if (['grpc'].includes(proxy.network)) {
|
if (['grpc'].includes(proxy.network)) {
|
||||||
proxy[proxy.network + '-opts'] = {
|
proxy[proxy.network + '-opts'] = {
|
||||||
'grpc-service-name': params["serviceName"],
|
'grpc-service-name': params["serviceName"],
|
||||||
'_grpc-type': params["mode"],
|
'_grpc-type': params["mode"],
|
||||||
|
'_grpc-authority': params["authority"],
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
if (params["path"]) {
|
if (params["path"]) {
|
||||||
@@ -102,6 +110,10 @@ params = "?" head:param tail:("&"@param)* {
|
|||||||
if (params["host"]) {
|
if (params["host"]) {
|
||||||
$set(proxy, proxy.network+"-opts.headers.Host", decodeURIComponent(params["host"]));
|
$set(proxy, proxy.network+"-opts.headers.Host", decodeURIComponent(params["host"]));
|
||||||
}
|
}
|
||||||
|
if (httpupgrade) {
|
||||||
|
$set(proxy, proxy.network+"-opts.v2ray-http-upgrade", true);
|
||||||
|
$set(proxy, proxy.network+"-opts.v2ray-http-upgrade-fast-open", true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -80,6 +80,8 @@ port = digits:[0-9]+ {
|
|||||||
params = "?" head:param tail:("&"@param)* {
|
params = "?" head:param tail:("&"@param)* {
|
||||||
proxy["skip-cert-verify"] = toBool(params["allowInsecure"]);
|
proxy["skip-cert-verify"] = toBool(params["allowInsecure"]);
|
||||||
proxy.sni = params["sni"] || params["peer"];
|
proxy.sni = params["sni"] || params["peer"];
|
||||||
|
proxy['client-fingerprint'] = params.fp;
|
||||||
|
proxy.alpn = params.alpn ? decodeURIComponent(params.alpn).split(',') : undefined;
|
||||||
|
|
||||||
if (toBool(params["ws"])) {
|
if (toBool(params["ws"])) {
|
||||||
proxy.network = "ws";
|
proxy.network = "ws";
|
||||||
@@ -87,11 +89,17 @@ params = "?" head:param tail:("&"@param)* {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (params["type"]) {
|
if (params["type"]) {
|
||||||
|
let httpupgrade
|
||||||
proxy.network = params["type"]
|
proxy.network = params["type"]
|
||||||
|
if(proxy.network === 'httpupgrade') {
|
||||||
|
proxy.network = 'ws'
|
||||||
|
httpupgrade = true
|
||||||
|
}
|
||||||
if (['grpc'].includes(proxy.network)) {
|
if (['grpc'].includes(proxy.network)) {
|
||||||
proxy[proxy.network + '-opts'] = {
|
proxy[proxy.network + '-opts'] = {
|
||||||
'grpc-service-name': params["serviceName"],
|
'grpc-service-name': params["serviceName"],
|
||||||
'_grpc-type': params["mode"],
|
'_grpc-type': params["mode"],
|
||||||
|
'_grpc-authority': params["authority"],
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
if (params["path"]) {
|
if (params["path"]) {
|
||||||
@@ -100,6 +108,10 @@ params = "?" head:param tail:("&"@param)* {
|
|||||||
if (params["host"]) {
|
if (params["host"]) {
|
||||||
$set(proxy, proxy.network+"-opts.headers.Host", decodeURIComponent(params["host"]));
|
$set(proxy, proxy.network+"-opts.headers.Host", decodeURIComponent(params["host"]));
|
||||||
}
|
}
|
||||||
|
if (httpupgrade) {
|
||||||
|
$set(proxy, proxy.network+"-opts.v2ray-http-upgrade", true);
|
||||||
|
$set(proxy, proxy.network+"-opts.v2ray-http-upgrade-fast-open", true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ function Base64Encoded() {
|
|||||||
'aHR0c', // htt
|
'aHR0c', // htt
|
||||||
'dmxlc3M=', // vless
|
'dmxlc3M=', // vless
|
||||||
'aHlzdGVyaWEy', // hysteria2
|
'aHlzdGVyaWEy', // hysteria2
|
||||||
|
'aHkyOi8v', // hy2://
|
||||||
'd2lyZWd1YXJkOi8v', // wireguard://
|
'd2lyZWd1YXJkOi8v', // wireguard://
|
||||||
'd2c6Ly8=', // wg://
|
'd2c6Ly8=', // wg://
|
||||||
'dHVpYzovLw==', // tuic://
|
'dHVpYzovLw==', // tuic://
|
||||||
@@ -49,10 +50,32 @@ function Clash() {
|
|||||||
};
|
};
|
||||||
const parse = function (raw) {
|
const parse = function (raw) {
|
||||||
// Clash YAML format
|
// Clash YAML format
|
||||||
|
|
||||||
|
// 防止 VLESS节点 reality-opts 选项中的 short-id 被解析成 Infinity
|
||||||
|
// 匹配 short-id 冒号后面的值(包含空格和引号)
|
||||||
|
const afterReplace = raw.replace(
|
||||||
|
/short-id:([ ]*[^,\n}]*)/g,
|
||||||
|
(matched, value) => {
|
||||||
|
const afterTrim = value.trim();
|
||||||
|
|
||||||
|
// 为空
|
||||||
|
if (!afterTrim || afterTrim === '') {
|
||||||
|
return 'short-id: ""'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 是否被引号包裹
|
||||||
|
if (/^(['"]).*\1$/.test(afterTrim)) {
|
||||||
|
return `short-id: ${afterTrim}`;
|
||||||
|
} else {
|
||||||
|
return `short-id: "${afterTrim}"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
proxies,
|
proxies,
|
||||||
'global-client-fingerprint': globalClientFingerprint,
|
'global-client-fingerprint': globalClientFingerprint,
|
||||||
} = safeLoad(raw);
|
} = safeLoad(afterReplace);
|
||||||
return proxies
|
return proxies
|
||||||
.map((p) => {
|
.map((p) => {
|
||||||
// https://github.com/MetaCubeX/mihomo/blob/Alpha/docs/config.yaml#L73C1-L73C26
|
// https://github.com/MetaCubeX/mihomo/blob/Alpha/docs/config.yaml#L73C1-L73C26
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
import resourceCache from '@/utils/resource-cache';
|
import resourceCache from '@/utils/resource-cache';
|
||||||
import scriptResourceCache from '@/utils/script-resource-cache';
|
import scriptResourceCache from '@/utils/script-resource-cache';
|
||||||
import { isIPv4, isIPv6 } from '@/utils';
|
import { isIPv4, isIPv6, ipAddress } from '@/utils';
|
||||||
import { FULL } from '@/utils/logical';
|
import { FULL } from '@/utils/logical';
|
||||||
import { getFlag } from '@/utils/geo';
|
import { getFlag, removeFlag } from '@/utils/geo';
|
||||||
|
import { doh } from '@/utils/dns';
|
||||||
import lodash from 'lodash';
|
import lodash from 'lodash';
|
||||||
import $ from '@/core/app';
|
import $ from '@/core/app';
|
||||||
import { hex_md5 } from '@/vendor/md5';
|
import { hex_md5 } from '@/vendor/md5';
|
||||||
import { ProxyUtils } from '@/core/proxy-utils';
|
import { ProxyUtils } from '@/core/proxy-utils';
|
||||||
import { produceArtifact } from '@/restful/sync';
|
import { produceArtifact } from '@/restful/sync';
|
||||||
|
import { SETTINGS_KEY } from '@/constants';
|
||||||
|
|
||||||
import env from '@/utils/env';
|
import env from '@/utils/env';
|
||||||
import {
|
import {
|
||||||
@@ -314,7 +316,7 @@ function RegexDeleteOperator(regex) {
|
|||||||
1. This function name should be `operator`!
|
1. This function name should be `operator`!
|
||||||
2. Always declare variables before using them!
|
2. Always declare variables before using them!
|
||||||
*/
|
*/
|
||||||
function ScriptOperator(script, targetPlatform, $arguments, source) {
|
function ScriptOperator(script, targetPlatform, $arguments, source, $options) {
|
||||||
return {
|
return {
|
||||||
name: 'Script Operator',
|
name: 'Script Operator',
|
||||||
func: async (proxies) => {
|
func: async (proxies) => {
|
||||||
@@ -324,6 +326,7 @@ function ScriptOperator(script, targetPlatform, $arguments, source) {
|
|||||||
'operator',
|
'operator',
|
||||||
script,
|
script,
|
||||||
$arguments,
|
$arguments,
|
||||||
|
$options,
|
||||||
);
|
);
|
||||||
output = operator(proxies, targetPlatform, { source, ...env });
|
output = operator(proxies, targetPlatform, { source, ...env });
|
||||||
})();
|
})();
|
||||||
@@ -336,9 +339,9 @@ function ScriptOperator(script, targetPlatform, $arguments, source) {
|
|||||||
'operator',
|
'operator',
|
||||||
`async function operator(input = []) {
|
`async function operator(input = []) {
|
||||||
if (input && (input.$files || input.$content)) {
|
if (input && (input.$files || input.$content)) {
|
||||||
let { $content, $files } = input
|
let { $content, $files, $options } = input
|
||||||
${script}
|
${script}
|
||||||
return { $content, $files }
|
return { $content, $files, $options }
|
||||||
} else {
|
} else {
|
||||||
let proxies = input
|
let proxies = input
|
||||||
let list = []
|
let list = []
|
||||||
@@ -350,6 +353,7 @@ function ScriptOperator(script, targetPlatform, $arguments, source) {
|
|||||||
}
|
}
|
||||||
}`,
|
}`,
|
||||||
$arguments,
|
$arguments,
|
||||||
|
$options,
|
||||||
);
|
);
|
||||||
output = operator(proxies, targetPlatform, { source, ...env });
|
output = operator(proxies, targetPlatform, { source, ...env });
|
||||||
})();
|
})();
|
||||||
@@ -362,9 +366,6 @@ function parseIP4P(IP4P) {
|
|||||||
let server;
|
let server;
|
||||||
let port;
|
let port;
|
||||||
try {
|
try {
|
||||||
if (!/^2001::[^:]+:[^:]+:[^:]+$/.test(IP4P)) {
|
|
||||||
throw new Error(`Invalid IP4P: ${IP4P}`);
|
|
||||||
}
|
|
||||||
let array = IP4P.split(':');
|
let array = IP4P.split(':');
|
||||||
|
|
||||||
port = parseInt(array[2], 16);
|
port = parseInt(array[2], 16);
|
||||||
@@ -389,31 +390,61 @@ function parseIP4P(IP4P) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const DOMAIN_RESOLVERS = {
|
const DOMAIN_RESOLVERS = {
|
||||||
Google: async function (domain, type, noCache) {
|
Custom: async function (domain, type, noCache, timeout, edns, url) {
|
||||||
const id = hex_md5(`GOOGLE:${domain}:${type}`);
|
const id = hex_md5(`CUSTOM:${url}:${domain}:${type}`);
|
||||||
const cached = resourceCache.get(id);
|
const cached = resourceCache.get(id);
|
||||||
if (!noCache && cached) return cached;
|
if (!noCache && cached) return cached;
|
||||||
const resp = await $.http.get({
|
const answerType = type === 'IPv6' ? 'AAAA' : 'A';
|
||||||
url: `https://8.8.4.4/resolve?name=${encodeURIComponent(
|
const res = await doh({
|
||||||
domain,
|
url,
|
||||||
)}&type=${type === 'IPv6' ? 'AAAA' : 'A'}`,
|
domain,
|
||||||
headers: {
|
type: answerType,
|
||||||
accept: 'application/dns-json',
|
timeout,
|
||||||
},
|
edns,
|
||||||
});
|
});
|
||||||
const body = JSON.parse(resp.body);
|
|
||||||
if (body['Status'] !== 0) {
|
const { answers } = res;
|
||||||
throw new Error(`Status is ${body['Status']}`);
|
if (!Array.isArray(answers) || answers.length === 0) {
|
||||||
}
|
throw new Error('No answers');
|
||||||
const answers = body['Answer'];
|
}
|
||||||
if (answers.length === 0) {
|
const result = answers
|
||||||
|
.filter((i) => i?.type === answerType)
|
||||||
|
.map((i) => i?.data)
|
||||||
|
.filter((i) => i);
|
||||||
|
if (result.length === 0) {
|
||||||
throw new Error('No answers');
|
throw new Error('No answers');
|
||||||
}
|
}
|
||||||
const result = answers[answers.length - 1].data;
|
|
||||||
resourceCache.set(id, result);
|
resourceCache.set(id, result);
|
||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
'IP-API': async function (domain, type, noCache) {
|
Google: async function (domain, type, noCache, timeout, edns) {
|
||||||
|
const id = hex_md5(`GOOGLE:${domain}:${type}`);
|
||||||
|
const cached = resourceCache.get(id);
|
||||||
|
if (!noCache && cached) return cached;
|
||||||
|
const answerType = type === 'IPv6' ? 'AAAA' : 'A';
|
||||||
|
const res = await doh({
|
||||||
|
url: 'https://8.8.4.4/dns-query',
|
||||||
|
domain,
|
||||||
|
type: answerType,
|
||||||
|
timeout,
|
||||||
|
edns,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { answers } = res;
|
||||||
|
if (!Array.isArray(answers) || answers.length === 0) {
|
||||||
|
throw new Error('No answers');
|
||||||
|
}
|
||||||
|
const result = answers
|
||||||
|
.filter((i) => i?.type === answerType)
|
||||||
|
.map((i) => i?.data)
|
||||||
|
.filter((i) => i);
|
||||||
|
if (result.length === 0) {
|
||||||
|
throw new Error('No answers');
|
||||||
|
}
|
||||||
|
resourceCache.set(id, result);
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
'IP-API': async function (domain, type, noCache, timeout) {
|
||||||
if (['IPv6'].includes(type)) {
|
if (['IPv6'].includes(type)) {
|
||||||
throw new Error(`域名解析服务提供方 IP-API 不支持 ${type}`);
|
throw new Error(`域名解析服务提供方 IP-API 不支持 ${type}`);
|
||||||
}
|
}
|
||||||
@@ -424,100 +455,138 @@ const DOMAIN_RESOLVERS = {
|
|||||||
url: `http://ip-api.com/json/${encodeURIComponent(
|
url: `http://ip-api.com/json/${encodeURIComponent(
|
||||||
domain,
|
domain,
|
||||||
)}?lang=zh-CN`,
|
)}?lang=zh-CN`,
|
||||||
|
timeout,
|
||||||
});
|
});
|
||||||
const body = JSON.parse(resp.body);
|
const body = JSON.parse(resp.body);
|
||||||
if (body['status'] !== 'success') {
|
if (body['status'] !== 'success') {
|
||||||
throw new Error(`Status is ${body['status']}`);
|
throw new Error(`Status is ${body['status']}`);
|
||||||
}
|
}
|
||||||
const result = body.query;
|
if (!body.query || body.query === 0) {
|
||||||
|
throw new Error('No answers');
|
||||||
|
}
|
||||||
|
const result = [body.query];
|
||||||
|
if (result.length === 0) {
|
||||||
|
throw new Error('No answers');
|
||||||
|
}
|
||||||
resourceCache.set(id, result);
|
resourceCache.set(id, result);
|
||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
Cloudflare: async function (domain, type, noCache) {
|
Cloudflare: async function (domain, type, noCache, timeout, edns) {
|
||||||
const id = hex_md5(`CLOUDFLARE:${domain}:${type}`);
|
const id = hex_md5(`CLOUDFLARE:${domain}:${type}`);
|
||||||
const cached = resourceCache.get(id);
|
const cached = resourceCache.get(id);
|
||||||
if (!noCache && cached) return cached;
|
if (!noCache && cached) return cached;
|
||||||
const resp = await $.http.get({
|
const answerType = type === 'IPv6' ? 'AAAA' : 'A';
|
||||||
url: `https://1.0.0.1/dns-query?name=${encodeURIComponent(
|
const res = await doh({
|
||||||
domain,
|
url: 'https://1.0.0.1/dns-query',
|
||||||
)}&type=${type === 'IPv6' ? 'AAAA' : 'A'}`,
|
domain,
|
||||||
headers: {
|
type: answerType,
|
||||||
accept: 'application/dns-json',
|
timeout,
|
||||||
},
|
edns,
|
||||||
});
|
});
|
||||||
const body = JSON.parse(resp.body);
|
|
||||||
if (body['Status'] !== 0) {
|
const { answers } = res;
|
||||||
throw new Error(`Status is ${body['Status']}`);
|
if (!Array.isArray(answers) || answers.length === 0) {
|
||||||
}
|
throw new Error('No answers');
|
||||||
const answers = body['Answer'];
|
}
|
||||||
if (answers.length === 0) {
|
const result = answers
|
||||||
|
.filter((i) => i?.type === answerType)
|
||||||
|
.map((i) => i?.data)
|
||||||
|
.filter((i) => i);
|
||||||
|
if (result.length === 0) {
|
||||||
throw new Error('No answers');
|
throw new Error('No answers');
|
||||||
}
|
}
|
||||||
const result = answers[answers.length - 1].data;
|
|
||||||
resourceCache.set(id, result);
|
resourceCache.set(id, result);
|
||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
Ali: async function (domain, type, noCache) {
|
Ali: async function (domain, type, noCache, timeout, edns) {
|
||||||
const id = hex_md5(`ALI:${domain}:${type}`);
|
const id = hex_md5(`ALI:${domain}:${type}`);
|
||||||
const cached = resourceCache.get(id);
|
const cached = resourceCache.get(id);
|
||||||
if (!noCache && cached) return cached;
|
if (!noCache && cached) return cached;
|
||||||
const resp = await $.http.get({
|
const resp = await $.http.get({
|
||||||
url: `http://223.6.6.6/resolve?name=${encodeURIComponent(
|
url: `http://223.6.6.6/resolve?edns_client_subnet=${edns}/24&name=${encodeURIComponent(
|
||||||
domain,
|
domain,
|
||||||
)}&type=${type === 'IPv6' ? 'AAAA' : 'A'}&short=1`,
|
)}&type=${type === 'IPv6' ? 'AAAA' : 'A'}&short=1`,
|
||||||
headers: {
|
headers: {
|
||||||
accept: 'application/dns-json',
|
accept: 'application/dns-json',
|
||||||
},
|
},
|
||||||
|
timeout,
|
||||||
});
|
});
|
||||||
const answers = JSON.parse(resp.body);
|
const answers = JSON.parse(resp.body);
|
||||||
if (answers.length === 0) {
|
if (!Array.isArray(answers) || answers.length === 0) {
|
||||||
|
throw new Error('No answers');
|
||||||
|
}
|
||||||
|
const result = answers;
|
||||||
|
if (result.length === 0) {
|
||||||
throw new Error('No answers');
|
throw new Error('No answers');
|
||||||
}
|
}
|
||||||
const result = answers[answers.length - 1];
|
|
||||||
resourceCache.set(id, result);
|
resourceCache.set(id, result);
|
||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
Tencent: async function (domain, type, noCache) {
|
Tencent: async function (domain, type, noCache, timeout, edns) {
|
||||||
const id = hex_md5(`ALI:${domain}:${type}`);
|
const id = hex_md5(`TENCENT:${domain}:${type}`);
|
||||||
const cached = resourceCache.get(id);
|
const cached = resourceCache.get(id);
|
||||||
if (!noCache && cached) return cached;
|
if (!noCache && cached) return cached;
|
||||||
const resp = await $.http.get({
|
const resp = await $.http.get({
|
||||||
url: `http://119.28.28.28/d?type=${
|
url: `http://119.28.28.28/d?ip=${edns}&type=${
|
||||||
type === 'IPv6' ? 'AAAA' : 'A'
|
type === 'IPv6' ? 'AAAA' : 'A'
|
||||||
}&dn=${encodeURIComponent(domain)}`,
|
}&dn=${encodeURIComponent(domain)}`,
|
||||||
headers: {
|
headers: {
|
||||||
accept: 'application/dns-json',
|
accept: 'application/dns-json',
|
||||||
},
|
},
|
||||||
|
timeout,
|
||||||
});
|
});
|
||||||
const answers = resp.body.split(';').map((i) => i.split(',')[0]);
|
const answers = resp.body.split(';').map((i) => i.split(',')[0]);
|
||||||
if (answers.length === 0 || String(answers) === '0') {
|
if (answers.length === 0 || String(answers) === '0') {
|
||||||
throw new Error('No answers');
|
throw new Error('No answers');
|
||||||
}
|
}
|
||||||
const result = answers[answers.length - 1];
|
const result = answers;
|
||||||
|
if (result.length === 0) {
|
||||||
|
throw new Error('No answers');
|
||||||
|
}
|
||||||
resourceCache.set(id, result);
|
resourceCache.set(id, result);
|
||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function ResolveDomainOperator({ provider, type: _type, filter, cache }) {
|
function ResolveDomainOperator({
|
||||||
|
provider,
|
||||||
|
type: _type,
|
||||||
|
filter,
|
||||||
|
cache,
|
||||||
|
url,
|
||||||
|
timeout,
|
||||||
|
edns: _edns,
|
||||||
|
}) {
|
||||||
if (['IPv6', 'IP4P'].includes(_type) && ['IP-API'].includes(provider)) {
|
if (['IPv6', 'IP4P'].includes(_type) && ['IP-API'].includes(provider)) {
|
||||||
throw new Error(`域名解析服务提供方 ${provider} 不支持 ${_type}`);
|
throw new Error(`域名解析服务提供方 ${provider} 不支持 ${_type}`);
|
||||||
}
|
}
|
||||||
|
const { defaultTimeout } = $.read(SETTINGS_KEY);
|
||||||
|
const requestTimeout = timeout || defaultTimeout || 8000;
|
||||||
let type = ['IPv6', 'IP4P'].includes(_type) ? 'IPv6' : 'IPv4';
|
let type = ['IPv6', 'IP4P'].includes(_type) ? 'IPv6' : 'IPv4';
|
||||||
|
|
||||||
const resolver = DOMAIN_RESOLVERS[provider];
|
const resolver = DOMAIN_RESOLVERS[provider];
|
||||||
if (!resolver) {
|
if (!resolver) {
|
||||||
throw new Error(`找不到域名解析服务提供方: ${provider}`);
|
throw new Error(`找不到域名解析服务提供方: ${provider}`);
|
||||||
}
|
}
|
||||||
|
let edns = _edns || '223.6.6.6';
|
||||||
|
if (!isIP(edns)) throw new Error(`域名解析 EDNS 应为 IP`);
|
||||||
|
$.info(
|
||||||
|
`Domain Resolver: [${_type}] ${provider} ${edns || ''} ${url || ''}`,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
name: 'Resolve Domain Operator',
|
name: 'Resolve Domain Operator',
|
||||||
func: async (proxies) => {
|
func: async (proxies) => {
|
||||||
|
proxies.forEach((p, i) => {
|
||||||
|
if (!p['_no-resolve'] && p['no-resolve']) {
|
||||||
|
proxies[i]['_no-resolve'] = p['no-resolve'];
|
||||||
|
}
|
||||||
|
});
|
||||||
const results = {};
|
const results = {};
|
||||||
const limit = 15; // more than 20 concurrency may result in surge TCP connection shortage.
|
const limit = 15; // more than 20 concurrency may result in surge TCP connection shortage.
|
||||||
const totalDomain = [
|
const totalDomain = [
|
||||||
...new Set(
|
...new Set(
|
||||||
proxies
|
proxies
|
||||||
.filter((p) => !isIP(p.server) && !p['no-resolve'])
|
.filter((p) => !isIP(p.server) && !p['_no-resolve'])
|
||||||
.map((c) => c.server),
|
.map((c) => c.server),
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
@@ -526,7 +595,14 @@ function ResolveDomainOperator({ provider, type: _type, filter, cache }) {
|
|||||||
const currentBatch = [];
|
const currentBatch = [];
|
||||||
for (let domain of totalDomain.splice(0, limit)) {
|
for (let domain of totalDomain.splice(0, limit)) {
|
||||||
currentBatch.push(
|
currentBatch.push(
|
||||||
resolver(domain, type, cache === 'disabled')
|
resolver(
|
||||||
|
domain,
|
||||||
|
type,
|
||||||
|
cache === 'disabled',
|
||||||
|
requestTimeout,
|
||||||
|
edns,
|
||||||
|
url,
|
||||||
|
)
|
||||||
.then((ip) => {
|
.then((ip) => {
|
||||||
results[domain] = ip;
|
results[domain] = ip;
|
||||||
$.info(
|
$.info(
|
||||||
@@ -543,34 +619,58 @@ function ResolveDomainOperator({ provider, type: _type, filter, cache }) {
|
|||||||
await Promise.all(currentBatch);
|
await Promise.all(currentBatch);
|
||||||
}
|
}
|
||||||
proxies.forEach((p) => {
|
proxies.forEach((p) => {
|
||||||
if (!p['no-resolve']) {
|
if (!p['_no-resolve']) {
|
||||||
if (results[p.server]) {
|
if (results[p.server]) {
|
||||||
if (_type === 'IP4P') {
|
p._resolved_ips = results[p.server];
|
||||||
const { server, port } = parseIP4P(
|
let ip = Array.isArray(results[p.server])
|
||||||
results[p.server],
|
? results[p.server][
|
||||||
);
|
Math.floor(
|
||||||
if (server && port) {
|
Math.random() * results[p.server].length,
|
||||||
|
)
|
||||||
|
]
|
||||||
|
: results[p.server];
|
||||||
|
if (type === 'IPv6' && isIPv6(ip)) {
|
||||||
|
try {
|
||||||
|
ip = new ipAddress.Address6(ip).correctForm();
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`Failed to parse IPv6 address: ${ip}: ${e}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (/^2001::[^:]+:[^:]+:[^:]+$/.test(ip)) {
|
||||||
|
p._IP4P = ip;
|
||||||
|
const { server, port } = parseIP4P(ip);
|
||||||
|
if (server && port) {
|
||||||
|
p._domain = p.server;
|
||||||
|
p.server = server;
|
||||||
|
p.port = port;
|
||||||
|
p.resolved = true;
|
||||||
|
p._IPv4 = p.server;
|
||||||
|
if (!isIP(p._IP)) {
|
||||||
|
p._IP = p.server;
|
||||||
|
}
|
||||||
|
} else if (!p.resolved) {
|
||||||
|
p.resolved = false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
p._domain = p.server;
|
p._domain = p.server;
|
||||||
p.server = server;
|
p.server = ip;
|
||||||
p.port = port;
|
|
||||||
p.resolved = true;
|
p.resolved = true;
|
||||||
p._IPv4 = p.server;
|
p[`_${type}`] = p.server;
|
||||||
if (!isIP(p._IP)) {
|
if (!isIP(p._IP)) {
|
||||||
p._IP = p.server;
|
p._IP = p.server;
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
p.resolved = false;
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
p._domain = p.server;
|
p._domain = p.server;
|
||||||
p.server = results[p.server];
|
p.server = ip;
|
||||||
p.resolved = true;
|
p.resolved = true;
|
||||||
p[`_${type}`] = p.server;
|
p[`_${type}`] = p.server;
|
||||||
if (!isIP(p._IP)) {
|
if (!isIP(p._IP)) {
|
||||||
p._IP = p.server;
|
p._IP = p.server;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if (!p.resolved) {
|
||||||
p.resolved = false;
|
p.resolved = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -578,7 +678,7 @@ function ResolveDomainOperator({ provider, type: _type, filter, cache }) {
|
|||||||
|
|
||||||
return proxies.filter((p) => {
|
return proxies.filter((p) => {
|
||||||
if (filter === 'removeFailed') {
|
if (filter === 'removeFailed') {
|
||||||
return isIP(p.server) || p['no-resolve'] || p.resolved;
|
return isIP(p.server) || p['_no-resolve'] || p.resolved;
|
||||||
} else if (filter === 'IPOnly') {
|
} else if (filter === 'IPOnly') {
|
||||||
return isIP(p.server);
|
return isIP(p.server);
|
||||||
} else if (filter === 'IPv4Only') {
|
} else if (filter === 'IPv4Only') {
|
||||||
@@ -599,24 +699,45 @@ function isIP(ip) {
|
|||||||
|
|
||||||
ResolveDomainOperator.resolver = DOMAIN_RESOLVERS;
|
ResolveDomainOperator.resolver = DOMAIN_RESOLVERS;
|
||||||
|
|
||||||
|
function isAscii(str) {
|
||||||
|
// eslint-disable-next-line no-control-regex
|
||||||
|
var pattern = /^[\x00-\x7F]+$/; // ASCII 范围的 Unicode 编码
|
||||||
|
return pattern.test(str);
|
||||||
|
}
|
||||||
|
|
||||||
/**************************** Filters ***************************************/
|
/**************************** Filters ***************************************/
|
||||||
// filter useless proxies
|
// filter useless proxies
|
||||||
function UselessFilter() {
|
function UselessFilter() {
|
||||||
const KEYWORDS = [
|
|
||||||
'网址',
|
|
||||||
'流量',
|
|
||||||
'时间',
|
|
||||||
'应急',
|
|
||||||
'过期',
|
|
||||||
'Bandwidth',
|
|
||||||
'expire',
|
|
||||||
];
|
|
||||||
return {
|
return {
|
||||||
name: 'Useless Filter',
|
name: 'Useless Filter',
|
||||||
func: RegexFilter({
|
func: (proxies) => {
|
||||||
regex: KEYWORDS,
|
return proxies.map((proxy) => {
|
||||||
keep: false,
|
if (proxy.cipher && !isAscii(proxy.cipher)) {
|
||||||
}).func,
|
return false;
|
||||||
|
} else if (proxy.password && !isAscii(proxy.password)) {
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
if (proxy.network) {
|
||||||
|
let transportHosts =
|
||||||
|
proxy[`${proxy.network}-opts`]?.headers?.Host ||
|
||||||
|
proxy[`${proxy.network}-opts`]?.headers?.host;
|
||||||
|
transportHosts = Array.isArray(transportHosts)
|
||||||
|
? transportHosts
|
||||||
|
: [transportHosts];
|
||||||
|
if (
|
||||||
|
transportHosts.some(
|
||||||
|
(host) => host && !isAscii(host),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return !/网址|流量|时间|应急|过期|Bandwidth|expire/.test(
|
||||||
|
proxy.name,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -692,7 +813,7 @@ function TypeFilter(types) {
|
|||||||
1. This function name should be `filter`!
|
1. This function name should be `filter`!
|
||||||
2. Always declare variables before using them!
|
2. Always declare variables before using them!
|
||||||
*/
|
*/
|
||||||
function ScriptFilter(script, targetPlatform, $arguments, source) {
|
function ScriptFilter(script, targetPlatform, $arguments, source, $options) {
|
||||||
return {
|
return {
|
||||||
name: 'Script Filter',
|
name: 'Script Filter',
|
||||||
func: async (proxies) => {
|
func: async (proxies) => {
|
||||||
@@ -702,6 +823,7 @@ function ScriptFilter(script, targetPlatform, $arguments, source) {
|
|||||||
'filter',
|
'filter',
|
||||||
script,
|
script,
|
||||||
$arguments,
|
$arguments,
|
||||||
|
$options,
|
||||||
);
|
);
|
||||||
output = filter(proxies, targetPlatform, { source, ...env });
|
output = filter(proxies, targetPlatform, { source, ...env });
|
||||||
})();
|
})();
|
||||||
@@ -724,6 +846,7 @@ function ScriptFilter(script, targetPlatform, $arguments, source) {
|
|||||||
return list
|
return list
|
||||||
}`,
|
}`,
|
||||||
$arguments,
|
$arguments,
|
||||||
|
$options,
|
||||||
);
|
);
|
||||||
output = filter(proxies, targetPlatform, { source, ...env });
|
output = filter(proxies, targetPlatform, { source, ...env });
|
||||||
})();
|
})();
|
||||||
@@ -864,14 +987,7 @@ function clone(object) {
|
|||||||
return JSON.parse(JSON.stringify(object));
|
return JSON.parse(JSON.stringify(object));
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove flag
|
function createDynamicFunction(name, script, $arguments, $options) {
|
||||||
function removeFlag(str) {
|
|
||||||
return str
|
|
||||||
.replace(/[\uD83C][\uDDE6-\uDDFF][\uD83C][\uDDE6-\uDDFF]|🏴☠️|🏳️🌈/g, '')
|
|
||||||
.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
function createDynamicFunction(name, script, $arguments) {
|
|
||||||
const flowUtils = {
|
const flowUtils = {
|
||||||
getFlowField,
|
getFlowField,
|
||||||
getFlowHeaders,
|
getFlowHeaders,
|
||||||
@@ -883,6 +999,7 @@ function createDynamicFunction(name, script, $arguments) {
|
|||||||
if ($.env.isLoon) {
|
if ($.env.isLoon) {
|
||||||
return new Function(
|
return new Function(
|
||||||
'$arguments',
|
'$arguments',
|
||||||
|
'$options',
|
||||||
'$substore',
|
'$substore',
|
||||||
'lodash',
|
'lodash',
|
||||||
'$persistentStore',
|
'$persistentStore',
|
||||||
@@ -892,9 +1009,11 @@ function createDynamicFunction(name, script, $arguments) {
|
|||||||
'scriptResourceCache',
|
'scriptResourceCache',
|
||||||
'flowUtils',
|
'flowUtils',
|
||||||
'produceArtifact',
|
'produceArtifact',
|
||||||
|
'require',
|
||||||
`${script}\n return ${name}`,
|
`${script}\n return ${name}`,
|
||||||
)(
|
)(
|
||||||
$arguments,
|
$arguments,
|
||||||
|
$options,
|
||||||
$,
|
$,
|
||||||
lodash,
|
lodash,
|
||||||
// eslint-disable-next-line no-undef
|
// eslint-disable-next-line no-undef
|
||||||
@@ -907,26 +1026,30 @@ function createDynamicFunction(name, script, $arguments) {
|
|||||||
scriptResourceCache,
|
scriptResourceCache,
|
||||||
flowUtils,
|
flowUtils,
|
||||||
produceArtifact,
|
produceArtifact,
|
||||||
|
eval(`typeof require !== "undefined"`) ? require : undefined,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
return new Function(
|
return new Function(
|
||||||
'$arguments',
|
'$arguments',
|
||||||
|
'$options',
|
||||||
'$substore',
|
'$substore',
|
||||||
'lodash',
|
'lodash',
|
||||||
'ProxyUtils',
|
'ProxyUtils',
|
||||||
'scriptResourceCache',
|
'scriptResourceCache',
|
||||||
'flowUtils',
|
'flowUtils',
|
||||||
'produceArtifact',
|
'produceArtifact',
|
||||||
|
'require',
|
||||||
`${script}\n return ${name}`,
|
`${script}\n return ${name}`,
|
||||||
)(
|
)(
|
||||||
$arguments,
|
$arguments,
|
||||||
|
$options,
|
||||||
$,
|
$,
|
||||||
lodash,
|
lodash,
|
||||||
ProxyUtils,
|
ProxyUtils,
|
||||||
scriptResourceCache,
|
scriptResourceCache,
|
||||||
flowUtils,
|
flowUtils,
|
||||||
produceArtifact,
|
produceArtifact,
|
||||||
|
eval(`typeof require !== "undefined"`) ? require : undefined,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,9 +133,13 @@ export default function Clash_Producer() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
['trojan', 'tuic', 'hysteria', 'hysteria2'].includes(
|
[
|
||||||
proxy.type,
|
'trojan',
|
||||||
)
|
'tuic',
|
||||||
|
'hysteria',
|
||||||
|
'hysteria2',
|
||||||
|
'juicity',
|
||||||
|
].includes(proxy.type)
|
||||||
) {
|
) {
|
||||||
delete proxy.tls;
|
delete proxy.tls;
|
||||||
}
|
}
|
||||||
@@ -158,9 +162,12 @@ export default function Clash_Producer() {
|
|||||||
delete proxy.collectionName;
|
delete proxy.collectionName;
|
||||||
delete proxy.id;
|
delete proxy.id;
|
||||||
delete proxy.resolved;
|
delete proxy.resolved;
|
||||||
for (const key in proxy) {
|
delete proxy['no-resolve'];
|
||||||
if (proxy[key] == null || /^_/i.test(key)) {
|
if (type !== 'internal') {
|
||||||
delete proxy[key];
|
for (const key in proxy) {
|
||||||
|
if (proxy[key] == null || /^_/i.test(key)) {
|
||||||
|
delete proxy[key];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
@@ -168,6 +175,7 @@ export default function Clash_Producer() {
|
|||||||
proxy[`${proxy.network}-opts`]
|
proxy[`${proxy.network}-opts`]
|
||||||
) {
|
) {
|
||||||
delete proxy[`${proxy.network}-opts`]['_grpc-type'];
|
delete proxy[`${proxy.network}-opts`]['_grpc-type'];
|
||||||
|
delete proxy[`${proxy.network}-opts`]['_grpc-authority'];
|
||||||
}
|
}
|
||||||
return proxy;
|
return proxy;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -149,9 +149,13 @@ export default function ClashMeta_Producer() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
['trojan', 'tuic', 'hysteria', 'hysteria2'].includes(
|
[
|
||||||
proxy.type,
|
'trojan',
|
||||||
)
|
'tuic',
|
||||||
|
'hysteria',
|
||||||
|
'hysteria2',
|
||||||
|
'juicity',
|
||||||
|
].includes(proxy.type)
|
||||||
) {
|
) {
|
||||||
delete proxy.tls;
|
delete proxy.tls;
|
||||||
}
|
}
|
||||||
@@ -173,9 +177,12 @@ export default function ClashMeta_Producer() {
|
|||||||
delete proxy.collectionName;
|
delete proxy.collectionName;
|
||||||
delete proxy.id;
|
delete proxy.id;
|
||||||
delete proxy.resolved;
|
delete proxy.resolved;
|
||||||
for (const key in proxy) {
|
delete proxy['no-resolve'];
|
||||||
if (proxy[key] == null || /^_/i.test(key)) {
|
if (type !== 'internal') {
|
||||||
delete proxy[key];
|
for (const key in proxy) {
|
||||||
|
if (proxy[key] == null || /^_/i.test(key)) {
|
||||||
|
delete proxy[key];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
@@ -183,6 +190,7 @@ export default function ClashMeta_Producer() {
|
|||||||
proxy[`${proxy.network}-opts`]
|
proxy[`${proxy.network}-opts`]
|
||||||
) {
|
) {
|
||||||
delete proxy[`${proxy.network}-opts`]['_grpc-type'];
|
delete proxy[`${proxy.network}-opts`]['_grpc-type'];
|
||||||
|
delete proxy[`${proxy.network}-opts`]['_grpc-authority'];
|
||||||
}
|
}
|
||||||
return proxy;
|
return proxy;
|
||||||
});
|
});
|
||||||
|
|||||||
298
backend/src/core/proxy-utils/producers/egern.js
Normal file
298
backend/src/core/proxy-utils/producers/egern.js
Normal file
@@ -0,0 +1,298 @@
|
|||||||
|
export default function Egern_Producer() {
|
||||||
|
const type = 'ALL';
|
||||||
|
const produce = (proxies, type, opts = {}) => {
|
||||||
|
// https://egernapp.com/zh-CN/docs/configuration/proxies
|
||||||
|
const list = proxies
|
||||||
|
.filter((proxy) => {
|
||||||
|
if (opts['include-unsupported-proxy']) return true;
|
||||||
|
if (
|
||||||
|
![
|
||||||
|
'http',
|
||||||
|
'socks5',
|
||||||
|
'ss',
|
||||||
|
'trojan',
|
||||||
|
'hysteria2',
|
||||||
|
'vless',
|
||||||
|
'vmess',
|
||||||
|
].includes(proxy.type) ||
|
||||||
|
(proxy.type === 'ss' &&
|
||||||
|
((proxy.plugin === 'obfs' &&
|
||||||
|
!['http', 'tls'].includes(
|
||||||
|
proxy['plugin-opts']?.mode,
|
||||||
|
)) ||
|
||||||
|
![
|
||||||
|
'chacha20-ietf-poly1305',
|
||||||
|
'chacha20-poly1305',
|
||||||
|
'aes-256-gcm',
|
||||||
|
'aes-128-gcm',
|
||||||
|
'none',
|
||||||
|
'tbale',
|
||||||
|
'rc4',
|
||||||
|
'rc4-md5',
|
||||||
|
'aes-128-cfb',
|
||||||
|
'aes-192-cfb',
|
||||||
|
'aes-256-cfb',
|
||||||
|
'aes-128-ctr',
|
||||||
|
'aes-192-ctr',
|
||||||
|
'aes-256-ctr',
|
||||||
|
'bf-cfb',
|
||||||
|
'camellia-128-cfb',
|
||||||
|
'camellia-192-cfb',
|
||||||
|
'camellia-256-cfb',
|
||||||
|
'cast5-cfb',
|
||||||
|
'des-cfb',
|
||||||
|
'idea-cfb',
|
||||||
|
'rc2-cfb',
|
||||||
|
'seed-cfb',
|
||||||
|
'salsa20',
|
||||||
|
'chacha20',
|
||||||
|
'chacha20-ietf',
|
||||||
|
].includes(proxy.cipher))) ||
|
||||||
|
(proxy.type === 'vmess' &&
|
||||||
|
(![
|
||||||
|
'auto',
|
||||||
|
'aes-128-gcm',
|
||||||
|
'chacha20-poly1305',
|
||||||
|
'none',
|
||||||
|
'zero',
|
||||||
|
].includes(proxy.cipher) ||
|
||||||
|
(!['http', 'ws', 'tcp'].includes(proxy.network) &&
|
||||||
|
proxy.network))) ||
|
||||||
|
(proxy.type === 'trojan' &&
|
||||||
|
!['http', 'ws', 'tcp'].includes(proxy.network) &&
|
||||||
|
proxy.network) ||
|
||||||
|
(proxy.type === 'vless' &&
|
||||||
|
(typeof proxy.flow !== 'undefined' ||
|
||||||
|
proxy['reality-opts'] ||
|
||||||
|
(!['http', 'ws', 'tcp'].includes(proxy.network) &&
|
||||||
|
proxy.network)))
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.map((proxy) => {
|
||||||
|
if (proxy.type === 'http') {
|
||||||
|
proxy = {
|
||||||
|
type: 'http',
|
||||||
|
name: proxy.name,
|
||||||
|
server: proxy.server,
|
||||||
|
port: proxy.port,
|
||||||
|
username: proxy.username,
|
||||||
|
password: proxy.password,
|
||||||
|
tfo: proxy.tfo || proxy['fast-open'],
|
||||||
|
next_hop: proxy.next_hop,
|
||||||
|
};
|
||||||
|
} else if (proxy.type === 'socks5') {
|
||||||
|
proxy = {
|
||||||
|
type: 'socks5',
|
||||||
|
name: proxy.name,
|
||||||
|
server: proxy.server,
|
||||||
|
port: proxy.port,
|
||||||
|
username: proxy.username,
|
||||||
|
password: proxy.password,
|
||||||
|
tfo: proxy.tfo || proxy['fast-open'],
|
||||||
|
udp_relay:
|
||||||
|
proxy.udp || proxy.udp_relay || proxy.udp_relay,
|
||||||
|
next_hop: proxy.next_hop,
|
||||||
|
};
|
||||||
|
} else if (proxy.type === 'ss') {
|
||||||
|
proxy = {
|
||||||
|
type: 'shadowsocks',
|
||||||
|
name: proxy.name,
|
||||||
|
method:
|
||||||
|
proxy.cipher === 'chacha20-ietf-poly1305'
|
||||||
|
? 'chacha20-poly1305'
|
||||||
|
: proxy.cipher,
|
||||||
|
server: proxy.server,
|
||||||
|
port: proxy.port,
|
||||||
|
password: proxy.password,
|
||||||
|
tfo: proxy.tfo || proxy['fast-open'],
|
||||||
|
udp_relay:
|
||||||
|
proxy.udp || proxy.udp_relay || proxy.udp_relay,
|
||||||
|
next_hop: proxy.next_hop,
|
||||||
|
};
|
||||||
|
if (proxy.plugin === 'obfs') {
|
||||||
|
proxy.obfs = proxy['plugin-opts'].mode;
|
||||||
|
proxy.obfs_host = proxy['plugin-opts'].host;
|
||||||
|
proxy.obfs_uri = proxy['plugin-opts'].path;
|
||||||
|
}
|
||||||
|
} else if (proxy.type === 'hysteria2') {
|
||||||
|
proxy = {
|
||||||
|
type: 'hysteria2',
|
||||||
|
name: proxy.name,
|
||||||
|
server: proxy.server,
|
||||||
|
port: proxy.port,
|
||||||
|
auth: proxy.password,
|
||||||
|
tfo: proxy.tfo || proxy['fast-open'],
|
||||||
|
udp_relay:
|
||||||
|
proxy.udp || proxy.udp_relay || proxy.udp_relay,
|
||||||
|
next_hop: proxy.next_hop,
|
||||||
|
sni: proxy.sni,
|
||||||
|
skip_tls_verify: proxy['skip-cert-verify'],
|
||||||
|
};
|
||||||
|
if (proxy['obfs-password'] && proxy.obfs == 'salamander') {
|
||||||
|
proxy.obfs = 'salamander';
|
||||||
|
proxy.obfs_password = proxy['obfs-password'];
|
||||||
|
}
|
||||||
|
} else if (proxy.type === 'trojan') {
|
||||||
|
if (proxy.network === 'ws') {
|
||||||
|
proxy.websocket = {
|
||||||
|
path: proxy['ws-opts']?.path,
|
||||||
|
host: proxy['ws-opts']?.headers?.Host,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
proxy = {
|
||||||
|
type: 'trojan',
|
||||||
|
name: proxy.name,
|
||||||
|
server: proxy.server,
|
||||||
|
port: proxy.port,
|
||||||
|
password: proxy.password,
|
||||||
|
tfo: proxy.tfo || proxy['fast-open'],
|
||||||
|
udp_relay:
|
||||||
|
proxy.udp || proxy.udp_relay || proxy.udp_relay,
|
||||||
|
next_hop: proxy.next_hop,
|
||||||
|
sni: proxy.sni,
|
||||||
|
skip_tls_verify: proxy['skip-cert-verify'],
|
||||||
|
websocket: proxy.websocket,
|
||||||
|
};
|
||||||
|
} else if (proxy.type === 'vmess') {
|
||||||
|
if (proxy.network === 'ws') {
|
||||||
|
proxy.transport = {
|
||||||
|
[proxy.tls ? 'wss' : 'ws']: {
|
||||||
|
path: proxy['ws-opts']?.path,
|
||||||
|
headers: {
|
||||||
|
Host: proxy['ws-opts']?.headers?.Host,
|
||||||
|
},
|
||||||
|
sni: proxy.tls ? proxy.sni : undefined,
|
||||||
|
skip_tls_verify: proxy.tls
|
||||||
|
? proxy['skip-cert-verify']
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} else if (proxy.network === 'http') {
|
||||||
|
proxy.transport = {
|
||||||
|
http: {
|
||||||
|
method: proxy['http-opts']?.method,
|
||||||
|
path: proxy['http-opts']?.path,
|
||||||
|
headers: {
|
||||||
|
Host: Array.isArray(
|
||||||
|
proxy['http-opts']?.headers?.Host,
|
||||||
|
)
|
||||||
|
? proxy['http-opts']?.headers?.Host[0]
|
||||||
|
: proxy['http-opts']?.headers?.Host,
|
||||||
|
},
|
||||||
|
skip_tls_verify: proxy['skip-cert-verify'],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} else if (proxy.network === 'tcp' || !proxy.network) {
|
||||||
|
proxy.transport = {
|
||||||
|
[proxy.tls ? 'tls' : 'tcp']: {
|
||||||
|
sni: proxy.tls ? proxy.sni : undefined,
|
||||||
|
skip_tls_verify: proxy.tls
|
||||||
|
? proxy['skip-cert-verify']
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
proxy = {
|
||||||
|
type: 'vmess',
|
||||||
|
name: proxy.name,
|
||||||
|
server: proxy.server,
|
||||||
|
port: proxy.port,
|
||||||
|
user_id: proxy.uuid,
|
||||||
|
security: proxy.cipher,
|
||||||
|
tfo: proxy.tfo || proxy['fast-open'],
|
||||||
|
legacy: proxy.legacy,
|
||||||
|
udp_relay:
|
||||||
|
proxy.udp || proxy.udp_relay || proxy.udp_relay,
|
||||||
|
next_hop: proxy.next_hop,
|
||||||
|
transport: proxy.transport,
|
||||||
|
// sni: proxy.sni,
|
||||||
|
// skip_tls_verify: proxy['skip-cert-verify'],
|
||||||
|
};
|
||||||
|
} else if (proxy.type === 'vless') {
|
||||||
|
if (proxy.network === 'ws') {
|
||||||
|
proxy.transport = {
|
||||||
|
[proxy.tls ? 'wss' : 'ws']: {
|
||||||
|
path: proxy['ws-opts']?.path,
|
||||||
|
headers: {
|
||||||
|
Host: proxy['ws-opts']?.headers?.Host,
|
||||||
|
},
|
||||||
|
sni: proxy.tls ? proxy.sni : undefined,
|
||||||
|
skip_tls_verify: proxy.tls
|
||||||
|
? proxy['skip-cert-verify']
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} else if (proxy.network === 'http') {
|
||||||
|
proxy.transport = {
|
||||||
|
http: {
|
||||||
|
method: proxy['http-opts']?.method,
|
||||||
|
path: proxy['http-opts']?.path,
|
||||||
|
headers: {
|
||||||
|
Host: Array.isArray(
|
||||||
|
proxy['http-opts']?.headers?.Host,
|
||||||
|
)
|
||||||
|
? proxy['http-opts']?.headers?.Host[0]
|
||||||
|
: proxy['http-opts']?.headers?.Host,
|
||||||
|
},
|
||||||
|
skip_tls_verify: proxy['skip-cert-verify'],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} else if (proxy.network === 'tcp' || !proxy.network) {
|
||||||
|
proxy.transport = {
|
||||||
|
[proxy.tls ? 'tls' : 'tcp']: {
|
||||||
|
sni: proxy.tls ? proxy.sni : undefined,
|
||||||
|
skip_tls_verify: proxy.tls
|
||||||
|
? proxy['skip-cert-verify']
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
proxy = {
|
||||||
|
type: 'vless',
|
||||||
|
name: proxy.name,
|
||||||
|
server: proxy.server,
|
||||||
|
port: proxy.port,
|
||||||
|
user_id: proxy.uuid,
|
||||||
|
security: proxy.cipher,
|
||||||
|
tfo: proxy.tfo || proxy['fast-open'],
|
||||||
|
legacy: proxy.legacy,
|
||||||
|
udp_relay:
|
||||||
|
proxy.udp || proxy.udp_relay || proxy.udp_relay,
|
||||||
|
next_hop: proxy.next_hop,
|
||||||
|
transport: proxy.transport,
|
||||||
|
// sni: proxy.sni,
|
||||||
|
// skip_tls_verify: proxy['skip-cert-verify'],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
delete proxy.subName;
|
||||||
|
delete proxy.collectionName;
|
||||||
|
delete proxy.id;
|
||||||
|
delete proxy.resolved;
|
||||||
|
delete proxy['no-resolve'];
|
||||||
|
if (type !== 'internal') {
|
||||||
|
for (const key in proxy) {
|
||||||
|
if (proxy[key] == null || /^_/i.test(key)) {
|
||||||
|
delete proxy[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
[proxy.type]: {
|
||||||
|
...proxy,
|
||||||
|
type: undefined,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return type === 'internal'
|
||||||
|
? list
|
||||||
|
: 'proxies:\n' +
|
||||||
|
list
|
||||||
|
.map((proxy) => ' - ' + JSON.stringify(proxy) + '\n')
|
||||||
|
.join('');
|
||||||
|
};
|
||||||
|
return { type, produce };
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import QX_Producer from './qx';
|
|||||||
import Shadowrocket_Producer from './shadowrocket';
|
import Shadowrocket_Producer from './shadowrocket';
|
||||||
import Surfboard_Producer from './surfboard';
|
import Surfboard_Producer from './surfboard';
|
||||||
import singbox_Producer from './sing-box';
|
import singbox_Producer from './sing-box';
|
||||||
|
import Egern_Producer from './egern';
|
||||||
|
|
||||||
function JSON_Producer() {
|
function JSON_Producer() {
|
||||||
const type = 'ALL';
|
const type = 'ALL';
|
||||||
@@ -34,4 +35,5 @@ export default {
|
|||||||
ShadowRocket: Shadowrocket_Producer(),
|
ShadowRocket: Shadowrocket_Producer(),
|
||||||
Surfboard: Surfboard_Producer(),
|
Surfboard: Surfboard_Producer(),
|
||||||
'sing-box': singbox_Producer(),
|
'sing-box': singbox_Producer(),
|
||||||
|
Egern: Egern_Producer(),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ import { isPresent, Result } from './utils';
|
|||||||
import { isIPv4, isIPv6 } from '@/utils';
|
import { isIPv4, isIPv6 } from '@/utils';
|
||||||
|
|
||||||
export default function Loon_Producer() {
|
export default function Loon_Producer() {
|
||||||
const produce = (proxy) => {
|
const produce = (proxy, type, opts = {}) => {
|
||||||
switch (proxy.type) {
|
switch (proxy.type) {
|
||||||
case 'ss':
|
case 'ss':
|
||||||
return shadowsocks(proxy);
|
return shadowsocks(proxy, opts['include-unsupported-proxy']);
|
||||||
case 'ssr':
|
case 'ssr':
|
||||||
return shadowsocksr(proxy);
|
return shadowsocksr(proxy);
|
||||||
case 'trojan':
|
case 'trojan':
|
||||||
@@ -32,7 +32,7 @@ export default function Loon_Producer() {
|
|||||||
return { produce };
|
return { produce };
|
||||||
}
|
}
|
||||||
|
|
||||||
function shadowsocks(proxy) {
|
function shadowsocks(proxy, includeUnsupportedProxy) {
|
||||||
const result = new Result(proxy);
|
const result = new Result(proxy);
|
||||||
if (
|
if (
|
||||||
![
|
![
|
||||||
@@ -56,6 +56,9 @@ function shadowsocks(proxy) {
|
|||||||
'aes-256-gcm',
|
'aes-256-gcm',
|
||||||
'chacha20-ietf-poly1305',
|
'chacha20-ietf-poly1305',
|
||||||
'xchacha20-ietf-poly1305',
|
'xchacha20-ietf-poly1305',
|
||||||
|
...(includeUnsupportedProxy
|
||||||
|
? ['2022-blake3-aes-128-gcm', '2022-blake3-aes-256-gcm']
|
||||||
|
: []),
|
||||||
].includes(proxy.cipher)
|
].includes(proxy.cipher)
|
||||||
) {
|
) {
|
||||||
throw new Error(`cipher ${proxy.cipher} is not supported`);
|
throw new Error(`cipher ${proxy.cipher} is not supported`);
|
||||||
@@ -153,6 +156,14 @@ function trojan(proxy) {
|
|||||||
|
|
||||||
// sni
|
// sni
|
||||||
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,tls-cert-sha256=${proxy['tls-fingerprint']}`,
|
||||||
|
'tls-fingerprint',
|
||||||
|
);
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,tls-pubkey-sha256=${proxy['tls-pubkey-sha256']}`,
|
||||||
|
'tls-pubkey-sha256',
|
||||||
|
);
|
||||||
|
|
||||||
// tfo
|
// tfo
|
||||||
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
||||||
@@ -215,6 +226,14 @@ function vmess(proxy) {
|
|||||||
|
|
||||||
// sni
|
// sni
|
||||||
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,tls-cert-sha256=${proxy['tls-fingerprint']}`,
|
||||||
|
'tls-fingerprint',
|
||||||
|
);
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,tls-pubkey-sha256=${proxy['tls-pubkey-sha256']}`,
|
||||||
|
'tls-pubkey-sha256',
|
||||||
|
);
|
||||||
|
|
||||||
// AEAD
|
// AEAD
|
||||||
if (isPresent(proxy, 'aead')) {
|
if (isPresent(proxy, 'aead')) {
|
||||||
@@ -286,6 +305,14 @@ function vless(proxy) {
|
|||||||
|
|
||||||
// sni
|
// sni
|
||||||
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,tls-cert-sha256=${proxy['tls-fingerprint']}`,
|
||||||
|
'tls-fingerprint',
|
||||||
|
);
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,tls-pubkey-sha256=${proxy['tls-pubkey-sha256']}`,
|
||||||
|
'tls-pubkey-sha256',
|
||||||
|
);
|
||||||
|
|
||||||
// tfo
|
// tfo
|
||||||
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
||||||
@@ -339,6 +366,11 @@ function socks5(proxy) {
|
|||||||
// tfo
|
// tfo
|
||||||
result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo');
|
result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo');
|
||||||
|
|
||||||
|
// udp
|
||||||
|
if (proxy.udp) {
|
||||||
|
result.append(`,udp=true`);
|
||||||
|
}
|
||||||
|
|
||||||
return result.toString();
|
return result.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -408,8 +440,8 @@ function wireguard(proxy) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function hysteria2(proxy) {
|
function hysteria2(proxy) {
|
||||||
if (proxy.obfs || proxy['obfs-password']) {
|
if (proxy['obfs-password'] && proxy.obfs != 'salamander') {
|
||||||
throw new Error(`obfs is unsupported`);
|
throw new Error(`only salamander obfs is supported`);
|
||||||
}
|
}
|
||||||
const result = new Result(proxy);
|
const result = new Result(proxy);
|
||||||
result.append(`${proxy.name}=Hysteria2,${proxy.server},${proxy.port}`);
|
result.append(`${proxy.name}=Hysteria2,${proxy.server},${proxy.port}`);
|
||||||
@@ -418,11 +450,23 @@ function hysteria2(proxy) {
|
|||||||
|
|
||||||
// sni
|
// sni
|
||||||
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
result.appendIfPresent(`,tls-name=${proxy.sni}`, 'sni');
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,tls-cert-sha256=${proxy['tls-fingerprint']}`,
|
||||||
|
'tls-fingerprint',
|
||||||
|
);
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,tls-pubkey-sha256=${proxy['tls-pubkey-sha256']}`,
|
||||||
|
'tls-pubkey-sha256',
|
||||||
|
);
|
||||||
result.appendIfPresent(
|
result.appendIfPresent(
|
||||||
`,skip-cert-verify=${proxy['skip-cert-verify']}`,
|
`,skip-cert-verify=${proxy['skip-cert-verify']}`,
|
||||||
'skip-cert-verify',
|
'skip-cert-verify',
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (proxy['obfs-password'] && proxy.obfs == 'salamander') {
|
||||||
|
result.append(`,salamander-password=${proxy['obfs-password']}`);
|
||||||
|
}
|
||||||
|
|
||||||
// tfo
|
// tfo
|
||||||
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
result.appendIfPresent(`,fast-open=${proxy.tfo}`, 'tfo');
|
||||||
|
|
||||||
|
|||||||
@@ -152,9 +152,13 @@ export default function ShadowRocket_Producer() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
['trojan', 'tuic', 'hysteria', 'hysteria2'].includes(
|
[
|
||||||
proxy.type,
|
'trojan',
|
||||||
)
|
'tuic',
|
||||||
|
'hysteria',
|
||||||
|
'hysteria2',
|
||||||
|
'juicity',
|
||||||
|
].includes(proxy.type)
|
||||||
) {
|
) {
|
||||||
delete proxy.tls;
|
delete proxy.tls;
|
||||||
}
|
}
|
||||||
@@ -176,9 +180,12 @@ export default function ShadowRocket_Producer() {
|
|||||||
delete proxy.collectionName;
|
delete proxy.collectionName;
|
||||||
delete proxy.id;
|
delete proxy.id;
|
||||||
delete proxy.resolved;
|
delete proxy.resolved;
|
||||||
for (const key in proxy) {
|
delete proxy['no-resolve'];
|
||||||
if (proxy[key] == null || /^_/i.test(key)) {
|
if (type !== 'internal') {
|
||||||
delete proxy[key];
|
for (const key in proxy) {
|
||||||
|
if (proxy[key] == null || /^_/i.test(key)) {
|
||||||
|
delete proxy[key];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
@@ -186,6 +193,7 @@ export default function ShadowRocket_Producer() {
|
|||||||
proxy[`${proxy.network}-opts`]
|
proxy[`${proxy.network}-opts`]
|
||||||
) {
|
) {
|
||||||
delete proxy[`${proxy.network}-opts`]['_grpc-type'];
|
delete proxy[`${proxy.network}-opts`]['_grpc-type'];
|
||||||
|
delete proxy[`${proxy.network}-opts`]['_grpc-authority'];
|
||||||
}
|
}
|
||||||
return proxy;
|
return proxy;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import $ from '@/core/app';
|
|||||||
import { isIPv4, isIPv6 } from '@/utils';
|
import { isIPv4, isIPv6 } from '@/utils';
|
||||||
|
|
||||||
const detourParser = (proxy, parsedProxy) => {
|
const detourParser = (proxy, parsedProxy) => {
|
||||||
if (proxy['dialer-proxy']) parsedProxy.detour = proxy['dialer-proxy'];
|
parsedProxy.detour = proxy['dialer-proxy'] || proxy.detour;
|
||||||
};
|
};
|
||||||
const tfoParser = (proxy, parsedProxy) => {
|
const tfoParser = (proxy, parsedProxy) => {
|
||||||
parsedProxy.tcp_fast_open = false;
|
parsedProxy.tcp_fast_open = false;
|
||||||
@@ -202,13 +202,8 @@ const tlsParser = (proxy, parsedProxy) => {
|
|||||||
parsedProxy.tls.alpn = [proxy.alpn];
|
parsedProxy.tls.alpn = [proxy.alpn];
|
||||||
} else if (Array.isArray(proxy.alpn)) parsedProxy.tls.alpn = proxy.alpn;
|
} else if (Array.isArray(proxy.alpn)) parsedProxy.tls.alpn = proxy.alpn;
|
||||||
if (proxy.ca) parsedProxy.tls.certificate_path = `${proxy.ca}`;
|
if (proxy.ca) parsedProxy.tls.certificate_path = `${proxy.ca}`;
|
||||||
if (proxy.ca_str) parsedProxy.tls.certificate = proxy.ca_sStr;
|
if (proxy.ca_str) parsedProxy.tls.certificate = [proxy.ca_str];
|
||||||
if (proxy['ca-str']) parsedProxy.tls.certificate = proxy['ca-str'];
|
if (proxy['ca-str']) parsedProxy.tls.certificate = [proxy['ca-str']];
|
||||||
if (proxy['client-fingerprint'] && proxy['client-fingerprint'] !== '')
|
|
||||||
parsedProxy.tls.utls = {
|
|
||||||
enabled: true,
|
|
||||||
fingerprint: proxy['client-fingerprint'],
|
|
||||||
};
|
|
||||||
if (proxy['reality-opts']) {
|
if (proxy['reality-opts']) {
|
||||||
parsedProxy.tls.reality = { enabled: true };
|
parsedProxy.tls.reality = { enabled: true };
|
||||||
if (proxy['reality-opts']['public-key'])
|
if (proxy['reality-opts']['public-key'])
|
||||||
@@ -217,7 +212,13 @@ const tlsParser = (proxy, parsedProxy) => {
|
|||||||
if (proxy['reality-opts']['short-id'])
|
if (proxy['reality-opts']['short-id'])
|
||||||
parsedProxy.tls.reality.short_id =
|
parsedProxy.tls.reality.short_id =
|
||||||
proxy['reality-opts']['short-id'];
|
proxy['reality-opts']['short-id'];
|
||||||
|
parsedProxy.tls.utls = { enabled: true };
|
||||||
}
|
}
|
||||||
|
if (proxy['client-fingerprint'] && proxy['client-fingerprint'] !== '')
|
||||||
|
parsedProxy.tls.utls = {
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: proxy['client-fingerprint'],
|
||||||
|
};
|
||||||
if (!parsedProxy.tls.enabled) delete parsedProxy.tls;
|
if (!parsedProxy.tls.enabled) delete parsedProxy.tls;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ export default function Stash_Producer() {
|
|||||||
// https://stash.wiki/proxy-protocols/proxy-types#shadowsocks
|
// https://stash.wiki/proxy-protocols/proxy-types#shadowsocks
|
||||||
const list = proxies
|
const list = proxies
|
||||||
.filter((proxy) => {
|
.filter((proxy) => {
|
||||||
if (opts['include-unsupported-proxy']) return true;
|
|
||||||
if (
|
if (
|
||||||
![
|
![
|
||||||
'ss',
|
'ss',
|
||||||
@@ -21,6 +20,8 @@ export default function Stash_Producer() {
|
|||||||
'wireguard',
|
'wireguard',
|
||||||
'hysteria',
|
'hysteria',
|
||||||
'hysteria2',
|
'hysteria2',
|
||||||
|
'ssh',
|
||||||
|
'juicity',
|
||||||
].includes(proxy.type) ||
|
].includes(proxy.type) ||
|
||||||
(proxy.type === 'ss' &&
|
(proxy.type === 'ss' &&
|
||||||
![
|
![
|
||||||
@@ -38,6 +39,12 @@ export default function Stash_Producer() {
|
|||||||
'xchacha20',
|
'xchacha20',
|
||||||
'chacha20-ietf-poly1305',
|
'chacha20-ietf-poly1305',
|
||||||
'xchacha20-ietf-poly1305',
|
'xchacha20-ietf-poly1305',
|
||||||
|
...(opts['include-unsupported-proxy']
|
||||||
|
? [
|
||||||
|
'2022-blake3-aes-128-gcm',
|
||||||
|
'2022-blake3-aes-256-gcm',
|
||||||
|
]
|
||||||
|
: []),
|
||||||
].includes(proxy.cipher)) ||
|
].includes(proxy.cipher)) ||
|
||||||
(proxy.type === 'snell' && String(proxy.version) === '4') ||
|
(proxy.type === 'snell' && String(proxy.version) === '4') ||
|
||||||
(proxy.type === 'vless' && proxy['reality-opts'])
|
(proxy.type === 'vless' && proxy['reality-opts'])
|
||||||
@@ -232,14 +239,18 @@ export default function Stash_Producer() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
['trojan', 'tuic', 'hysteria', 'hysteria2'].includes(
|
[
|
||||||
proxy.type,
|
'trojan',
|
||||||
)
|
'tuic',
|
||||||
|
'hysteria',
|
||||||
|
'hysteria2',
|
||||||
|
'juicity',
|
||||||
|
].includes(proxy.type)
|
||||||
) {
|
) {
|
||||||
delete proxy.tls;
|
delete proxy.tls;
|
||||||
}
|
}
|
||||||
if (proxy['tls-fingerprint']) {
|
if (proxy['tls-fingerprint']) {
|
||||||
proxy.fingerprint = proxy['tls-fingerprint'];
|
proxy['server-cert-fingerprint'] = proxy['tls-fingerprint'];
|
||||||
}
|
}
|
||||||
delete proxy['tls-fingerprint'];
|
delete proxy['tls-fingerprint'];
|
||||||
|
|
||||||
@@ -265,9 +276,12 @@ export default function Stash_Producer() {
|
|||||||
delete proxy.collectionName;
|
delete proxy.collectionName;
|
||||||
delete proxy.id;
|
delete proxy.id;
|
||||||
delete proxy.resolved;
|
delete proxy.resolved;
|
||||||
for (const key in proxy) {
|
delete proxy['no-resolve'];
|
||||||
if (proxy[key] == null || /^_/i.test(key)) {
|
if (type !== 'internal') {
|
||||||
delete proxy[key];
|
for (const key in proxy) {
|
||||||
|
if (proxy[key] == null || /^_/i.test(key)) {
|
||||||
|
delete proxy[key];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
@@ -275,6 +289,7 @@ export default function Stash_Producer() {
|
|||||||
proxy[`${proxy.network}-opts`]
|
proxy[`${proxy.network}-opts`]
|
||||||
) {
|
) {
|
||||||
delete proxy[`${proxy.network}-opts`]['_grpc-type'];
|
delete proxy[`${proxy.network}-opts`]['_grpc-type'];
|
||||||
|
delete proxy[`${proxy.network}-opts`]['_grpc-authority'];
|
||||||
}
|
}
|
||||||
return proxy;
|
return proxy;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ const targetPlatform = 'Surfboard';
|
|||||||
|
|
||||||
export default function Surfboard_Producer() {
|
export default function Surfboard_Producer() {
|
||||||
const produce = (proxy) => {
|
const produce = (proxy) => {
|
||||||
proxy.name = proxy.name.replace(/=/g, '');
|
proxy.name = proxy.name.replace(/=|,/g, '');
|
||||||
switch (proxy.type) {
|
switch (proxy.type) {
|
||||||
case 'ss':
|
case 'ss':
|
||||||
return shadowsocks(proxy);
|
return shadowsocks(proxy);
|
||||||
|
|||||||
@@ -14,15 +14,21 @@ const ipVersions = {
|
|||||||
|
|
||||||
export default function Surge_Producer() {
|
export default function Surge_Producer() {
|
||||||
const produce = (proxy, type, opts = {}) => {
|
const produce = (proxy, type, opts = {}) => {
|
||||||
|
proxy.name = proxy.name.replace(/=|,/g, '');
|
||||||
|
if (proxy.ports) {
|
||||||
|
proxy.ports = String(proxy.ports);
|
||||||
|
}
|
||||||
switch (proxy.type) {
|
switch (proxy.type) {
|
||||||
case 'ss':
|
case 'ss':
|
||||||
return shadowsocks(proxy);
|
return shadowsocks(proxy, opts['include-unsupported-proxy']);
|
||||||
case 'trojan':
|
case 'trojan':
|
||||||
return trojan(proxy);
|
return trojan(proxy);
|
||||||
case 'vmess':
|
case 'vmess':
|
||||||
return vmess(proxy);
|
return vmess(proxy, opts['include-unsupported-proxy']);
|
||||||
case 'http':
|
case 'http':
|
||||||
return http(proxy);
|
return http(proxy);
|
||||||
|
case 'direct':
|
||||||
|
return direct(proxy);
|
||||||
case 'socks5':
|
case 'socks5':
|
||||||
return socks5(proxy);
|
return socks5(proxy);
|
||||||
case 'snell':
|
case 'snell':
|
||||||
@@ -47,7 +53,7 @@ export default function Surge_Producer() {
|
|||||||
return { produce };
|
return { produce };
|
||||||
}
|
}
|
||||||
|
|
||||||
function shadowsocks(proxy) {
|
function shadowsocks(proxy, includeUnsupportedProxy) {
|
||||||
const result = new Result(proxy);
|
const result = new Result(proxy);
|
||||||
result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`);
|
result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`);
|
||||||
if (!proxy.cipher) {
|
if (!proxy.cipher) {
|
||||||
@@ -81,12 +87,15 @@ function shadowsocks(proxy) {
|
|||||||
'chacha20',
|
'chacha20',
|
||||||
'chacha20-ietf',
|
'chacha20-ietf',
|
||||||
'none',
|
'none',
|
||||||
|
...(includeUnsupportedProxy
|
||||||
|
? ['2022-blake3-aes-128-gcm', '2022-blake3-aes-256-gcm']
|
||||||
|
: []),
|
||||||
].includes(proxy.cipher)
|
].includes(proxy.cipher)
|
||||||
) {
|
) {
|
||||||
throw new Error(`cipher ${proxy.cipher} is not supported`);
|
throw new Error(`cipher ${proxy.cipher} is not supported`);
|
||||||
}
|
}
|
||||||
result.append(`,encrypt-method=${proxy.cipher}`);
|
result.append(`,encrypt-method=${proxy.cipher}`);
|
||||||
result.appendIfPresent(`,password=${proxy.password}`, 'password');
|
result.appendIfPresent(`,password="${proxy.password}"`, 'password');
|
||||||
|
|
||||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||||
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
||||||
@@ -118,6 +127,8 @@ function shadowsocks(proxy) {
|
|||||||
|
|
||||||
// udp
|
// udp
|
||||||
result.appendIfPresent(`,udp-relay=${proxy.udp}`, 'udp');
|
result.appendIfPresent(`,udp-relay=${proxy.udp}`, 'udp');
|
||||||
|
// udp-port
|
||||||
|
result.appendIfPresent(`,udp-port=${proxy['udp-port']}`, 'udp-port');
|
||||||
|
|
||||||
// test-url
|
// test-url
|
||||||
result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url');
|
result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url');
|
||||||
@@ -184,7 +195,7 @@ function shadowsocks(proxy) {
|
|||||||
function trojan(proxy) {
|
function trojan(proxy) {
|
||||||
const result = new Result(proxy);
|
const result = new Result(proxy);
|
||||||
result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`);
|
result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`);
|
||||||
result.appendIfPresent(`,password=${proxy.password}`, 'password');
|
result.appendIfPresent(`,password="${proxy.password}"`, 'password');
|
||||||
|
|
||||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||||
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
||||||
@@ -263,7 +274,7 @@ function trojan(proxy) {
|
|||||||
return result.toString();
|
return result.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
function vmess(proxy) {
|
function vmess(proxy, includeUnsupportedProxy) {
|
||||||
const result = new Result(proxy);
|
const result = new Result(proxy);
|
||||||
result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`);
|
result.append(`${proxy.name}=${proxy.type},${proxy.server},${proxy.port}`);
|
||||||
result.appendIfPresent(`,username=${proxy.uuid}`, 'uuid');
|
result.appendIfPresent(`,username=${proxy.uuid}`, 'uuid');
|
||||||
@@ -277,7 +288,7 @@ function vmess(proxy) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// transport
|
// transport
|
||||||
handleTransport(result, proxy);
|
handleTransport(result, proxy, includeUnsupportedProxy);
|
||||||
|
|
||||||
// AEAD
|
// AEAD
|
||||||
if (isPresent(proxy, 'aead')) {
|
if (isPresent(proxy, 'aead')) {
|
||||||
@@ -357,7 +368,7 @@ function ssh(proxy) {
|
|||||||
result.append(`${proxy.name}=ssh,${proxy.server},${proxy.port}`);
|
result.append(`${proxy.name}=ssh,${proxy.server},${proxy.port}`);
|
||||||
result.appendIfPresent(`,${proxy.username}`, 'username');
|
result.appendIfPresent(`,${proxy.username}`, 'username');
|
||||||
// 所有的类似的字段都有双引号的问题 暂不处理
|
// 所有的类似的字段都有双引号的问题 暂不处理
|
||||||
result.appendIfPresent(`,${proxy.password}`, 'password');
|
result.appendIfPresent(`,"${proxy.password}"`, 'password');
|
||||||
|
|
||||||
// https://manual.nssurge.com/policy/ssh.html
|
// https://manual.nssurge.com/policy/ssh.html
|
||||||
// 需配合 Keystore
|
// 需配合 Keystore
|
||||||
@@ -422,7 +433,7 @@ function http(proxy) {
|
|||||||
const type = proxy.tls ? 'https' : 'http';
|
const type = proxy.tls ? 'https' : 'http';
|
||||||
result.append(`${proxy.name}=${type},${proxy.server},${proxy.port}`);
|
result.append(`${proxy.name}=${type},${proxy.server},${proxy.port}`);
|
||||||
result.appendIfPresent(`,${proxy.username}`, 'username');
|
result.appendIfPresent(`,${proxy.username}`, 'username');
|
||||||
result.appendIfPresent(`,${proxy.password}`, 'password');
|
result.appendIfPresent(`,"${proxy.password}"`, 'password');
|
||||||
|
|
||||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||||
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
||||||
@@ -494,13 +505,61 @@ function http(proxy) {
|
|||||||
|
|
||||||
return result.toString();
|
return result.toString();
|
||||||
}
|
}
|
||||||
|
function direct(proxy) {
|
||||||
|
const result = new Result(proxy);
|
||||||
|
const type = 'direct';
|
||||||
|
result.append(`${proxy.name}=${type}`);
|
||||||
|
|
||||||
|
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||||
|
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
||||||
|
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,no-error-alert=${proxy['no-error-alert']}`,
|
||||||
|
'no-error-alert',
|
||||||
|
);
|
||||||
|
|
||||||
|
// tfo
|
||||||
|
result.appendIfPresent(`,tfo=${proxy.tfo}`, 'tfo');
|
||||||
|
|
||||||
|
// udp
|
||||||
|
result.appendIfPresent(`,udp-relay=${proxy.udp}`, 'udp');
|
||||||
|
|
||||||
|
// test-url
|
||||||
|
result.appendIfPresent(`,test-url=${proxy['test-url']}`, 'test-url');
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,test-timeout=${proxy['test-timeout']}`,
|
||||||
|
'test-timeout',
|
||||||
|
);
|
||||||
|
result.appendIfPresent(`,test-udp=${proxy['test-udp']}`, 'test-udp');
|
||||||
|
result.appendIfPresent(`,hybrid=${proxy['hybrid']}`, 'hybrid');
|
||||||
|
result.appendIfPresent(`,tos=${proxy['tos']}`, 'tos');
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,allow-other-interface=${proxy['allow-other-interface']}`,
|
||||||
|
'allow-other-interface',
|
||||||
|
);
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,interface=${proxy['interface-name']}`,
|
||||||
|
'interface-name',
|
||||||
|
);
|
||||||
|
|
||||||
|
// block-quic
|
||||||
|
result.appendIfPresent(`,block-quic=${proxy['block-quic']}`, 'block-quic');
|
||||||
|
|
||||||
|
// underlying-proxy
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,underlying-proxy=${proxy['underlying-proxy']}`,
|
||||||
|
'underlying-proxy',
|
||||||
|
);
|
||||||
|
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
function socks5(proxy) {
|
function socks5(proxy) {
|
||||||
const result = new Result(proxy);
|
const result = new Result(proxy);
|
||||||
const type = proxy.tls ? 'socks5-tls' : 'socks5';
|
const type = proxy.tls ? 'socks5-tls' : 'socks5';
|
||||||
result.append(`${proxy.name}=${type},${proxy.server},${proxy.port}`);
|
result.append(`${proxy.name}=${type},${proxy.server},${proxy.port}`);
|
||||||
result.appendIfPresent(`,${proxy.username}`, 'username');
|
result.appendIfPresent(`,${proxy.username}`, 'username');
|
||||||
result.appendIfPresent(`,${proxy.password}`, 'password');
|
result.appendIfPresent(`,"${proxy.password}"`, 'password');
|
||||||
|
|
||||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||||
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
||||||
@@ -666,7 +725,7 @@ function tuic(proxy) {
|
|||||||
result.append(`${proxy.name}=${type},${proxy.server},${proxy.port}`);
|
result.append(`${proxy.name}=${type},${proxy.server},${proxy.port}`);
|
||||||
|
|
||||||
result.appendIfPresent(`,uuid=${proxy.uuid}`, 'uuid');
|
result.appendIfPresent(`,uuid=${proxy.uuid}`, 'uuid');
|
||||||
result.appendIfPresent(`,password=${proxy.password}`, 'password');
|
result.appendIfPresent(`,password="${proxy.password}"`, 'password');
|
||||||
result.appendIfPresent(`,token=${proxy.token}`, 'token');
|
result.appendIfPresent(`,token=${proxy.token}`, 'token');
|
||||||
|
|
||||||
result.appendIfPresent(
|
result.appendIfPresent(
|
||||||
@@ -674,6 +733,15 @@ function tuic(proxy) {
|
|||||||
'alpn',
|
'alpn',
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (isPresent(proxy, 'ports')) {
|
||||||
|
result.append(`,port-hopping="${proxy.ports.replace(/,/g, ';')}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,port-hopping-interval=${proxy['hop-interval']}`,
|
||||||
|
'hop-interval',
|
||||||
|
);
|
||||||
|
|
||||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||||
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
||||||
|
|
||||||
@@ -932,7 +1000,16 @@ function hysteria2(proxy) {
|
|||||||
const result = new Result(proxy);
|
const result = new Result(proxy);
|
||||||
result.append(`${proxy.name}=hysteria2,${proxy.server},${proxy.port}`);
|
result.append(`${proxy.name}=hysteria2,${proxy.server},${proxy.port}`);
|
||||||
|
|
||||||
result.appendIfPresent(`,password=${proxy.password}`, 'password');
|
result.appendIfPresent(`,password="${proxy.password}"`, 'password');
|
||||||
|
|
||||||
|
if (isPresent(proxy, 'ports')) {
|
||||||
|
result.append(`,port-hopping="${proxy.ports.replace(/,/g, ';')}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
result.appendIfPresent(
|
||||||
|
`,port-hopping-interval=${proxy['hop-interval']}`,
|
||||||
|
'hop-interval',
|
||||||
|
);
|
||||||
|
|
||||||
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
const ip_version = ipVersions[proxy['ip-version']] || proxy['ip-version'];
|
||||||
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
result.appendIfPresent(`,ip-version=${ip_version}`, 'ip-version');
|
||||||
@@ -1012,7 +1089,7 @@ function hysteria2(proxy) {
|
|||||||
return result.toString();
|
return result.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleTransport(result, proxy) {
|
function handleTransport(result, proxy, includeUnsupportedProxy) {
|
||||||
if (isPresent(proxy, 'network')) {
|
if (isPresent(proxy, 'network')) {
|
||||||
if (proxy.network === 'ws') {
|
if (proxy.network === 'ws') {
|
||||||
result.append(`,ws=true`);
|
result.append(`,ws=true`);
|
||||||
@@ -1038,7 +1115,13 @@ function handleTransport(result, proxy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`network ${proxy.network} is unsupported`);
|
if (includeUnsupportedProxy && ['http'].includes(proxy.network)) {
|
||||||
|
$.info(
|
||||||
|
`Include Unsupported Proxy: nework ${proxy.network} -> tcp`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
throw new Error(`network ${proxy.network} is unsupported`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { Result } from './utils';
|
import { Base64 } from 'js-base64';
|
||||||
|
import { Result, isPresent } from './utils';
|
||||||
import Surge_Producer from './surge';
|
import Surge_Producer from './surge';
|
||||||
import { isIPv4, isIPv6, isPresent } from '@/utils';
|
import ClashMeta_Producer from './clashmeta';
|
||||||
|
import { isIPv4, isIPv6 } from '@/utils';
|
||||||
import $ from '@/core/app';
|
import $ from '@/core/app';
|
||||||
|
|
||||||
const targetPlatform = 'SurgeMac';
|
const targetPlatform = 'SurgeMac';
|
||||||
@@ -8,14 +10,28 @@ const targetPlatform = 'SurgeMac';
|
|||||||
const surge_Producer = Surge_Producer();
|
const surge_Producer = Surge_Producer();
|
||||||
|
|
||||||
export default function SurgeMac_Producer() {
|
export default function SurgeMac_Producer() {
|
||||||
const produce = (proxy) => {
|
const produce = (proxy, type, opts = {}) => {
|
||||||
switch (proxy.type) {
|
switch (proxy.type) {
|
||||||
case 'external':
|
case 'external':
|
||||||
return external(proxy);
|
return external(proxy);
|
||||||
case 'ssr':
|
// case 'ssr':
|
||||||
return shadowsocksr(proxy);
|
// return shadowsocksr(proxy);
|
||||||
default:
|
default: {
|
||||||
return surge_Producer.produce(proxy);
|
try {
|
||||||
|
return surge_Producer.produce(proxy, type, opts);
|
||||||
|
} catch (e) {
|
||||||
|
if (opts.useMihomoExternal) {
|
||||||
|
$.log(
|
||||||
|
`${proxy.name} is not supported on ${targetPlatform}, try to use Mihomo(SurgeMac - External Proxy Program) instead`,
|
||||||
|
);
|
||||||
|
return mihomo(proxy, type, opts);
|
||||||
|
} else {
|
||||||
|
throw new Error(
|
||||||
|
`Surge for macOS 可手动指定链接参数 target=SurgeMac 或在 同步配置 中指定 SurgeMac 来启用 mihomo 支援 Surge 本身不支持的协议`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
return { produce };
|
return { produce };
|
||||||
@@ -60,6 +76,7 @@ function external(proxy) {
|
|||||||
|
|
||||||
return result.toString();
|
return result.toString();
|
||||||
}
|
}
|
||||||
|
// eslint-disable-next-line no-unused-vars
|
||||||
function shadowsocksr(proxy) {
|
function shadowsocksr(proxy) {
|
||||||
const external_proxy = {
|
const external_proxy = {
|
||||||
...proxy,
|
...proxy,
|
||||||
@@ -84,6 +101,7 @@ function shadowsocksr(proxy) {
|
|||||||
for (const [key, value] of Object.entries({
|
for (const [key, value] of Object.entries({
|
||||||
cipher: '-m',
|
cipher: '-m',
|
||||||
obfs: '-o',
|
obfs: '-o',
|
||||||
|
'obfs-param': '-g',
|
||||||
password: '-k',
|
password: '-k',
|
||||||
port: '-p',
|
port: '-p',
|
||||||
protocol: '-O',
|
protocol: '-O',
|
||||||
@@ -92,12 +110,73 @@ function shadowsocksr(proxy) {
|
|||||||
'local-port': '-l',
|
'local-port': '-l',
|
||||||
'local-address': '-b',
|
'local-address': '-b',
|
||||||
})) {
|
})) {
|
||||||
external_proxy.args.push(value);
|
if (external_proxy[key] != null) {
|
||||||
external_proxy.args.push(external_proxy[key]);
|
external_proxy.args.push(value);
|
||||||
|
external_proxy.args.push(external_proxy[key]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return external(external_proxy);
|
return external(external_proxy);
|
||||||
}
|
}
|
||||||
|
// eslint-disable-next-line no-unused-vars
|
||||||
|
function mihomo(proxy, type, opts) {
|
||||||
|
const clashProxy = ClashMeta_Producer().produce([proxy], 'internal')?.[0];
|
||||||
|
if (clashProxy) {
|
||||||
|
const localPort = opts?.localPort || proxy._localPort || 65535;
|
||||||
|
const ipv6 = ['ipv4', 'v4-only'].includes(proxy['ip-version'])
|
||||||
|
? false
|
||||||
|
: true;
|
||||||
|
const external_proxy = {
|
||||||
|
name: proxy.name,
|
||||||
|
type: 'external',
|
||||||
|
exec: proxy._exec || '/usr/local/bin/mihomo',
|
||||||
|
'local-port': localPort,
|
||||||
|
args: [
|
||||||
|
'-config',
|
||||||
|
Base64.encode(
|
||||||
|
JSON.stringify({
|
||||||
|
'mixed-port': localPort,
|
||||||
|
ipv6,
|
||||||
|
mode: 'global',
|
||||||
|
dns: {
|
||||||
|
enable: true,
|
||||||
|
ipv6,
|
||||||
|
nameserver: [
|
||||||
|
'https://223.6.6.6/dns-query',
|
||||||
|
'https://120.53.53.53/dns-query',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
proxies: [
|
||||||
|
{
|
||||||
|
...clashProxy,
|
||||||
|
name: 'proxy',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'proxy-groups': [
|
||||||
|
{
|
||||||
|
name: 'GLOBAL',
|
||||||
|
type: 'select',
|
||||||
|
proxies: ['proxy'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
addresses: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
// https://manual.nssurge.com/policy/external-proxy.html
|
||||||
|
if (isIP(proxy.server)) {
|
||||||
|
external_proxy.addresses.push(proxy.server);
|
||||||
|
} else {
|
||||||
|
$.log(
|
||||||
|
`Platform ${targetPlatform}, proxy type ${proxy.type}: addresses should be an IP address, but got ${proxy.server}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
opts.localPort = localPort - 1;
|
||||||
|
return external(external_proxy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function isIP(ip) {
|
function isIP(ip) {
|
||||||
return isIPv4(ip) || isIPv6(ip);
|
return isIPv4(ip) || isIPv6(ip);
|
||||||
|
|||||||
@@ -10,12 +10,17 @@ export default function URI_Producer() {
|
|||||||
delete proxy.collectionName;
|
delete proxy.collectionName;
|
||||||
delete proxy.id;
|
delete proxy.id;
|
||||||
delete proxy.resolved;
|
delete proxy.resolved;
|
||||||
|
delete proxy['no-resolve'];
|
||||||
for (const key in proxy) {
|
for (const key in proxy) {
|
||||||
if (proxy[key] == null || /^_/i.test(key)) {
|
if (proxy[key] == null || /^_/i.test(key)) {
|
||||||
delete proxy[key];
|
delete proxy[key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (['trojan', 'tuic', 'hysteria', 'hysteria2'].includes(proxy.type)) {
|
if (
|
||||||
|
['trojan', 'tuic', 'hysteria', 'hysteria2', 'juicity'].includes(
|
||||||
|
proxy.type,
|
||||||
|
)
|
||||||
|
) {
|
||||||
delete proxy.tls;
|
delete proxy.tls;
|
||||||
}
|
}
|
||||||
if (proxy.server && isIPv6(proxy.server)) {
|
if (proxy.server && isIPv6(proxy.server)) {
|
||||||
@@ -24,9 +29,13 @@ export default function URI_Producer() {
|
|||||||
switch (proxy.type) {
|
switch (proxy.type) {
|
||||||
case 'ss':
|
case 'ss':
|
||||||
const userinfo = `${proxy.cipher}:${proxy.password}`;
|
const userinfo = `${proxy.cipher}:${proxy.password}`;
|
||||||
result = `ss://${Base64.encode(userinfo)}@${proxy.server}:${
|
result = `ss://${
|
||||||
proxy.port
|
proxy.cipher?.startsWith('2022-blake3-')
|
||||||
}/`;
|
? `${encodeURIComponent(
|
||||||
|
proxy.cipher,
|
||||||
|
)}:${encodeURIComponent(proxy.password)}`
|
||||||
|
: Base64.encode(userinfo)
|
||||||
|
}@${proxy.server}:${proxy.port}${proxy.plugin ? '/' : ''}`;
|
||||||
if (proxy.plugin) {
|
if (proxy.plugin) {
|
||||||
result += '?plugin=';
|
result += '?plugin=';
|
||||||
const opts = proxy['plugin-opts'];
|
const opts = proxy['plugin-opts'];
|
||||||
@@ -55,7 +64,9 @@ export default function URI_Producer() {
|
|||||||
result = `${result}${proxy.plugin ? '&' : '?'}uot=1`;
|
result = `${result}${proxy.plugin ? '&' : '?'}uot=1`;
|
||||||
}
|
}
|
||||||
if (proxy.tfo) {
|
if (proxy.tfo) {
|
||||||
result = `${result}${proxy.plugin ? '&' : '?'}tfo=1`;
|
result = `${result}${
|
||||||
|
proxy.plugin || proxy['udp-over-tcp'] ? '&' : '?'
|
||||||
|
}tfo=1`;
|
||||||
}
|
}
|
||||||
result += `#${encodeURIComponent(proxy.name)}`;
|
result += `#${encodeURIComponent(proxy.name)}`;
|
||||||
break;
|
break;
|
||||||
@@ -82,6 +93,11 @@ export default function URI_Producer() {
|
|||||||
if (proxy.network === 'http') {
|
if (proxy.network === 'http') {
|
||||||
net = 'tcp';
|
net = 'tcp';
|
||||||
type = 'http';
|
type = 'http';
|
||||||
|
} else if (
|
||||||
|
proxy.network === 'ws' &&
|
||||||
|
proxy['ws-opts']?.['v2ray-http-upgrade']
|
||||||
|
) {
|
||||||
|
net = 'httpupgrade';
|
||||||
}
|
}
|
||||||
result = {
|
result = {
|
||||||
v: '2',
|
v: '2',
|
||||||
@@ -90,7 +106,7 @@ export default function URI_Producer() {
|
|||||||
port: proxy.port,
|
port: proxy.port,
|
||||||
id: proxy.uuid,
|
id: proxy.uuid,
|
||||||
type,
|
type,
|
||||||
aid: 0,
|
aid: proxy.alterId || 0,
|
||||||
net,
|
net,
|
||||||
tls: proxy.tls ? 'tls' : '',
|
tls: proxy.tls ? 'tls' : '',
|
||||||
};
|
};
|
||||||
@@ -122,6 +138,8 @@ export default function URI_Producer() {
|
|||||||
result.type =
|
result.type =
|
||||||
proxy[`${proxy.network}-opts`]?.['_grpc-type'] ||
|
proxy[`${proxy.network}-opts`]?.['_grpc-type'] ||
|
||||||
'gun';
|
'gun';
|
||||||
|
result.host =
|
||||||
|
proxy[`${proxy.network}-opts`]?.['_grpc-authority'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
result = 'vmess://' + Base64.encode(JSON.stringify(result));
|
result = 'vmess://' + Base64.encode(JSON.stringify(result));
|
||||||
@@ -170,14 +188,27 @@ export default function URI_Producer() {
|
|||||||
if (proxy.flow) {
|
if (proxy.flow) {
|
||||||
flow = `&flow=${encodeURIComponent(proxy.flow)}`;
|
flow = `&flow=${encodeURIComponent(proxy.flow)}`;
|
||||||
}
|
}
|
||||||
let vlessTransport = `&type=${encodeURIComponent(
|
let vlessType = proxy.network;
|
||||||
proxy.network,
|
if (
|
||||||
)}`;
|
proxy.network === 'ws' &&
|
||||||
|
proxy['ws-opts']?.['v2ray-http-upgrade']
|
||||||
|
) {
|
||||||
|
vlessType = 'httpupgrade';
|
||||||
|
}
|
||||||
|
|
||||||
|
let vlessTransport = `&type=${encodeURIComponent(vlessType)}`;
|
||||||
if (['grpc'].includes(proxy.network)) {
|
if (['grpc'].includes(proxy.network)) {
|
||||||
// https://github.com/XTLS/Xray-core/issues/91
|
// https://github.com/XTLS/Xray-core/issues/91
|
||||||
vlessTransport += `&mode=${encodeURIComponent(
|
vlessTransport += `&mode=${encodeURIComponent(
|
||||||
proxy[`${proxy.network}-opts`]?.['_grpc-type'] || 'gun',
|
proxy[`${proxy.network}-opts`]?.['_grpc-type'] || 'gun',
|
||||||
)}`;
|
)}`;
|
||||||
|
const authority =
|
||||||
|
proxy[`${proxy.network}-opts`]?.['_grpc-authority'];
|
||||||
|
if (authority) {
|
||||||
|
vlessTransport += `&authority=${encodeURIComponent(
|
||||||
|
authority,
|
||||||
|
)}`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let vlessTransportServiceName =
|
let vlessTransportServiceName =
|
||||||
@@ -206,6 +237,18 @@ export default function URI_Producer() {
|
|||||||
vlessTransportServiceName,
|
vlessTransportServiceName,
|
||||||
)}`;
|
)}`;
|
||||||
}
|
}
|
||||||
|
if (proxy.network === 'kcp') {
|
||||||
|
if (proxy.seed) {
|
||||||
|
vlessTransport += `&seed=${encodeURIComponent(
|
||||||
|
proxy.seed,
|
||||||
|
)}`;
|
||||||
|
}
|
||||||
|
if (proxy.headerType) {
|
||||||
|
vlessTransport += `&headerType=${encodeURIComponent(
|
||||||
|
proxy.headerType,
|
||||||
|
)}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
result = `vless://${proxy.uuid}@${proxy.server}:${
|
result = `vless://${proxy.uuid}@${proxy.server}:${
|
||||||
proxy.port
|
proxy.port
|
||||||
@@ -218,17 +261,31 @@ export default function URI_Producer() {
|
|||||||
case 'trojan':
|
case 'trojan':
|
||||||
let trojanTransport = '';
|
let trojanTransport = '';
|
||||||
if (proxy.network) {
|
if (proxy.network) {
|
||||||
trojanTransport = `&type=${proxy.network}`;
|
let trojanType = proxy.network;
|
||||||
|
if (
|
||||||
|
proxy.network === 'ws' &&
|
||||||
|
proxy['ws-opts']?.['v2ray-http-upgrade']
|
||||||
|
) {
|
||||||
|
trojanType = 'httpupgrade';
|
||||||
|
}
|
||||||
|
trojanTransport = `&type=${encodeURIComponent(trojanType)}`;
|
||||||
if (['grpc'].includes(proxy.network)) {
|
if (['grpc'].includes(proxy.network)) {
|
||||||
let trojanTransportServiceName =
|
let trojanTransportServiceName =
|
||||||
proxy[`${proxy.network}-opts`]?.[
|
proxy[`${proxy.network}-opts`]?.[
|
||||||
`${proxy.network}-service-name`
|
`${proxy.network}-service-name`
|
||||||
];
|
];
|
||||||
|
let trojanTransportAuthority =
|
||||||
|
proxy[`${proxy.network}-opts`]?.['_grpc-authority'];
|
||||||
if (trojanTransportServiceName) {
|
if (trojanTransportServiceName) {
|
||||||
trojanTransport += `&serviceName=${encodeURIComponent(
|
trojanTransport += `&serviceName=${encodeURIComponent(
|
||||||
trojanTransportServiceName,
|
trojanTransportServiceName,
|
||||||
)}`;
|
)}`;
|
||||||
}
|
}
|
||||||
|
if (trojanTransportAuthority) {
|
||||||
|
trojanTransport += `&authority=${encodeURIComponent(
|
||||||
|
trojanTransportAuthority,
|
||||||
|
)}`;
|
||||||
|
}
|
||||||
trojanTransport += `&mode=${encodeURIComponent(
|
trojanTransport += `&mode=${encodeURIComponent(
|
||||||
proxy[`${proxy.network}-opts`]?.['_grpc-type'] ||
|
proxy[`${proxy.network}-opts`]?.['_grpc-type'] ||
|
||||||
'gun',
|
'gun',
|
||||||
@@ -253,11 +310,27 @@ export default function URI_Producer() {
|
|||||||
)}`;
|
)}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let trojanFp = '';
|
||||||
|
if (proxy['client-fingerprint']) {
|
||||||
|
trojanFp = `&fp=${encodeURIComponent(
|
||||||
|
proxy['client-fingerprint'],
|
||||||
|
)}`;
|
||||||
|
}
|
||||||
|
let trojanAlpn = '';
|
||||||
|
if (proxy.alpn) {
|
||||||
|
trojanAlpn = `&alpn=${encodeURIComponent(
|
||||||
|
Array.isArray(proxy.alpn)
|
||||||
|
? proxy.alpn
|
||||||
|
: proxy.alpn.join(','),
|
||||||
|
)}`;
|
||||||
|
}
|
||||||
result = `trojan://${proxy.password}@${proxy.server}:${
|
result = `trojan://${proxy.password}@${proxy.server}:${
|
||||||
proxy.port
|
proxy.port
|
||||||
}?sni=${encodeURIComponent(proxy.sni || proxy.server)}${
|
}?sni=${encodeURIComponent(proxy.sni || proxy.server)}${
|
||||||
proxy['skip-cert-verify'] ? '&allowInsecure=1' : ''
|
proxy['skip-cert-verify'] ? '&allowInsecure=1' : ''
|
||||||
}${trojanTransport}#${encodeURIComponent(proxy.name)}`;
|
}${trojanTransport}${trojanAlpn}${trojanFp}#${encodeURIComponent(
|
||||||
|
proxy.name,
|
||||||
|
)}`;
|
||||||
break;
|
break;
|
||||||
case 'hysteria2':
|
case 'hysteria2':
|
||||||
let hysteria2params = [];
|
let hysteria2params = [];
|
||||||
|
|||||||
@@ -1,12 +1,30 @@
|
|||||||
/* eslint-disable no-case-declarations */
|
/* eslint-disable no-case-declarations */
|
||||||
import { Base64 } from 'js-base64';
|
import { Base64 } from 'js-base64';
|
||||||
import URI_Producer from './uri';
|
import URI_Producer from './uri';
|
||||||
|
import $ from '@/core/app';
|
||||||
|
|
||||||
const URI = URI_Producer();
|
const URI = URI_Producer();
|
||||||
|
|
||||||
export default function V2Ray_Producer() {
|
export default function V2Ray_Producer() {
|
||||||
const type = 'ALL';
|
const type = 'ALL';
|
||||||
const produce = (proxies) =>
|
const produce = (proxies) => {
|
||||||
Base64.encode(proxies.map((proxy) => URI.produce(proxy)).join('\n'));
|
let result = [];
|
||||||
|
proxies.map((proxy) => {
|
||||||
|
try {
|
||||||
|
result.push(URI.produce(proxy));
|
||||||
|
} catch (err) {
|
||||||
|
$.error(
|
||||||
|
`Cannot produce proxy: ${JSON.stringify(
|
||||||
|
proxy,
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
)}\nReason: ${err}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return Base64.encode(result.join('\n'));
|
||||||
|
};
|
||||||
|
|
||||||
return { type, produce };
|
return { type, produce };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,17 +11,65 @@ import { syncToGist } from '@/restful/artifacts';
|
|||||||
import { findByName } from '@/utils/database';
|
import { findByName } from '@/utils/database';
|
||||||
|
|
||||||
!(async function () {
|
!(async function () {
|
||||||
const settings = $.read(SETTINGS_KEY);
|
let arg;
|
||||||
// if GitHub token is not configured
|
if (typeof $argument != 'undefined') {
|
||||||
if (!settings.githubUser || !settings.gistToken) return;
|
arg = Object.fromEntries(
|
||||||
|
// eslint-disable-next-line no-undef
|
||||||
|
$argument.split('&').map((item) => item.split('=')),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
arg = {};
|
||||||
|
}
|
||||||
|
let sub_names = (arg?.subscription ?? arg?.sub ?? '')
|
||||||
|
.split(/,|,/g)
|
||||||
|
.map((i) => i.trim())
|
||||||
|
.filter((i) => i.length > 0)
|
||||||
|
.map((i) => decodeURIComponent(i));
|
||||||
|
let col_names = (arg?.collection ?? arg?.col ?? '')
|
||||||
|
.split(/,|,/g)
|
||||||
|
.map((i) => i.trim())
|
||||||
|
.filter((i) => i.length > 0)
|
||||||
|
.map((i) => decodeURIComponent(i));
|
||||||
|
if (sub_names.length > 0 || col_names.length > 0) {
|
||||||
|
if (sub_names.length > 0)
|
||||||
|
await produceArtifacts(sub_names, 'subscription');
|
||||||
|
if (col_names.length > 0)
|
||||||
|
await produceArtifacts(col_names, 'collection');
|
||||||
|
} else {
|
||||||
|
const settings = $.read(SETTINGS_KEY);
|
||||||
|
// if GitHub token is not configured
|
||||||
|
if (!settings.githubUser || !settings.gistToken) return;
|
||||||
|
|
||||||
const artifacts = $.read(ARTIFACTS_KEY);
|
const artifacts = $.read(ARTIFACTS_KEY);
|
||||||
if (!artifacts || artifacts.length === 0) return;
|
if (!artifacts || artifacts.length === 0) return;
|
||||||
|
|
||||||
const shouldSync = artifacts.some((artifact) => artifact.sync);
|
const shouldSync = artifacts.some((artifact) => artifact.sync);
|
||||||
if (shouldSync) await doSync();
|
if (shouldSync) await doSync();
|
||||||
|
}
|
||||||
})().finally(() => $.done());
|
})().finally(() => $.done());
|
||||||
|
|
||||||
|
async function produceArtifacts(names, type) {
|
||||||
|
try {
|
||||||
|
if (names.length > 0) {
|
||||||
|
$.info(`produceArtifacts ${type} 开始: ${names.join(', ')}`);
|
||||||
|
await Promise.all(
|
||||||
|
names.map(async (name) => {
|
||||||
|
try {
|
||||||
|
await produceArtifact({
|
||||||
|
type,
|
||||||
|
name,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
$.error(`${type} ${name} error: ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
$.info(`produceArtifacts ${type} 完成: ${names.join(', ')}`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
$.error(`produceArtifacts error: ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
async function doSync() {
|
async function doSync() {
|
||||||
console.log(
|
console.log(
|
||||||
`
|
`
|
||||||
@@ -69,6 +117,7 @@ async function doSync() {
|
|||||||
await produceArtifact({
|
await produceArtifact({
|
||||||
type: 'subscription',
|
type: 'subscription',
|
||||||
name: subName,
|
name: subName,
|
||||||
|
awaitCustomCache: true,
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// $.error(`${e.message ?? e}`);
|
// $.error(`${e.message ?? e}`);
|
||||||
@@ -81,6 +130,15 @@ async function doSync() {
|
|||||||
try {
|
try {
|
||||||
if (artifact.sync && artifact.source) {
|
if (artifact.sync && artifact.source) {
|
||||||
$.info(`正在同步云配置:${artifact.name}...`);
|
$.info(`正在同步云配置:${artifact.name}...`);
|
||||||
|
|
||||||
|
const useMihomoExternal =
|
||||||
|
artifact.platform === 'SurgeMac';
|
||||||
|
|
||||||
|
if (useMihomoExternal) {
|
||||||
|
$.info(
|
||||||
|
`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`,
|
||||||
|
);
|
||||||
|
}
|
||||||
const output = await produceArtifact({
|
const output = await produceArtifact({
|
||||||
type: artifact.type,
|
type: artifact.type,
|
||||||
name: artifact.source,
|
name: artifact.source,
|
||||||
@@ -88,6 +146,7 @@ async function doSync() {
|
|||||||
produceOpts: {
|
produceOpts: {
|
||||||
'include-unsupported-proxy':
|
'include-unsupported-proxy':
|
||||||
artifact.includeUnsupportedProxy,
|
artifact.includeUnsupportedProxy,
|
||||||
|
useMihomoExternal,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -37,7 +37,9 @@ let resourceUrl = typeof $resourceUrl !== 'undefined' ? $resourceUrl : '';
|
|||||||
if (resourceType === RESOURCE_TYPE.PROXY) {
|
if (resourceType === RESOURCE_TYPE.PROXY) {
|
||||||
try {
|
try {
|
||||||
let proxies = ProxyUtils.parse(resource);
|
let proxies = ProxyUtils.parse(resource);
|
||||||
result = ProxyUtils.produce(proxies, 'Loon');
|
result = ProxyUtils.produce(proxies, 'Loon', undefined, {
|
||||||
|
'include-unsupported-proxy': arg?.includeUnsupportedProxy,
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log('解析器: 使用 resource 出现错误');
|
console.log('解析器: 使用 resource 出现错误');
|
||||||
console.log(e.message ?? e);
|
console.log(e.message ?? e);
|
||||||
@@ -47,7 +49,9 @@ let resourceUrl = typeof $resourceUrl !== 'undefined' ? $resourceUrl : '';
|
|||||||
try {
|
try {
|
||||||
let raw = await download(resourceUrl, arg?.ua, arg?.timeout);
|
let raw = await download(resourceUrl, arg?.ua, arg?.timeout);
|
||||||
let proxies = ProxyUtils.parse(raw);
|
let proxies = ProxyUtils.parse(raw);
|
||||||
result = ProxyUtils.produce(proxies, 'Loon');
|
result = ProxyUtils.produce(proxies, 'Loon', undefined, {
|
||||||
|
'include-unsupported-proxy': arg?.includeUnsupportedProxy,
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log(e.message ?? e);
|
console.log(e.message ?? e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import registerSettingRoutes from '@/restful/settings';
|
|||||||
import registerMiscRoutes from '@/restful/miscs';
|
import registerMiscRoutes from '@/restful/miscs';
|
||||||
import registerSortRoutes from '@/restful/sort';
|
import registerSortRoutes from '@/restful/sort';
|
||||||
import registerFileRoutes from '@/restful/file';
|
import registerFileRoutes from '@/restful/file';
|
||||||
|
import registerTokenRoutes from '@/restful/token';
|
||||||
import registerModuleRoutes from '@/restful/module';
|
import registerModuleRoutes from '@/restful/module';
|
||||||
|
|
||||||
migrate();
|
migrate();
|
||||||
@@ -32,6 +33,7 @@ function serve() {
|
|||||||
// register routes
|
// register routes
|
||||||
registerCollectionRoutes($app);
|
registerCollectionRoutes($app);
|
||||||
registerSubscriptionRoutes($app);
|
registerSubscriptionRoutes($app);
|
||||||
|
registerTokenRoutes($app);
|
||||||
registerFileRoutes($app);
|
registerFileRoutes($app);
|
||||||
registerModuleRoutes($app);
|
registerModuleRoutes($app);
|
||||||
registerArtifactRoutes($app);
|
registerArtifactRoutes($app);
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ import { getISO } from '@/utils/geo';
|
|||||||
import env from '@/utils/env';
|
import env from '@/utils/env';
|
||||||
|
|
||||||
export default function register($app) {
|
export default function register($app) {
|
||||||
|
$app.get('/share/col/:name', downloadCollection);
|
||||||
|
$app.get('/share/sub/:name', downloadSubscription);
|
||||||
|
|
||||||
$app.get('/download/collection/:name', downloadCollection);
|
$app.get('/download/collection/:name', downloadCollection);
|
||||||
$app.get('/download/:name', downloadSubscription);
|
$app.get('/download/:name', downloadSubscription);
|
||||||
$app.get(
|
$app.get(
|
||||||
@@ -52,10 +55,16 @@ async function downloadSubscription(req, res) {
|
|||||||
name = decodeURIComponent(name);
|
name = decodeURIComponent(name);
|
||||||
nezhaIndex = decodeURIComponent(nezhaIndex);
|
nezhaIndex = decodeURIComponent(nezhaIndex);
|
||||||
|
|
||||||
|
const useMihomoExternal = req.query.target === 'SurgeMac';
|
||||||
|
|
||||||
const platform =
|
const platform =
|
||||||
req.query.target || getPlatformFromHeaders(req.headers) || 'JSON';
|
req.query.target || getPlatformFromHeaders(req.headers) || 'JSON';
|
||||||
|
|
||||||
$.info(`正在下载订阅:${name}`);
|
$.info(
|
||||||
|
`正在下载订阅:${name}\n请求 User-Agent: ${
|
||||||
|
req.headers['user-agent'] || req.headers['User-Agent']
|
||||||
|
}`,
|
||||||
|
);
|
||||||
let {
|
let {
|
||||||
url,
|
url,
|
||||||
ua,
|
ua,
|
||||||
@@ -65,11 +74,35 @@ async function downloadSubscription(req, res) {
|
|||||||
produceType,
|
produceType,
|
||||||
includeUnsupportedProxy,
|
includeUnsupportedProxy,
|
||||||
resultFormat,
|
resultFormat,
|
||||||
|
proxy,
|
||||||
|
noCache,
|
||||||
} = req.query;
|
} = req.query;
|
||||||
|
let $options = {};
|
||||||
|
if (req.query.$options) {
|
||||||
|
try {
|
||||||
|
// 支持 `#${encodeURIComponent(JSON.stringify({arg1: "1"}))}`
|
||||||
|
$options = JSON.parse(decodeURIComponent(req.query.$options));
|
||||||
|
} catch (e) {
|
||||||
|
for (const pair of req.query.$options.split('&')) {
|
||||||
|
const key = pair.split('=')[0];
|
||||||
|
const value = pair.split('=')[1];
|
||||||
|
// 部分兼容之前的逻辑 const value = pair.split('=')[1] || true;
|
||||||
|
$options[key] =
|
||||||
|
value == null || value === ''
|
||||||
|
? true
|
||||||
|
: decodeURIComponent(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$.info(`传入 $options: ${JSON.stringify($options)}`);
|
||||||
|
}
|
||||||
if (url) {
|
if (url) {
|
||||||
url = decodeURIComponent(url);
|
url = decodeURIComponent(url);
|
||||||
$.info(`指定远程订阅 URL: ${url}`);
|
$.info(`指定远程订阅 URL: ${url}`);
|
||||||
}
|
}
|
||||||
|
if (proxy) {
|
||||||
|
proxy = decodeURIComponent(proxy);
|
||||||
|
$.info(`指定远程订阅使用代理/策略 proxy: ${proxy}`);
|
||||||
|
}
|
||||||
if (ua) {
|
if (ua) {
|
||||||
ua = decodeURIComponent(ua);
|
ua = decodeURIComponent(ua);
|
||||||
$.info(`指定远程订阅 User-Agent: ${ua}`);
|
$.info(`指定远程订阅 User-Agent: ${ua}`);
|
||||||
@@ -95,6 +128,14 @@ async function downloadSubscription(req, res) {
|
|||||||
$.info(`包含不支持的节点: ${includeUnsupportedProxy}`);
|
$.info(`包含不支持的节点: ${includeUnsupportedProxy}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (useMihomoExternal) {
|
||||||
|
$.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (noCache) {
|
||||||
|
$.info(`指定不使用缓存: ${noCache}`);
|
||||||
|
}
|
||||||
|
|
||||||
const allSubs = $.read(SUBS_KEY);
|
const allSubs = $.read(SUBS_KEY);
|
||||||
const sub = findByName(allSubs, name);
|
const sub = findByName(allSubs, name);
|
||||||
if (sub) {
|
if (sub) {
|
||||||
@@ -111,18 +152,23 @@ async function downloadSubscription(req, res) {
|
|||||||
produceType,
|
produceType,
|
||||||
produceOpts: {
|
produceOpts: {
|
||||||
'include-unsupported-proxy': includeUnsupportedProxy,
|
'include-unsupported-proxy': includeUnsupportedProxy,
|
||||||
|
useMihomoExternal,
|
||||||
},
|
},
|
||||||
|
$options,
|
||||||
|
proxy,
|
||||||
|
noCache,
|
||||||
});
|
});
|
||||||
|
let flowInfo;
|
||||||
if (
|
if (
|
||||||
sub.source !== 'local' ||
|
sub.source !== 'local' ||
|
||||||
['localFirst', 'remoteFirst'].includes(sub.mergeSources)
|
['localFirst', 'remoteFirst'].includes(sub.mergeSources)
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
url = `${url || sub.url}`
|
url =
|
||||||
.split(/[\r\n]+/)
|
`${url || sub.url}`
|
||||||
.map((i) => i.trim())
|
.split(/[\r\n]+/)
|
||||||
.filter((i) => i.length)?.[0];
|
.map((i) => i.trim())
|
||||||
|
.filter((i) => i.length)?.[0] || '';
|
||||||
|
|
||||||
let $arguments = {};
|
let $arguments = {};
|
||||||
const rawArgs = url.split('#');
|
const rawArgs = url.split('#');
|
||||||
@@ -147,11 +193,12 @@ async function downloadSubscription(req, res) {
|
|||||||
}
|
}
|
||||||
if (!$arguments.noFlow) {
|
if (!$arguments.noFlow) {
|
||||||
// forward flow headers
|
// forward flow headers
|
||||||
const flowInfo = await getFlowHeaders(
|
flowInfo = await getFlowHeaders(
|
||||||
url,
|
$arguments?.insecure ? `${url}#insecure` : url,
|
||||||
$arguments.flowUserAgent,
|
$arguments.flowUserAgent,
|
||||||
undefined,
|
undefined,
|
||||||
sub.proxy,
|
proxy || sub.proxy,
|
||||||
|
$arguments.flowUrl,
|
||||||
);
|
);
|
||||||
if (flowInfo) {
|
if (flowInfo) {
|
||||||
res.set('subscription-userinfo', flowInfo);
|
res.set('subscription-userinfo', flowInfo);
|
||||||
@@ -166,7 +213,30 @@ async function downloadSubscription(req, res) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (sub.subUserinfo) {
|
if (sub.subUserinfo) {
|
||||||
res.set('subscription-userinfo', sub.subUserinfo);
|
let subUserInfo;
|
||||||
|
if (/^https?:\/\//.test(sub.subUserinfo)) {
|
||||||
|
try {
|
||||||
|
subUserInfo = await getFlowHeaders(
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
proxy || sub.proxy,
|
||||||
|
sub.subUserinfo,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`订阅 ${name} 使用自定义流量链接 ${
|
||||||
|
sub.subUserinfo
|
||||||
|
} 获取流量信息时发生错误: ${JSON.stringify(e)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
subUserInfo = sub.subUserinfo;
|
||||||
|
}
|
||||||
|
res.set(
|
||||||
|
'subscription-userinfo',
|
||||||
|
[subUserInfo, flowInfo].filter((i) => i).join('; '),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (platform === 'JSON') {
|
if (platform === 'JSON') {
|
||||||
@@ -205,7 +275,7 @@ async function downloadSubscription(req, res) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
$.notify(`🌍 Sub-Store 下载订阅失败`, `❌ 未找到订阅:${name}!`);
|
$.error(`🌍 Sub-Store 下载订阅失败\n❌ 未找到订阅:${name}!`);
|
||||||
failed(
|
failed(
|
||||||
res,
|
res,
|
||||||
new ResourceNotFoundError(
|
new ResourceNotFoundError(
|
||||||
@@ -222,21 +292,53 @@ async function downloadCollection(req, res) {
|
|||||||
name = decodeURIComponent(name);
|
name = decodeURIComponent(name);
|
||||||
nezhaIndex = decodeURIComponent(nezhaIndex);
|
nezhaIndex = decodeURIComponent(nezhaIndex);
|
||||||
|
|
||||||
|
const useMihomoExternal = req.query.target === 'SurgeMac';
|
||||||
|
|
||||||
const platform =
|
const platform =
|
||||||
req.query.target || getPlatformFromHeaders(req.headers) || 'JSON';
|
req.query.target || getPlatformFromHeaders(req.headers) || 'JSON';
|
||||||
|
|
||||||
const allCols = $.read(COLLECTIONS_KEY);
|
const allCols = $.read(COLLECTIONS_KEY);
|
||||||
const collection = findByName(allCols, name);
|
const collection = findByName(allCols, name);
|
||||||
|
|
||||||
$.info(`正在下载组合订阅:${name}`);
|
$.info(
|
||||||
|
`正在下载组合订阅:${name}\n请求 User-Agent: ${
|
||||||
|
req.headers['user-agent'] || req.headers['User-Agent']
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
|
||||||
let {
|
let {
|
||||||
ignoreFailedRemoteSub,
|
ignoreFailedRemoteSub,
|
||||||
produceType,
|
produceType,
|
||||||
includeUnsupportedProxy,
|
includeUnsupportedProxy,
|
||||||
resultFormat,
|
resultFormat,
|
||||||
|
proxy,
|
||||||
|
noCache,
|
||||||
} = req.query;
|
} = req.query;
|
||||||
|
|
||||||
|
let $options = {};
|
||||||
|
if (req.query.$options) {
|
||||||
|
try {
|
||||||
|
// 支持 `#${encodeURIComponent(JSON.stringify({arg1: "1"}))}`
|
||||||
|
$options = JSON.parse(decodeURIComponent(req.query.$options));
|
||||||
|
} catch (e) {
|
||||||
|
for (const pair of req.query.$options.split('&')) {
|
||||||
|
const key = pair.split('=')[0];
|
||||||
|
const value = pair.split('=')[1];
|
||||||
|
// 部分兼容之前的逻辑 const value = pair.split('=')[1] || true;
|
||||||
|
$options[key] =
|
||||||
|
value == null || value === ''
|
||||||
|
? true
|
||||||
|
: decodeURIComponent(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$.info(`传入 $options: ${JSON.stringify($options)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (proxy) {
|
||||||
|
proxy = decodeURIComponent(proxy);
|
||||||
|
$.info(`指定远程订阅使用代理/策略 proxy: ${proxy}`);
|
||||||
|
}
|
||||||
|
|
||||||
if (ignoreFailedRemoteSub != null && ignoreFailedRemoteSub !== '') {
|
if (ignoreFailedRemoteSub != null && ignoreFailedRemoteSub !== '') {
|
||||||
ignoreFailedRemoteSub = decodeURIComponent(ignoreFailedRemoteSub);
|
ignoreFailedRemoteSub = decodeURIComponent(ignoreFailedRemoteSub);
|
||||||
$.info(`指定忽略失败的远程订阅: ${ignoreFailedRemoteSub}`);
|
$.info(`指定忽略失败的远程订阅: ${ignoreFailedRemoteSub}`);
|
||||||
@@ -250,6 +352,12 @@ async function downloadCollection(req, res) {
|
|||||||
includeUnsupportedProxy = decodeURIComponent(includeUnsupportedProxy);
|
includeUnsupportedProxy = decodeURIComponent(includeUnsupportedProxy);
|
||||||
$.info(`包含不支持的节点: ${includeUnsupportedProxy}`);
|
$.info(`包含不支持的节点: ${includeUnsupportedProxy}`);
|
||||||
}
|
}
|
||||||
|
if (useMihomoExternal) {
|
||||||
|
$.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`);
|
||||||
|
}
|
||||||
|
if (noCache) {
|
||||||
|
$.info(`指定不使用缓存: ${noCache}`);
|
||||||
|
}
|
||||||
|
|
||||||
if (collection) {
|
if (collection) {
|
||||||
try {
|
try {
|
||||||
@@ -261,7 +369,11 @@ async function downloadCollection(req, res) {
|
|||||||
produceType,
|
produceType,
|
||||||
produceOpts: {
|
produceOpts: {
|
||||||
'include-unsupported-proxy': includeUnsupportedProxy,
|
'include-unsupported-proxy': includeUnsupportedProxy,
|
||||||
|
useMihomoExternal,
|
||||||
},
|
},
|
||||||
|
$options,
|
||||||
|
proxy,
|
||||||
|
noCache,
|
||||||
});
|
});
|
||||||
|
|
||||||
// forward flow header from the first subscription in this collection
|
// forward flow header from the first subscription in this collection
|
||||||
@@ -269,15 +381,17 @@ async function downloadCollection(req, res) {
|
|||||||
const subnames = collection.subscriptions;
|
const subnames = collection.subscriptions;
|
||||||
if (subnames.length > 0) {
|
if (subnames.length > 0) {
|
||||||
const sub = findByName(allSubs, subnames[0]);
|
const sub = findByName(allSubs, subnames[0]);
|
||||||
|
let flowInfo;
|
||||||
if (
|
if (
|
||||||
sub.source !== 'local' ||
|
sub.source !== 'local' ||
|
||||||
['localFirst', 'remoteFirst'].includes(sub.mergeSources)
|
['localFirst', 'remoteFirst'].includes(sub.mergeSources)
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
let url = `${sub.url}`
|
let url =
|
||||||
.split(/[\r\n]+/)
|
`${sub.url}`
|
||||||
.map((i) => i.trim())
|
.split(/[\r\n]+/)
|
||||||
.filter((i) => i.length)?.[0];
|
.map((i) => i.trim())
|
||||||
|
.filter((i) => i.length)?.[0] || '';
|
||||||
|
|
||||||
let $arguments = {};
|
let $arguments = {};
|
||||||
const rawArgs = url.split('#');
|
const rawArgs = url.split('#');
|
||||||
@@ -301,11 +415,12 @@ async function downloadCollection(req, res) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!$arguments.noFlow) {
|
if (!$arguments.noFlow) {
|
||||||
const flowInfo = await getFlowHeaders(
|
flowInfo = await getFlowHeaders(
|
||||||
url,
|
$arguments?.insecure ? `${url}#insecure` : url,
|
||||||
$arguments.flowUserAgent,
|
$arguments.flowUserAgent,
|
||||||
undefined,
|
undefined,
|
||||||
sub.proxy,
|
proxy || sub.proxy || collection.proxy,
|
||||||
|
$arguments.flowUrl,
|
||||||
);
|
);
|
||||||
if (flowInfo) {
|
if (flowInfo) {
|
||||||
res.set('subscription-userinfo', flowInfo);
|
res.set('subscription-userinfo', flowInfo);
|
||||||
@@ -320,7 +435,30 @@ async function downloadCollection(req, res) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (sub.subUserinfo) {
|
if (sub.subUserinfo) {
|
||||||
res.set('subscription-userinfo', sub.subUserinfo);
|
let subUserInfo;
|
||||||
|
if (/^https?:\/\//.test(sub.subUserinfo)) {
|
||||||
|
try {
|
||||||
|
subUserInfo = await getFlowHeaders(
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
proxy || sub.proxy,
|
||||||
|
sub.subUserinfo,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`组合订阅 ${name} 使用自定义流量链接 ${
|
||||||
|
sub.subUserinfo
|
||||||
|
} 获取流量信息时发生错误: ${JSON.stringify(e)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
subUserInfo = sub.subUserinfo;
|
||||||
|
}
|
||||||
|
res.set(
|
||||||
|
'subscription-userinfo',
|
||||||
|
[subUserInfo, flowInfo].filter((i) => i).join('; '),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -359,7 +497,7 @@ async function downloadCollection(req, res) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
$.notify(
|
$.error(
|
||||||
`🌍 Sub-Store 下载组合订阅失败`,
|
`🌍 Sub-Store 下载组合订阅失败`,
|
||||||
`❌ 未找到组合订阅:${name}!`,
|
`❌ 未找到组合订阅:${name}!`,
|
||||||
);
|
);
|
||||||
@@ -469,7 +607,11 @@ function nezhaTransform(output) {
|
|||||||
// 简单判断下
|
// 简单判断下
|
||||||
if (/^[a-z]{2}$/i.test(CountryCode)) {
|
if (/^[a-z]{2}$/i.test(CountryCode)) {
|
||||||
// 如果节点上有数据 就取节点上的数据
|
// 如果节点上有数据 就取节点上的数据
|
||||||
let time = proxy._unavailable ? 0 : Date.now();
|
let now = Math.round(new Date().getTime() / 1000);
|
||||||
|
let time = proxy._unavailable ? 0 : now;
|
||||||
|
|
||||||
|
const uptime = parseInt(proxy._uptime || 0, 10);
|
||||||
|
|
||||||
result.result.push({
|
result.result.push({
|
||||||
id: index,
|
id: index,
|
||||||
name: proxy.name,
|
name: proxy.name,
|
||||||
@@ -489,7 +631,7 @@ function nezhaTransform(output) {
|
|||||||
SwapTotal: 1024,
|
SwapTotal: 1024,
|
||||||
Arch: '',
|
Arch: '',
|
||||||
Virtualization: '',
|
Virtualization: '',
|
||||||
BootTime: time,
|
BootTime: now - uptime,
|
||||||
CountryCode, // 目前需要
|
CountryCode, // 目前需要
|
||||||
Version: '0.0.1',
|
Version: '0.0.1',
|
||||||
},
|
},
|
||||||
@@ -502,7 +644,7 @@ function nezhaTransform(output) {
|
|||||||
NetOutTransfer: 0,
|
NetOutTransfer: 0,
|
||||||
NetInSpeed: 0,
|
NetInSpeed: 0,
|
||||||
NetOutSpeed: 0,
|
NetOutSpeed: 0,
|
||||||
Uptime: parseInt(proxy._uptime ?? index, 10),
|
Uptime: uptime,
|
||||||
Load1: 0,
|
Load1: 0,
|
||||||
Load5: 0,
|
Load5: 0,
|
||||||
Load15: 0,
|
Load15: 0,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { deleteByName, findByName, updateByName } from '@/utils/database';
|
import { deleteByName, findByName, updateByName } from '@/utils/database';
|
||||||
|
import { getFlowHeaders } from '@/utils/flow';
|
||||||
import { FILES_KEY } from '@/constants';
|
import { FILES_KEY } from '@/constants';
|
||||||
import { failed, success } from '@/restful/response';
|
import { failed, success } from '@/restful/response';
|
||||||
import $ from '@/core/app';
|
import $ from '@/core/app';
|
||||||
@@ -12,6 +13,8 @@ import { produceArtifact } from '@/restful/sync';
|
|||||||
export default function register($app) {
|
export default function register($app) {
|
||||||
if (!$.read(FILES_KEY)) $.write([], FILES_KEY);
|
if (!$.read(FILES_KEY)) $.write([], FILES_KEY);
|
||||||
|
|
||||||
|
$app.get('/share/file/:name', getFile);
|
||||||
|
|
||||||
$app.route('/api/file/:name')
|
$app.route('/api/file/:name')
|
||||||
.get(getFile)
|
.get(getFile)
|
||||||
.patch(updateFile)
|
.patch(updateFile)
|
||||||
@@ -50,15 +53,54 @@ async function getFile(req, res) {
|
|||||||
name = decodeURIComponent(name);
|
name = decodeURIComponent(name);
|
||||||
|
|
||||||
$.info(`正在下载文件:${name}`);
|
$.info(`正在下载文件:${name}`);
|
||||||
let { url, ua, content, mergeSources, ignoreFailedRemoteFile } = req.query;
|
let {
|
||||||
|
url,
|
||||||
|
subInfoUrl,
|
||||||
|
subInfoUserAgent,
|
||||||
|
ua,
|
||||||
|
content,
|
||||||
|
mergeSources,
|
||||||
|
ignoreFailedRemoteFile,
|
||||||
|
proxy,
|
||||||
|
} = req.query;
|
||||||
|
let $options = {};
|
||||||
|
if (req.query.$options) {
|
||||||
|
try {
|
||||||
|
// 支持 `#${encodeURIComponent(JSON.stringify({arg1: "1"}))}`
|
||||||
|
$options = JSON.parse(decodeURIComponent(req.query.$options));
|
||||||
|
} catch (e) {
|
||||||
|
for (const pair of req.query.$options.split('&')) {
|
||||||
|
const key = pair.split('=')[0];
|
||||||
|
const value = pair.split('=')[1];
|
||||||
|
// 部分兼容之前的逻辑 const value = pair.split('=')[1] || true;
|
||||||
|
$options[key] =
|
||||||
|
value == null || value === ''
|
||||||
|
? true
|
||||||
|
: decodeURIComponent(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$.info(`传入 $options: ${JSON.stringify($options)}`);
|
||||||
|
}
|
||||||
if (url) {
|
if (url) {
|
||||||
url = decodeURIComponent(url);
|
url = decodeURIComponent(url);
|
||||||
$.info(`指定远程文件 URL: ${url}`);
|
$.info(`指定远程文件 URL: ${url}`);
|
||||||
}
|
}
|
||||||
|
if (proxy) {
|
||||||
|
proxy = decodeURIComponent(proxy);
|
||||||
|
$.info(`指定远程订阅使用代理/策略 proxy: ${proxy}`);
|
||||||
|
}
|
||||||
if (ua) {
|
if (ua) {
|
||||||
ua = decodeURIComponent(ua);
|
ua = decodeURIComponent(ua);
|
||||||
$.info(`指定远程文件 User-Agent: ${ua}`);
|
$.info(`指定远程文件 User-Agent: ${ua}`);
|
||||||
}
|
}
|
||||||
|
if (subInfoUrl) {
|
||||||
|
subInfoUrl = decodeURIComponent(subInfoUrl);
|
||||||
|
$.info(`指定获取流量的 subInfoUrl: ${subInfoUrl}`);
|
||||||
|
}
|
||||||
|
if (subInfoUserAgent) {
|
||||||
|
subInfoUserAgent = decodeURIComponent(subInfoUserAgent);
|
||||||
|
$.info(`指定获取流量的 subInfoUserAgent: ${subInfoUserAgent}`);
|
||||||
|
}
|
||||||
if (content) {
|
if (content) {
|
||||||
content = decodeURIComponent(content);
|
content = decodeURIComponent(content);
|
||||||
$.info(`指定本地文件: ${content}`);
|
$.info(`指定本地文件: ${content}`);
|
||||||
@@ -84,8 +126,39 @@ async function getFile(req, res) {
|
|||||||
content,
|
content,
|
||||||
mergeSources,
|
mergeSources,
|
||||||
ignoreFailedRemoteFile,
|
ignoreFailedRemoteFile,
|
||||||
|
$options,
|
||||||
|
proxy,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
subInfoUrl = subInfoUrl || file.subInfoUrl;
|
||||||
|
if (subInfoUrl) {
|
||||||
|
// forward flow headers
|
||||||
|
const flowInfo = await getFlowHeaders(
|
||||||
|
subInfoUrl,
|
||||||
|
subInfoUserAgent || file.subInfoUserAgent,
|
||||||
|
undefined,
|
||||||
|
proxy || file.proxy,
|
||||||
|
);
|
||||||
|
if (flowInfo) {
|
||||||
|
res.set('subscription-userinfo', flowInfo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
$.error(
|
||||||
|
`文件 ${name} 获取流量信息时发生错误: ${JSON.stringify(
|
||||||
|
err,
|
||||||
|
)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (file.download) {
|
||||||
|
res.set(
|
||||||
|
'Content-Disposition',
|
||||||
|
`attachment; filename*=UTF-8''${encodeURIComponent(
|
||||||
|
file.displayName || file.name,
|
||||||
|
)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
res.set('Content-Type', 'text/plain; charset=utf-8').send(
|
res.set('Content-Type', 'text/plain; charset=utf-8').send(
|
||||||
output ?? '',
|
output ?? '',
|
||||||
);
|
);
|
||||||
@@ -106,7 +179,7 @@ async function getFile(req, res) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
$.notify(`🌍 Sub-Store 下载文件失败`, `❌ 未找到文件:${name}!`);
|
$.error(`🌍 Sub-Store 下载文件失败\n❌ 未找到文件:${name}!`);
|
||||||
failed(
|
failed(
|
||||||
res,
|
res,
|
||||||
new ResourceNotFoundError(
|
new ResourceNotFoundError(
|
||||||
|
|||||||
@@ -3,11 +3,14 @@ import $ from '@/core/app';
|
|||||||
import migrate from '@/utils/migration';
|
import migrate from '@/utils/migration';
|
||||||
import download from '@/utils/download';
|
import download from '@/utils/download';
|
||||||
import { syncArtifacts } from '@/restful/sync';
|
import { syncArtifacts } from '@/restful/sync';
|
||||||
|
import { gistBackupAction } from '@/restful/miscs';
|
||||||
|
import { TOKENS_KEY } from '@/constants';
|
||||||
|
|
||||||
import registerSubscriptionRoutes from './subscriptions';
|
import registerSubscriptionRoutes from './subscriptions';
|
||||||
import registerCollectionRoutes from './collections';
|
import registerCollectionRoutes from './collections';
|
||||||
import registerArtifactRoutes from './artifacts';
|
import registerArtifactRoutes from './artifacts';
|
||||||
import registerFileRoutes from './file';
|
import registerFileRoutes from './file';
|
||||||
|
import registerTokenRoutes from './token';
|
||||||
import registerModuleRoutes from './module';
|
import registerModuleRoutes from './module';
|
||||||
import registerSyncRoutes from './sync';
|
import registerSyncRoutes from './sync';
|
||||||
import registerDownloadRoutes from './download';
|
import registerDownloadRoutes from './download';
|
||||||
@@ -35,6 +38,7 @@ export default function serve() {
|
|||||||
registerSettingRoutes($app);
|
registerSettingRoutes($app);
|
||||||
registerArtifactRoutes($app);
|
registerArtifactRoutes($app);
|
||||||
registerFileRoutes($app);
|
registerFileRoutes($app);
|
||||||
|
registerTokenRoutes($app);
|
||||||
registerModuleRoutes($app);
|
registerModuleRoutes($app);
|
||||||
registerSyncRoutes($app);
|
registerSyncRoutes($app);
|
||||||
registerNodeInfoRoutes($app);
|
registerNodeInfoRoutes($app);
|
||||||
@@ -44,20 +48,81 @@ export default function serve() {
|
|||||||
$app.start();
|
$app.start();
|
||||||
|
|
||||||
if ($.env.isNode) {
|
if ($.env.isNode) {
|
||||||
const backend_cron = eval('process.env.SUB_STORE_BACKEND_CRON');
|
// Deprecated: SUB_STORE_BACKEND_CRON
|
||||||
if (backend_cron) {
|
const backend_sync_cron =
|
||||||
$.info(`[CRON] ${backend_cron} enabled`);
|
eval('process.env.SUB_STORE_BACKEND_SYNC_CRON') ||
|
||||||
|
eval('process.env.SUB_STORE_BACKEND_CRON');
|
||||||
|
if (backend_sync_cron) {
|
||||||
|
$.info(`[SYNC CRON] ${backend_sync_cron} enabled`);
|
||||||
const { CronJob } = eval(`require("cron")`);
|
const { CronJob } = eval(`require("cron")`);
|
||||||
new CronJob(
|
new CronJob(
|
||||||
backend_cron,
|
backend_sync_cron,
|
||||||
async function () {
|
async function () {
|
||||||
try {
|
try {
|
||||||
$.info(`[CRON] ${backend_cron} started`);
|
$.info(`[SYNC CRON] ${backend_sync_cron} started`);
|
||||||
await syncArtifacts();
|
await syncArtifacts();
|
||||||
$.info(`[CRON] ${backend_cron} finished`);
|
$.info(`[SYNC CRON] ${backend_sync_cron} finished`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
$.error(
|
$.error(
|
||||||
`[CRON] ${backend_cron} error: ${e.message ?? e}`,
|
`[SYNC CRON] ${backend_sync_cron} error: ${
|
||||||
|
e.message ?? e
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, // onTick
|
||||||
|
null, // onComplete
|
||||||
|
true, // start
|
||||||
|
// 'Asia/Shanghai' // timeZone
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const backend_download_cron = eval(
|
||||||
|
'process.env.SUB_STORE_BACKEND_DOWNLOAD_CRON',
|
||||||
|
);
|
||||||
|
if (backend_download_cron) {
|
||||||
|
$.info(`[DOWNLOAD CRON] ${backend_download_cron} enabled`);
|
||||||
|
const { CronJob } = eval(`require("cron")`);
|
||||||
|
new CronJob(
|
||||||
|
backend_download_cron,
|
||||||
|
async function () {
|
||||||
|
try {
|
||||||
|
$.info(
|
||||||
|
`[DOWNLOAD CRON] ${backend_download_cron} started`,
|
||||||
|
);
|
||||||
|
await gistBackupAction('download');
|
||||||
|
$.info(
|
||||||
|
`[DOWNLOAD CRON] ${backend_download_cron} finished`,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`[DOWNLOAD CRON] ${backend_download_cron} error: ${
|
||||||
|
e.message ?? e
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, // onTick
|
||||||
|
null, // onComplete
|
||||||
|
true, // start
|
||||||
|
// 'Asia/Shanghai' // timeZone
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const backend_upload_cron = eval(
|
||||||
|
'process.env.SUB_STORE_BACKEND_UPLOAD_CRON',
|
||||||
|
);
|
||||||
|
if (backend_upload_cron) {
|
||||||
|
$.info(`[UPLOAD CRON] ${backend_upload_cron} enabled`);
|
||||||
|
const { CronJob } = eval(`require("cron")`);
|
||||||
|
new CronJob(
|
||||||
|
backend_upload_cron,
|
||||||
|
async function () {
|
||||||
|
try {
|
||||||
|
$.info(`[UPLOAD CRON] ${backend_upload_cron} started`);
|
||||||
|
await gistBackupAction('upload');
|
||||||
|
$.info(`[UPLOAD CRON] ${backend_upload_cron} finished`);
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`[UPLOAD CRON] ${backend_upload_cron} error: ${
|
||||||
|
e.message ?? e
|
||||||
|
}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}, // onTick
|
}, // onTick
|
||||||
@@ -81,7 +146,7 @@ export default function serve() {
|
|||||||
try {
|
try {
|
||||||
fs.accessSync(path.join(fe_abs_path, 'index.html'));
|
fs.accessSync(path.join(fe_abs_path, 'index.html'));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(
|
$.error(
|
||||||
`[FRONTEND] index.html file not found in ${fe_abs_path}`,
|
`[FRONTEND] index.html file not found in ${fe_abs_path}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -96,6 +161,7 @@ export default function serve() {
|
|||||||
|
|
||||||
const staticFileMiddleware = express_.static(fe_path);
|
const staticFileMiddleware = express_.static(fe_path);
|
||||||
|
|
||||||
|
let be_share_rewrite = '/share/:type/:name';
|
||||||
let be_api_rewrite = '';
|
let be_api_rewrite = '';
|
||||||
let be_download_rewrite = '';
|
let be_download_rewrite = '';
|
||||||
let be_api = '/api/';
|
let be_api = '/api/';
|
||||||
@@ -112,15 +178,39 @@ export default function serve() {
|
|||||||
be_download_rewrite = `${
|
be_download_rewrite = `${
|
||||||
fe_be_path === '/' ? '' : fe_be_path
|
fe_be_path === '/' ? '' : fe_be_path
|
||||||
}${be_download}`;
|
}${be_download}`;
|
||||||
|
|
||||||
|
app.use(
|
||||||
|
be_share_rewrite,
|
||||||
|
createProxyMiddleware({
|
||||||
|
target: `http://127.0.0.1:${port}`,
|
||||||
|
changeOrigin: true,
|
||||||
|
pathRewrite: (path, req) => {
|
||||||
|
if (req.method.toLowerCase() !== 'get')
|
||||||
|
throw new Error('Method not allowed');
|
||||||
|
const tokens = $.read(TOKENS_KEY) || [];
|
||||||
|
const token = tokens.find(
|
||||||
|
(t) =>
|
||||||
|
t.token === req.query.token &&
|
||||||
|
t.type === req.params.type &&
|
||||||
|
t.name === req.params.name &&
|
||||||
|
(t.exp == null || t.exp > Date.now()),
|
||||||
|
);
|
||||||
|
if (!token) throw new Error('Forbbiden');
|
||||||
|
return path;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
app.use(
|
app.use(
|
||||||
be_api_rewrite,
|
be_api_rewrite,
|
||||||
createProxyMiddleware({
|
createProxyMiddleware({
|
||||||
target: `http://127.0.0.1:${port}`,
|
target: `http://127.0.0.1:${port}`,
|
||||||
changeOrigin: true,
|
|
||||||
pathRewrite: (path) => {
|
pathRewrite: (path) => {
|
||||||
return path.startsWith(be_api_rewrite)
|
const newPath = path.startsWith(be_api_rewrite)
|
||||||
? path.replace(be_api_rewrite, be_api)
|
? path.replace(be_api_rewrite, be_api)
|
||||||
: path;
|
: path;
|
||||||
|
return newPath.includes('?')
|
||||||
|
? `${newPath}&share=true`
|
||||||
|
: `${newPath}?share=true`;
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -158,6 +248,9 @@ export default function serve() {
|
|||||||
$.info(
|
$.info(
|
||||||
`[FRONTEND -> BACKEND] ${fe_address}:${fe_port}${be_download_rewrite} -> http://127.0.0.1:${port}${be_download}`,
|
`[FRONTEND -> BACKEND] ${fe_address}:${fe_port}${be_download_rewrite} -> http://127.0.0.1:${port}${be_download}`,
|
||||||
);
|
);
|
||||||
|
$.info(
|
||||||
|
`[SHARE BACKEND] ${fe_address}:${fe_port}${be_share_rewrite}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,6 +65,9 @@ export default function register($app) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getEnv(req, res) {
|
function getEnv(req, res) {
|
||||||
|
if (req.query.share) {
|
||||||
|
env.feature.share = true;
|
||||||
|
}
|
||||||
success(res, env);
|
success(res, env);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,10 +83,72 @@ async function refresh(_, res) {
|
|||||||
success(res);
|
success(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function gistBackupAction(action) {
|
||||||
|
// read token
|
||||||
|
const { gistToken, syncPlatform } = $.read(SETTINGS_KEY);
|
||||||
|
if (!gistToken) throw new Error('GitHub Token is required for backup!');
|
||||||
|
|
||||||
|
const gist = new Gist({
|
||||||
|
token: gistToken,
|
||||||
|
key: GIST_BACKUP_KEY,
|
||||||
|
syncPlatform,
|
||||||
|
});
|
||||||
|
let content;
|
||||||
|
const settings = $.read(SETTINGS_KEY);
|
||||||
|
const updated = settings.syncTime;
|
||||||
|
switch (action) {
|
||||||
|
case 'upload':
|
||||||
|
// update syncTime
|
||||||
|
settings.syncTime = new Date().getTime();
|
||||||
|
$.write(settings, SETTINGS_KEY);
|
||||||
|
content = $.read('#sub-store');
|
||||||
|
if ($.env.isNode) content = JSON.stringify($.cache, null, ` `);
|
||||||
|
$.info(`上传备份中...`);
|
||||||
|
try {
|
||||||
|
await gist.upload({
|
||||||
|
[GIST_BACKUP_FILE_NAME]: { content },
|
||||||
|
});
|
||||||
|
$.info(`上传备份完成`);
|
||||||
|
} catch (err) {
|
||||||
|
// restore syncTime if upload failed
|
||||||
|
settings.syncTime = updated;
|
||||||
|
$.write(settings, SETTINGS_KEY);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'download':
|
||||||
|
$.info(`还原备份中...`);
|
||||||
|
content = await gist.download(GIST_BACKUP_FILE_NAME);
|
||||||
|
try {
|
||||||
|
if (Object.keys(JSON.parse(content).settings).length === 0) {
|
||||||
|
throw new Error('备份文件应该至少包含 settings 字段');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
$.error(
|
||||||
|
`Gist 备份文件校验失败, 无法还原\nReason: ${
|
||||||
|
err.message ?? err
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
throw new Error('Gist 备份文件校验失败, 无法还原');
|
||||||
|
}
|
||||||
|
// restore settings
|
||||||
|
$.write(content, '#sub-store');
|
||||||
|
if ($.env.isNode) {
|
||||||
|
content = JSON.parse(content);
|
||||||
|
$.cache = content;
|
||||||
|
$.persistCache();
|
||||||
|
}
|
||||||
|
$.info(`perform migration after restoring from gist...`);
|
||||||
|
migrate();
|
||||||
|
$.info(`migration completed`);
|
||||||
|
$.info(`还原备份完成`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
async function gistBackup(req, res) {
|
async function gistBackup(req, res) {
|
||||||
const { action } = req.query;
|
const { action } = req.query;
|
||||||
// read token
|
// read token
|
||||||
const { gistToken, syncPlatform } = $.read(SETTINGS_KEY);
|
const { gistToken } = $.read(SETTINGS_KEY);
|
||||||
if (!gistToken) {
|
if (!gistToken) {
|
||||||
failed(
|
failed(
|
||||||
res,
|
res,
|
||||||
@@ -93,68 +158,8 @@ async function gistBackup(req, res) {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
const gist = new Gist({
|
|
||||||
token: gistToken,
|
|
||||||
key: GIST_BACKUP_KEY,
|
|
||||||
syncPlatform,
|
|
||||||
});
|
|
||||||
try {
|
try {
|
||||||
let content;
|
await gistBackupAction(action);
|
||||||
const settings = $.read(SETTINGS_KEY);
|
|
||||||
const updated = settings.syncTime;
|
|
||||||
switch (action) {
|
|
||||||
case 'upload':
|
|
||||||
// update syncTime
|
|
||||||
settings.syncTime = new Date().getTime();
|
|
||||||
$.write(settings, SETTINGS_KEY);
|
|
||||||
content = $.read('#sub-store');
|
|
||||||
if ($.env.isNode)
|
|
||||||
content = JSON.stringify($.cache, null, ` `);
|
|
||||||
$.info(`上传备份中...`);
|
|
||||||
try {
|
|
||||||
await gist.upload({
|
|
||||||
[GIST_BACKUP_FILE_NAME]: { content },
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
// restore syncTime if upload failed
|
|
||||||
settings.syncTime = updated;
|
|
||||||
$.write(settings, SETTINGS_KEY);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case 'download':
|
|
||||||
$.info(`还原备份中...`);
|
|
||||||
content = await gist.download(GIST_BACKUP_FILE_NAME);
|
|
||||||
try {
|
|
||||||
if (
|
|
||||||
Object.keys(JSON.parse(content).settings).length ===
|
|
||||||
0
|
|
||||||
) {
|
|
||||||
throw new Error(
|
|
||||||
'备份文件应该至少包含 settings 字段',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
$.error(
|
|
||||||
`Gist 备份文件校验失败, 无法还原\nReason: ${
|
|
||||||
err.message ?? err
|
|
||||||
}`,
|
|
||||||
);
|
|
||||||
throw new Error('Gist 备份文件校验失败, 无法还原');
|
|
||||||
}
|
|
||||||
// restore settings
|
|
||||||
$.write(content, '#sub-store');
|
|
||||||
if ($.env.isNode) {
|
|
||||||
content = JSON.parse(content);
|
|
||||||
$.cache = content;
|
|
||||||
$.persistCache();
|
|
||||||
}
|
|
||||||
$.info(`perform migration after restoring from gist...`);
|
|
||||||
migrate();
|
|
||||||
$.info(`migration completed`);
|
|
||||||
$.info(`还原备份完成`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
success(res);
|
success(res);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
$.error(
|
$.error(
|
||||||
@@ -171,3 +176,5 @@ async function gistBackup(req, res) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export { gistBackupAction };
|
||||||
|
|||||||
@@ -146,7 +146,8 @@ async function compareSub(req, res) {
|
|||||||
// add id
|
// add id
|
||||||
original.forEach((proxy, i) => {
|
original.forEach((proxy, i) => {
|
||||||
proxy.id = i;
|
proxy.id = i;
|
||||||
proxy.subName = sub.name;
|
proxy._subName = sub.name;
|
||||||
|
proxy._subDisplayName = sub.displayName;
|
||||||
});
|
});
|
||||||
|
|
||||||
// apply processors
|
// apply processors
|
||||||
@@ -176,7 +177,20 @@ async function compareCollection(req, res) {
|
|||||||
try {
|
try {
|
||||||
const allSubs = $.read(SUBS_KEY);
|
const allSubs = $.read(SUBS_KEY);
|
||||||
const collection = req.body;
|
const collection = req.body;
|
||||||
const subnames = collection.subscriptions;
|
const subnames = [...collection.subscriptions];
|
||||||
|
let subscriptionTags = collection.subscriptionTags;
|
||||||
|
if (Array.isArray(subscriptionTags) && subscriptionTags.length > 0) {
|
||||||
|
allSubs.forEach((sub) => {
|
||||||
|
if (
|
||||||
|
Array.isArray(sub.tag) &&
|
||||||
|
sub.tag.length > 0 &&
|
||||||
|
!subnames.includes(sub.name) &&
|
||||||
|
sub.tag.some((tag) => subscriptionTags.includes(tag))
|
||||||
|
) {
|
||||||
|
subnames.push(sub.name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
const results = {};
|
const results = {};
|
||||||
const errors = {};
|
const errors = {};
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
@@ -237,8 +251,10 @@ async function compareCollection(req, res) {
|
|||||||
.flat();
|
.flat();
|
||||||
|
|
||||||
currentProxies.forEach((proxy) => {
|
currentProxies.forEach((proxy) => {
|
||||||
proxy.subName = sub.name;
|
proxy._subName = sub.name;
|
||||||
proxy.collectionName = collection.name;
|
proxy._subDisplayName = sub.displayName;
|
||||||
|
proxy._collectionName = collection.name;
|
||||||
|
proxy._collectionDisplayName = collection.displayName;
|
||||||
});
|
});
|
||||||
|
|
||||||
// apply processors
|
// apply processors
|
||||||
@@ -276,7 +292,8 @@ async function compareCollection(req, res) {
|
|||||||
|
|
||||||
original.forEach((proxy, i) => {
|
original.forEach((proxy, i) => {
|
||||||
proxy.id = i;
|
proxy.id = i;
|
||||||
proxy.collectionName = collection.name;
|
proxy._collectionName = collection.name;
|
||||||
|
proxy._collectionDisplayName = collection.displayName;
|
||||||
});
|
});
|
||||||
|
|
||||||
const processed = await ProxyUtils.process(
|
const processed = await ProxyUtils.process(
|
||||||
|
|||||||
@@ -34,6 +34,11 @@ export default function register($app) {
|
|||||||
async function getFlowInfo(req, res) {
|
async function getFlowInfo(req, res) {
|
||||||
let { name } = req.params;
|
let { name } = req.params;
|
||||||
name = decodeURIComponent(name);
|
name = decodeURIComponent(name);
|
||||||
|
let { url } = req.query;
|
||||||
|
if (url) {
|
||||||
|
url = decodeURIComponent(url);
|
||||||
|
$.info(`指定远程订阅 URL: ${url}`);
|
||||||
|
}
|
||||||
const allSubs = $.read(SUBS_KEY);
|
const allSubs = $.read(SUBS_KEY);
|
||||||
const sub = findByName(allSubs, name);
|
const sub = findByName(allSubs, name);
|
||||||
if (!sub) {
|
if (!sub) {
|
||||||
@@ -52,9 +57,45 @@ async function getFlowInfo(req, res) {
|
|||||||
!['localFirst', 'remoteFirst'].includes(sub.mergeSources)
|
!['localFirst', 'remoteFirst'].includes(sub.mergeSources)
|
||||||
) {
|
) {
|
||||||
if (sub.subUserinfo) {
|
if (sub.subUserinfo) {
|
||||||
success(res, {
|
let subUserInfo;
|
||||||
...parseFlowHeaders(sub.subUserinfo),
|
if (/^https?:\/\//.test(sub.subUserinfo)) {
|
||||||
});
|
try {
|
||||||
|
subUserInfo = await getFlowHeaders(
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
sub.proxy,
|
||||||
|
sub.subUserinfo,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`订阅 ${name} 使用自定义流量链接 ${
|
||||||
|
sub.subUserinfo
|
||||||
|
} 获取流量信息时发生错误: ${JSON.stringify(e)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
subUserInfo = sub.subUserinfo;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
success(res, {
|
||||||
|
...parseFlowHeaders(subUserInfo),
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`Failed to parse flow info for local subscription ${name}: ${
|
||||||
|
e.message ?? e
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'NO_FLOW_INFO',
|
||||||
|
'N/A',
|
||||||
|
`Failed to parse flow info`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
failed(
|
failed(
|
||||||
res,
|
res,
|
||||||
@@ -68,10 +109,11 @@ async function getFlowInfo(req, res) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
let url = `${sub.url}`
|
url =
|
||||||
.split(/[\r\n]+/)
|
`${url || sub.url}`
|
||||||
.map((i) => i.trim())
|
.split(/[\r\n]+/)
|
||||||
.filter((i) => i.length)?.[0];
|
.map((i) => i.trim())
|
||||||
|
.filter((i) => i.length)?.[0] || '';
|
||||||
|
|
||||||
let $arguments = {};
|
let $arguments = {};
|
||||||
const rawArgs = url.split('#');
|
const rawArgs = url.split('#');
|
||||||
@@ -103,41 +145,73 @@ async function getFlowInfo(req, res) {
|
|||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (sub.subUserinfo) {
|
const flowHeaders = await getFlowHeaders(
|
||||||
success(res, {
|
$arguments?.insecure ? `${url}#insecure` : url,
|
||||||
...parseFlowHeaders(sub.subUserinfo),
|
$arguments.flowUserAgent,
|
||||||
remainingDays: getRmainingDays({
|
undefined,
|
||||||
resetDay: $arguments.resetDay,
|
sub.proxy,
|
||||||
startDate: $arguments.startDate,
|
$arguments.flowUrl,
|
||||||
cycleDays: $arguments.cycleDays,
|
);
|
||||||
}),
|
if (!flowHeaders && !sub.subUserinfo) {
|
||||||
});
|
failed(
|
||||||
} else {
|
res,
|
||||||
const flowHeaders = await getFlowHeaders(
|
new InternalServerError(
|
||||||
url,
|
'NO_FLOW_INFO',
|
||||||
$arguments.flowUserAgent,
|
'No flow info',
|
||||||
undefined,
|
`Failed to fetch flow headers`,
|
||||||
sub.proxy,
|
),
|
||||||
);
|
);
|
||||||
if (!flowHeaders) {
|
return;
|
||||||
failed(
|
}
|
||||||
res,
|
try {
|
||||||
new InternalServerError(
|
const remainingDays = getRmainingDays({
|
||||||
'NO_FLOW_INFO',
|
resetDay: $arguments.resetDay,
|
||||||
'No flow info',
|
startDate: $arguments.startDate,
|
||||||
`Failed to fetch flow headers`,
|
cycleDays: $arguments.cycleDays,
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
success(res, {
|
|
||||||
...parseFlowHeaders(flowHeaders),
|
|
||||||
remainingDays: getRmainingDays({
|
|
||||||
resetDay: $arguments.resetDay,
|
|
||||||
startDate: $arguments.startDate,
|
|
||||||
cycleDays: $arguments.cycleDays,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
let subUserInfo;
|
||||||
|
if (/^https?:\/\//.test(sub.subUserinfo)) {
|
||||||
|
try {
|
||||||
|
subUserInfo = await getFlowHeaders(
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
sub.proxy,
|
||||||
|
sub.subUserinfo,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`订阅 ${name} 使用自定义流量链接 ${
|
||||||
|
sub.subUserinfo
|
||||||
|
} 获取流量信息时发生错误: ${JSON.stringify(e)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
subUserInfo = sub.subUserinfo;
|
||||||
|
}
|
||||||
|
const result = {
|
||||||
|
...parseFlowHeaders(
|
||||||
|
[subUserInfo, flowHeaders].filter((i) => i).join('; '),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
if (remainingDays != null) {
|
||||||
|
result.remainingDays = remainingDays;
|
||||||
|
}
|
||||||
|
success(res, result);
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`Failed to parse flow info for local subscription ${name}: ${
|
||||||
|
e.message ?? e
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'NO_FLOW_INFO',
|
||||||
|
'N/A',
|
||||||
|
`Failed to parse flow info`,
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
failed(
|
failed(
|
||||||
|
|||||||
@@ -36,6 +36,10 @@ async function produceArtifact({
|
|||||||
produceType,
|
produceType,
|
||||||
produceOpts = {},
|
produceOpts = {},
|
||||||
subscription,
|
subscription,
|
||||||
|
awaitCustomCache,
|
||||||
|
$options,
|
||||||
|
proxy,
|
||||||
|
noCache,
|
||||||
}) {
|
}) {
|
||||||
platform = platform || 'JSON';
|
platform = platform || 'JSON';
|
||||||
|
|
||||||
@@ -66,7 +70,10 @@ async function produceArtifact({
|
|||||||
url,
|
url,
|
||||||
ua || sub.ua,
|
ua || sub.ua,
|
||||||
undefined,
|
undefined,
|
||||||
sub.proxy,
|
proxy || sub.proxy,
|
||||||
|
undefined,
|
||||||
|
awaitCustomCache,
|
||||||
|
noCache,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
errors[url] = err;
|
errors[url] = err;
|
||||||
@@ -111,7 +118,10 @@ async function produceArtifact({
|
|||||||
url,
|
url,
|
||||||
ua || sub.ua,
|
ua || sub.ua,
|
||||||
undefined,
|
undefined,
|
||||||
sub.proxy,
|
proxy || sub.proxy,
|
||||||
|
undefined,
|
||||||
|
awaitCustomCache,
|
||||||
|
noCache,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
errors[url] = err;
|
errors[url] = err;
|
||||||
@@ -145,7 +155,8 @@ async function produceArtifact({
|
|||||||
.flat();
|
.flat();
|
||||||
|
|
||||||
proxies.forEach((proxy) => {
|
proxies.forEach((proxy) => {
|
||||||
proxy.subName = sub.name;
|
proxy._subName = sub.name;
|
||||||
|
proxy._subDisplayName = sub.displayName;
|
||||||
});
|
});
|
||||||
// apply processors
|
// apply processors
|
||||||
proxies = await ProxyUtils.process(
|
proxies = await ProxyUtils.process(
|
||||||
@@ -153,6 +164,7 @@ async function produceArtifact({
|
|||||||
sub.process || [],
|
sub.process || [],
|
||||||
platform,
|
platform,
|
||||||
{ [sub.name]: sub },
|
{ [sub.name]: sub },
|
||||||
|
$options,
|
||||||
);
|
);
|
||||||
if (proxies.length === 0) {
|
if (proxies.length === 0) {
|
||||||
throw new Error(`订阅 ${name} 中不含有效节点`);
|
throw new Error(`订阅 ${name} 中不含有效节点`);
|
||||||
@@ -181,7 +193,20 @@ async function produceArtifact({
|
|||||||
const allCols = $.read(COLLECTIONS_KEY);
|
const allCols = $.read(COLLECTIONS_KEY);
|
||||||
const collection = findByName(allCols, name);
|
const collection = findByName(allCols, name);
|
||||||
if (!collection) throw new Error(`找不到组合订阅 ${name}`);
|
if (!collection) throw new Error(`找不到组合订阅 ${name}`);
|
||||||
const subnames = collection.subscriptions;
|
const subnames = [...collection.subscriptions];
|
||||||
|
let subscriptionTags = collection.subscriptionTags;
|
||||||
|
if (Array.isArray(subscriptionTags) && subscriptionTags.length > 0) {
|
||||||
|
allSubs.forEach((sub) => {
|
||||||
|
if (
|
||||||
|
Array.isArray(sub.tag) &&
|
||||||
|
sub.tag.length > 0 &&
|
||||||
|
!subnames.includes(sub.name) &&
|
||||||
|
sub.tag.some((tag) => subscriptionTags.includes(tag))
|
||||||
|
) {
|
||||||
|
subnames.push(sub.name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
const results = {};
|
const results = {};
|
||||||
const errors = {};
|
const errors = {};
|
||||||
let processed = 0;
|
let processed = 0;
|
||||||
@@ -212,7 +237,12 @@ async function produceArtifact({
|
|||||||
url,
|
url,
|
||||||
sub.ua,
|
sub.ua,
|
||||||
undefined,
|
undefined,
|
||||||
sub.proxy,
|
proxy ||
|
||||||
|
sub.proxy ||
|
||||||
|
collection.proxy,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
noCache,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
errors[url] = err;
|
errors[url] = err;
|
||||||
@@ -245,8 +275,10 @@ async function produceArtifact({
|
|||||||
.flat();
|
.flat();
|
||||||
|
|
||||||
currentProxies.forEach((proxy) => {
|
currentProxies.forEach((proxy) => {
|
||||||
proxy.subName = sub.name;
|
proxy._subName = sub.name;
|
||||||
proxy.collectionName = collection.name;
|
proxy._subDisplayName = sub.displayName;
|
||||||
|
proxy._collectionName = collection.name;
|
||||||
|
proxy._collectionDisplayName = collection.displayName;
|
||||||
});
|
});
|
||||||
|
|
||||||
// apply processors
|
// apply processors
|
||||||
@@ -254,7 +286,11 @@ async function produceArtifact({
|
|||||||
currentProxies,
|
currentProxies,
|
||||||
sub.process || [],
|
sub.process || [],
|
||||||
platform,
|
platform,
|
||||||
{ [sub.name]: sub, _collection: collection },
|
{
|
||||||
|
[sub.name]: sub,
|
||||||
|
_collection: collection,
|
||||||
|
$options,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
results[name] = currentProxies;
|
results[name] = currentProxies;
|
||||||
processed++;
|
processed++;
|
||||||
@@ -298,7 +334,8 @@ async function produceArtifact({
|
|||||||
);
|
);
|
||||||
|
|
||||||
proxies.forEach((proxy) => {
|
proxies.forEach((proxy) => {
|
||||||
proxy.collectionName = collection.name;
|
proxy._collectionName = collection.name;
|
||||||
|
proxy._collectionDisplayName = collection.displayName;
|
||||||
});
|
});
|
||||||
|
|
||||||
// apply own processors
|
// apply own processors
|
||||||
@@ -307,6 +344,7 @@ async function produceArtifact({
|
|||||||
collection.process || [],
|
collection.process || [],
|
||||||
platform,
|
platform,
|
||||||
{ _collection: collection },
|
{ _collection: collection },
|
||||||
|
$options,
|
||||||
);
|
);
|
||||||
if (proxies.length === 0) {
|
if (proxies.length === 0) {
|
||||||
throw new Error(`组合订阅 ${name} 中不含有效节点`);
|
throw new Error(`组合订阅 ${name} 中不含有效节点`);
|
||||||
@@ -373,7 +411,15 @@ async function produceArtifact({
|
|||||||
.filter((i) => i.length)
|
.filter((i) => i.length)
|
||||||
.map(async (url) => {
|
.map(async (url) => {
|
||||||
try {
|
try {
|
||||||
return await download(url, ua || file.ua);
|
return await download(
|
||||||
|
url,
|
||||||
|
ua || file.ua,
|
||||||
|
undefined,
|
||||||
|
file.proxy || proxy,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
noCache,
|
||||||
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
errors[url] = err;
|
errors[url] = err;
|
||||||
$.error(
|
$.error(
|
||||||
@@ -416,7 +462,15 @@ async function produceArtifact({
|
|||||||
.filter((i) => i.length)
|
.filter((i) => i.length)
|
||||||
.map(async (url) => {
|
.map(async (url) => {
|
||||||
try {
|
try {
|
||||||
return await download(url, ua || file.ua);
|
return await download(
|
||||||
|
url,
|
||||||
|
ua || file.ua,
|
||||||
|
undefined,
|
||||||
|
file.proxy || proxy,
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
noCache,
|
||||||
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
errors[url] = err;
|
errors[url] = err;
|
||||||
$.error(
|
$.error(
|
||||||
@@ -455,10 +509,10 @@ async function produceArtifact({
|
|||||||
const processed =
|
const processed =
|
||||||
Array.isArray(file.process) && file.process.length > 0
|
Array.isArray(file.process) && file.process.length > 0
|
||||||
? await ProxyUtils.process(
|
? await ProxyUtils.process(
|
||||||
{ $files: files, $content: filesContent },
|
{ $files: files, $content: filesContent, $options },
|
||||||
file.process,
|
file.process,
|
||||||
)
|
)
|
||||||
: { $content: filesContent, $files: files };
|
: { $content: filesContent, $files: files, $options };
|
||||||
|
|
||||||
return processed?.$content ?? '';
|
return processed?.$content ?? '';
|
||||||
}
|
}
|
||||||
@@ -503,6 +557,7 @@ async function syncArtifacts() {
|
|||||||
await produceArtifact({
|
await produceArtifact({
|
||||||
type: 'subscription',
|
type: 'subscription',
|
||||||
name: subName,
|
name: subName,
|
||||||
|
awaitCustomCache: true,
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// $.error(`${e.message ?? e}`);
|
// $.error(`${e.message ?? e}`);
|
||||||
@@ -516,6 +571,16 @@ async function syncArtifacts() {
|
|||||||
try {
|
try {
|
||||||
if (artifact.sync && artifact.source) {
|
if (artifact.sync && artifact.source) {
|
||||||
$.info(`正在同步云配置:${artifact.name}...`);
|
$.info(`正在同步云配置:${artifact.name}...`);
|
||||||
|
|
||||||
|
const useMihomoExternal =
|
||||||
|
artifact.platform === 'SurgeMac';
|
||||||
|
|
||||||
|
if (useMihomoExternal) {
|
||||||
|
$.info(
|
||||||
|
`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const output = await produceArtifact({
|
const output = await produceArtifact({
|
||||||
type: artifact.type,
|
type: artifact.type,
|
||||||
name: artifact.source,
|
name: artifact.source,
|
||||||
@@ -523,6 +588,7 @@ async function syncArtifacts() {
|
|||||||
produceOpts: {
|
produceOpts: {
|
||||||
'include-unsupported-proxy':
|
'include-unsupported-proxy':
|
||||||
artifact.includeUnsupportedProxy,
|
artifact.includeUnsupportedProxy,
|
||||||
|
useMihomoExternal,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -638,12 +704,18 @@ async function syncArtifact(req, res) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const useMihomoExternal = artifact.platform === 'SurgeMac';
|
||||||
|
|
||||||
|
if (useMihomoExternal) {
|
||||||
|
$.info(`手动指定了 target 为 SurgeMac, 将使用 Mihomo External`);
|
||||||
|
}
|
||||||
const output = await produceArtifact({
|
const output = await produceArtifact({
|
||||||
type: artifact.type,
|
type: artifact.type,
|
||||||
name: artifact.source,
|
name: artifact.source,
|
||||||
platform: artifact.platform,
|
platform: artifact.platform,
|
||||||
produceOpts: {
|
produceOpts: {
|
||||||
'include-unsupported-proxy': artifact.includeUnsupportedProxy,
|
'include-unsupported-proxy': artifact.includeUnsupportedProxy,
|
||||||
|
useMihomoExternal,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
181
backend/src/restful/token.js
Normal file
181
backend/src/restful/token.js
Normal file
@@ -0,0 +1,181 @@
|
|||||||
|
import { deleteByName } from '@/utils/database';
|
||||||
|
import { ENV } from '@/vendor/open-api';
|
||||||
|
import { TOKENS_KEY, SUBS_KEY, FILES_KEY, COLLECTIONS_KEY } from '@/constants';
|
||||||
|
import { failed, success } from '@/restful/response';
|
||||||
|
import $ from '@/core/app';
|
||||||
|
import { RequestInvalidError, InternalServerError } from '@/restful/errors';
|
||||||
|
|
||||||
|
export default function register($app) {
|
||||||
|
if (!$.read(TOKENS_KEY)) $.write([], TOKENS_KEY);
|
||||||
|
|
||||||
|
$app.post('/api/token', signToken);
|
||||||
|
|
||||||
|
$app.route('/api/token/:token').delete(deleteToken);
|
||||||
|
|
||||||
|
$app.route('/api/tokens').get(getAllTokens);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteToken(req, res) {
|
||||||
|
let { token } = req.params;
|
||||||
|
token = decodeURIComponent(token);
|
||||||
|
$.info(`正在删除:${token}`);
|
||||||
|
let allTokens = $.read(TOKENS_KEY);
|
||||||
|
deleteByName(allTokens, token, 'token');
|
||||||
|
$.write(allTokens, TOKENS_KEY);
|
||||||
|
success(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAllTokens(req, res) {
|
||||||
|
const { type, name } = req.query;
|
||||||
|
const allTokens = $.read(TOKENS_KEY) || [];
|
||||||
|
success(
|
||||||
|
res,
|
||||||
|
type || name
|
||||||
|
? allTokens.filter(
|
||||||
|
(item) =>
|
||||||
|
(type ? item.type === type : true) &&
|
||||||
|
(name ? item.name === name : true),
|
||||||
|
)
|
||||||
|
: allTokens,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signToken(req, res) {
|
||||||
|
if (!ENV().isNode) {
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'INVALID_ENV',
|
||||||
|
`This endpoint is only available in Node.js environment`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { payload, options } = req.body;
|
||||||
|
const ms = eval(`require("ms")`);
|
||||||
|
let token = payload?.token;
|
||||||
|
if (token != null) {
|
||||||
|
if (typeof token !== 'string' || token.length < 1) {
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'INVALID_CUSTOM_TOKEN',
|
||||||
|
`Invalid custom token: ${token}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const tokens = $.read(TOKENS_KEY) || [];
|
||||||
|
if (tokens.find((t) => t.token === token)) {
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'DUPLICATE_TOKEN',
|
||||||
|
`Token ${token} already exists`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const type = payload?.type;
|
||||||
|
const name = payload?.name;
|
||||||
|
if (!type || !name)
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'INVALID_PAYLOAD',
|
||||||
|
`payload type and name are required`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (type === 'col') {
|
||||||
|
const collections = $.read(COLLECTIONS_KEY) || [];
|
||||||
|
const collection = collections.find((c) => c.name === name);
|
||||||
|
if (!collection)
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'INVALID_COLLECTION',
|
||||||
|
`collection ${name} not found`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else if (type === 'file') {
|
||||||
|
const files = $.read(FILES_KEY) || [];
|
||||||
|
const file = files.find((f) => f.name === name);
|
||||||
|
if (!file)
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'INVALID_FILE',
|
||||||
|
`file ${name} not found`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else if (type === 'sub') {
|
||||||
|
const subs = $.read(SUBS_KEY) || [];
|
||||||
|
const sub = subs.find((s) => s.name === name);
|
||||||
|
if (!sub)
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'INVALID_SUB',
|
||||||
|
`sub ${name} not found`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'INVALID_TYPE',
|
||||||
|
`type ${name} not supported`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let expiresIn = options?.expiresIn;
|
||||||
|
if (options?.expiresIn != null) {
|
||||||
|
expiresIn = ms(options.expiresIn);
|
||||||
|
if (expiresIn == null || isNaN(expiresIn) || expiresIn <= 0) {
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new RequestInvalidError(
|
||||||
|
'INVALID_EXPIRES_IN',
|
||||||
|
`Invalid expiresIn option: ${options.expiresIn}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// const secret = eval('process.env.SUB_STORE_FRONTEND_BACKEND_PATH');
|
||||||
|
const nanoid = eval(`require("nanoid")`);
|
||||||
|
const tokens = $.read(TOKENS_KEY) || [];
|
||||||
|
// const now = Date.now();
|
||||||
|
// for (const key in tokens) {
|
||||||
|
// const token = tokens[key];
|
||||||
|
// if (token.exp != null || token.exp < now) {
|
||||||
|
// delete tokens[key];
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
if (!token) {
|
||||||
|
do {
|
||||||
|
token = nanoid.customAlphabet(nanoid.urlAlphabet)();
|
||||||
|
} while (tokens.find((t) => t.token === token));
|
||||||
|
}
|
||||||
|
tokens.push({
|
||||||
|
...payload,
|
||||||
|
token,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
expiresIn: expiresIn > 0 ? options?.expiresIn : undefined,
|
||||||
|
exp: expiresIn > 0 ? Date.now() + expiresIn : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
$.write(tokens, TOKENS_KEY);
|
||||||
|
return success(res, {
|
||||||
|
token,
|
||||||
|
// secret,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return failed(
|
||||||
|
res,
|
||||||
|
new InternalServerError(
|
||||||
|
'TOKEN_SIGN_FAILED',
|
||||||
|
`Failed to sign token`,
|
||||||
|
`Reason: ${e.message ?? e}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
export function findByName(list, name) {
|
export function findByName(list, name, field = 'name') {
|
||||||
return list.find((item) => item.name === name);
|
return list.find((item) => item[field] === name);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function findIndexByName(list, name) {
|
export function findIndexByName(list, name, field = 'name') {
|
||||||
return list.findIndex((item) => item.name === name);
|
return list.findIndex((item) => item[field] === name);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function deleteByName(list, name) {
|
export function deleteByName(list, name, field = 'name') {
|
||||||
const idx = findIndexByName(list, name);
|
const idx = findIndexByName(list, name, field);
|
||||||
list.splice(idx, 1);
|
list.splice(idx, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateByName(list, name, newItem) {
|
export function updateByName(list, name, newItem, field = 'name') {
|
||||||
const idx = findIndexByName(list, name);
|
const idx = findIndexByName(list, name, field);
|
||||||
list[idx] = newItem;
|
list[idx] = newItem;
|
||||||
}
|
}
|
||||||
|
|||||||
50
backend/src/utils/dns.js
Normal file
50
backend/src/utils/dns.js
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import $ from '@/core/app';
|
||||||
|
import dnsPacket from 'dns-packet';
|
||||||
|
import { Buffer } from 'buffer';
|
||||||
|
import { isIPv4 } from '@/utils';
|
||||||
|
|
||||||
|
export async function doh({ url, domain, type = 'A', timeout, edns }) {
|
||||||
|
const buf = dnsPacket.encode({
|
||||||
|
type: 'query',
|
||||||
|
id: 0,
|
||||||
|
flags: dnsPacket.RECURSION_DESIRED,
|
||||||
|
questions: [
|
||||||
|
{
|
||||||
|
type,
|
||||||
|
name: domain,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
additionals: [
|
||||||
|
{
|
||||||
|
type: 'OPT',
|
||||||
|
name: '.',
|
||||||
|
udpPayloadSize: 4096,
|
||||||
|
flags: 0,
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
code: 'CLIENT_SUBNET',
|
||||||
|
ip: edns,
|
||||||
|
sourcePrefixLength: isIPv4(edns) ? 24 : 56,
|
||||||
|
scopePrefixLength: 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const res = await $.http.get({
|
||||||
|
url: `${url}?dns=${buf
|
||||||
|
.toString('base64')
|
||||||
|
.toString('utf-8')
|
||||||
|
.replace(/=/g, '')}`,
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/dns-message',
|
||||||
|
// 'Content-Type': 'application/dns-message',
|
||||||
|
},
|
||||||
|
// body: buf,
|
||||||
|
'binary-mode': true,
|
||||||
|
encoding: null, // 使用 null 编码以确保响应是原始二进制数据
|
||||||
|
timeout,
|
||||||
|
});
|
||||||
|
|
||||||
|
return dnsPacket.decode(Buffer.from($.env.isQX ? res.bodyBytes : res.body));
|
||||||
|
}
|
||||||
@@ -14,7 +14,15 @@ import $ from '@/core/app';
|
|||||||
|
|
||||||
const tasks = new Map();
|
const tasks = new Map();
|
||||||
|
|
||||||
export default async function download(rawUrl, ua, timeout, proxy) {
|
export default async function download(
|
||||||
|
rawUrl = '',
|
||||||
|
ua,
|
||||||
|
timeout,
|
||||||
|
customProxy,
|
||||||
|
skipCustomCache,
|
||||||
|
awaitCustomCache,
|
||||||
|
noCache,
|
||||||
|
) {
|
||||||
let $arguments = {};
|
let $arguments = {};
|
||||||
let url = rawUrl.replace(/#noFlow$/, '');
|
let url = rawUrl.replace(/#noFlow$/, '');
|
||||||
const rawArgs = url.split('#');
|
const rawArgs = url.split('#');
|
||||||
@@ -35,10 +43,82 @@ export default async function download(rawUrl, ua, timeout, proxy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const { isNode, isStash, isLoon, isShadowRocket, isQX } = ENV();
|
||||||
|
const {
|
||||||
|
defaultProxy,
|
||||||
|
defaultUserAgent,
|
||||||
|
defaultTimeout,
|
||||||
|
cacheThreshold: defaultCacheThreshold,
|
||||||
|
} = $.read(SETTINGS_KEY);
|
||||||
|
const cacheThreshold = defaultCacheThreshold || 1024;
|
||||||
|
let proxy = customProxy || defaultProxy;
|
||||||
|
if ($.env.isNode) {
|
||||||
|
proxy = proxy || eval('process.env.SUB_STORE_BACKEND_DEFAULT_PROXY');
|
||||||
|
}
|
||||||
|
const userAgent = ua || defaultUserAgent || 'clash.meta';
|
||||||
|
const requestTimeout = timeout || defaultTimeout || 8000;
|
||||||
|
const id = hex_md5(userAgent + url);
|
||||||
|
|
||||||
|
if ($arguments?.cacheKey === true) {
|
||||||
|
$.error(`使用自定义缓存时 cacheKey 的值不能为空`);
|
||||||
|
$arguments.cacheKey = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
const customCacheKey = $arguments?.cacheKey
|
const customCacheKey = $arguments?.cacheKey
|
||||||
? `#sub-store-cached-custom-${$arguments?.cacheKey}`
|
? `#sub-store-cached-custom-${$arguments?.cacheKey}`
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
|
if (customCacheKey && !skipCustomCache) {
|
||||||
|
const customCached = $.read(customCacheKey);
|
||||||
|
const cached = resourceCache.get(id);
|
||||||
|
if (!noCache && !$arguments?.noCache && cached) {
|
||||||
|
$.info(
|
||||||
|
`乐观缓存: URL ${url}\n存在有效的常规缓存\n使用常规缓存以避免重复请求`,
|
||||||
|
);
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
if (customCached) {
|
||||||
|
if (awaitCustomCache) {
|
||||||
|
$.info(`乐观缓存: URL ${url}\n本次进行请求 尝试更新缓存`);
|
||||||
|
try {
|
||||||
|
await download(
|
||||||
|
rawUrl.replace(/(\?|&)cacheKey=.*?(&|$)/, ''),
|
||||||
|
ua,
|
||||||
|
timeout,
|
||||||
|
proxy,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`乐观缓存: URL ${url} 更新缓存发生错误 ${
|
||||||
|
e.message ?? e
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
$.info('使用乐观缓存的数据刷新缓存, 防止后续请求');
|
||||||
|
resourceCache.set(id, customCached);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$.info(
|
||||||
|
`乐观缓存: URL ${url}\n本次返回自定义缓存 ${$arguments?.cacheKey}\n并进行请求 尝试异步更新缓存`,
|
||||||
|
);
|
||||||
|
download(
|
||||||
|
rawUrl.replace(/(\?|&)cacheKey=.*?(&|$)/, ''),
|
||||||
|
ua,
|
||||||
|
timeout,
|
||||||
|
proxy,
|
||||||
|
true,
|
||||||
|
).catch((e) => {
|
||||||
|
$.error(
|
||||||
|
`乐观缓存: URL ${url} 异步更新缓存发生错误 ${
|
||||||
|
e.message ?? e
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return customCached;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// const downloadUrlMatch = url.match(/^\/api\/(file|module)\/(.+)/);
|
// const downloadUrlMatch = url.match(/^\/api\/(file|module)\/(.+)/);
|
||||||
// if (downloadUrlMatch) {
|
// if (downloadUrlMatch) {
|
||||||
// let type = downloadUrlMatch?.[1];
|
// let type = downloadUrlMatch?.[1];
|
||||||
@@ -56,12 +136,6 @@ export default async function download(rawUrl, ua, timeout, proxy) {
|
|||||||
// return item.content;
|
// return item.content;
|
||||||
// }
|
// }
|
||||||
|
|
||||||
const { isNode, isStash, isLoon, isShadowRocket, isQX } = ENV();
|
|
||||||
const { defaultUserAgent, defaultTimeout, cacheThreshold } =
|
|
||||||
$.read(SETTINGS_KEY);
|
|
||||||
const userAgent = ua || defaultUserAgent || 'clash.meta';
|
|
||||||
const requestTimeout = timeout || defaultTimeout;
|
|
||||||
const id = hex_md5(userAgent + url);
|
|
||||||
if (!isNode && tasks.has(id)) {
|
if (!isNode && tasks.has(id)) {
|
||||||
return tasks.get(id);
|
return tasks.get(id);
|
||||||
}
|
}
|
||||||
@@ -81,26 +155,40 @@ export default async function download(rawUrl, ua, timeout, proxy) {
|
|||||||
|
|
||||||
// try to find in app cache
|
// try to find in app cache
|
||||||
const cached = resourceCache.get(id);
|
const cached = resourceCache.get(id);
|
||||||
if (!$arguments?.noCache && cached) {
|
if (!noCache && !$arguments?.noCache && cached) {
|
||||||
$.info(`使用缓存: ${url}`);
|
$.info(`使用缓存: ${url}, ${userAgent}`);
|
||||||
result = cached;
|
result = cached;
|
||||||
|
if (customCacheKey) {
|
||||||
|
$.info(`URL ${url}\n写入自定义缓存 ${$arguments?.cacheKey}`);
|
||||||
|
$.write(cached, customCacheKey);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
|
const insecure = $arguments?.insecure
|
||||||
|
? isNode
|
||||||
|
? { strictSSL: false }
|
||||||
|
: { insecure: true }
|
||||||
|
: undefined;
|
||||||
$.info(
|
$.info(
|
||||||
`Downloading...\nUser-Agent: ${userAgent}\nTimeout: ${requestTimeout}\nProxy: ${proxy}\nURL: ${url}`,
|
`Downloading...\nUser-Agent: ${userAgent}\nTimeout: ${requestTimeout}\nProxy: ${proxy}\nInsecure: ${!!insecure}\nURL: ${url}`,
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
const { body, headers } = await http.get({
|
const { body, headers, statusCode } = await http.get({
|
||||||
url,
|
url,
|
||||||
...(proxy ? { proxy } : {}),
|
...(proxy ? { proxy } : {}),
|
||||||
...(isLoon && proxy ? { node: proxy } : {}),
|
...(isLoon && proxy ? { node: proxy } : {}),
|
||||||
...(isQX && proxy ? { opts: { policy: proxy } } : {}),
|
...(isQX && proxy ? { opts: { policy: proxy } } : {}),
|
||||||
...(proxy ? getPolicyDescriptor(proxy) : {}),
|
...(proxy ? getPolicyDescriptor(proxy) : {}),
|
||||||
|
...(insecure ? insecure : {}),
|
||||||
});
|
});
|
||||||
|
$.info(`statusCode: ${statusCode}`);
|
||||||
|
if (statusCode < 200 || statusCode >= 400) {
|
||||||
|
throw new Error(`statusCode: ${statusCode}`);
|
||||||
|
}
|
||||||
|
|
||||||
if (headers) {
|
if (headers) {
|
||||||
const flowInfo = getFlowField(headers);
|
const flowInfo = getFlowField(headers);
|
||||||
if (flowInfo) {
|
if (flowInfo) {
|
||||||
headersResourceCache.set(url, flowInfo);
|
headersResourceCache.set(id, flowInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (body.replace(/\s/g, '').length === 0)
|
if (body.replace(/\s/g, '').length === 0)
|
||||||
@@ -120,6 +208,9 @@ export default async function download(rawUrl, ua, timeout, proxy) {
|
|||||||
if (shouldCache) {
|
if (shouldCache) {
|
||||||
resourceCache.set(id, body);
|
resourceCache.set(id, body);
|
||||||
if (customCacheKey) {
|
if (customCacheKey) {
|
||||||
|
$.info(
|
||||||
|
`URL ${url}\n写入自定义缓存 ${$arguments?.cacheKey}`,
|
||||||
|
);
|
||||||
$.write(body, customCacheKey);
|
$.write(body, customCacheKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -151,6 +242,7 @@ export default async function download(rawUrl, ua, timeout, proxy) {
|
|||||||
$arguments.flowUserAgent,
|
$arguments.flowUserAgent,
|
||||||
undefined,
|
undefined,
|
||||||
proxy,
|
proxy,
|
||||||
|
$arguments.flowUrl,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ const {
|
|||||||
isShadowRocket,
|
isShadowRocket,
|
||||||
isLanceX,
|
isLanceX,
|
||||||
isEgern,
|
isEgern,
|
||||||
|
isGUIforCores,
|
||||||
} = ENV();
|
} = ENV();
|
||||||
let backend = 'Node';
|
let backend = 'Node';
|
||||||
if (isNode) backend = 'Node';
|
if (isNode) backend = 'Node';
|
||||||
@@ -20,8 +21,10 @@ if (isStash) backend = 'Stash';
|
|||||||
if (isShadowRocket) backend = 'ShadowRocket';
|
if (isShadowRocket) backend = 'ShadowRocket';
|
||||||
if (isEgern) backend = 'Egern';
|
if (isEgern) backend = 'Egern';
|
||||||
if (isLanceX) backend = 'LanceX';
|
if (isLanceX) backend = 'LanceX';
|
||||||
|
if (isGUIforCores) backend = 'GUI.for.Cores';
|
||||||
|
|
||||||
let meta = {};
|
let meta = {};
|
||||||
|
let feature = {};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (typeof $environment !== 'undefined') {
|
if (typeof $environment !== 'undefined') {
|
||||||
@@ -36,6 +39,10 @@ try {
|
|||||||
// eslint-disable-next-line no-undef
|
// eslint-disable-next-line no-undef
|
||||||
meta.script = $script;
|
meta.script = $script;
|
||||||
}
|
}
|
||||||
|
if (typeof $Plugin !== 'undefined') {
|
||||||
|
// eslint-disable-next-line no-undef
|
||||||
|
meta.plugin = $Plugin;
|
||||||
|
}
|
||||||
if (isNode) {
|
if (isNode) {
|
||||||
meta.node = {
|
meta.node = {
|
||||||
version: eval('process.version'),
|
version: eval('process.version'),
|
||||||
@@ -57,5 +64,6 @@ try {
|
|||||||
export default {
|
export default {
|
||||||
backend,
|
backend,
|
||||||
version: substoreVersion,
|
version: substoreVersion,
|
||||||
|
feature,
|
||||||
meta,
|
meta,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,17 +1,35 @@
|
|||||||
import { SETTINGS_KEY } from '@/constants';
|
import { SETTINGS_KEY } from '@/constants';
|
||||||
import { HTTP, ENV } from '@/vendor/open-api';
|
import { HTTP, ENV } from '@/vendor/open-api';
|
||||||
|
import { hex_md5 } from '@/vendor/md5';
|
||||||
import { getPolicyDescriptor } from '@/utils';
|
import { getPolicyDescriptor } from '@/utils';
|
||||||
import $ from '@/core/app';
|
import $ from '@/core/app';
|
||||||
import headersResourceCache from '@/utils/headers-resource-cache';
|
import headersResourceCache from '@/utils/headers-resource-cache';
|
||||||
|
|
||||||
export function getFlowField(headers) {
|
export function getFlowField(headers) {
|
||||||
const subkey = Object.keys(headers).filter((k) =>
|
const keys = Object.keys(headers);
|
||||||
/SUBSCRIPTION-USERINFO/i.test(k),
|
let sub = '';
|
||||||
)[0];
|
let webPage = '';
|
||||||
return headers[subkey];
|
for (let k of keys) {
|
||||||
|
const lower = k.toLowerCase();
|
||||||
|
if (lower === 'subscription-userinfo') {
|
||||||
|
sub = headers[k];
|
||||||
|
} else if (lower === 'profile-web-page-url') {
|
||||||
|
webPage = headers[k];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${sub || ''}${
|
||||||
|
webPage ? `; app_url=${encodeURIComponent(webPage)}` : ''
|
||||||
|
}`;
|
||||||
}
|
}
|
||||||
export async function getFlowHeaders(rawUrl, ua, timeout, proxy) {
|
export async function getFlowHeaders(
|
||||||
let url = rawUrl;
|
rawUrl,
|
||||||
|
ua,
|
||||||
|
timeout,
|
||||||
|
customProxy,
|
||||||
|
flowUrl,
|
||||||
|
) {
|
||||||
|
let url = flowUrl || rawUrl || '';
|
||||||
let $arguments = {};
|
let $arguments = {};
|
||||||
const rawArgs = url.split('#');
|
const rawArgs = url.split('#');
|
||||||
url = url.split('#')[0];
|
url = url.split('#')[0];
|
||||||
@@ -35,76 +53,125 @@ export async function getFlowHeaders(rawUrl, ua, timeout, proxy) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { isStash, isLoon, isShadowRocket, isQX } = ENV();
|
const { isStash, isLoon, isShadowRocket, isQX } = ENV();
|
||||||
const cached = headersResourceCache.get(url);
|
const insecure = $arguments?.insecure
|
||||||
|
? $.env.isNode
|
||||||
|
? { strictSSL: false }
|
||||||
|
: { insecure: true }
|
||||||
|
: undefined;
|
||||||
|
const { defaultProxy, defaultFlowUserAgent, defaultTimeout } =
|
||||||
|
$.read(SETTINGS_KEY);
|
||||||
|
let proxy = customProxy || defaultProxy;
|
||||||
|
if ($.env.isNode) {
|
||||||
|
proxy = proxy || eval('process.env.SUB_STORE_BACKEND_DEFAULT_PROXY');
|
||||||
|
}
|
||||||
|
const userAgent = ua || defaultFlowUserAgent || 'clash';
|
||||||
|
const requestTimeout = timeout || defaultTimeout || 8000;
|
||||||
|
const id = hex_md5(userAgent + url);
|
||||||
|
const cached = headersResourceCache.get(id);
|
||||||
let flowInfo;
|
let flowInfo;
|
||||||
if (!$arguments?.noCache && cached) {
|
if (!$arguments?.noCache && cached) {
|
||||||
// $.info(`使用缓存的流量信息: ${url}`);
|
$.info(`使用缓存的流量信息: ${url}, ${userAgent}`);
|
||||||
flowInfo = cached;
|
flowInfo = cached;
|
||||||
} else {
|
} else {
|
||||||
const { defaultFlowUserAgent, defaultTimeout } = $.read(SETTINGS_KEY);
|
|
||||||
const userAgent =
|
|
||||||
ua ||
|
|
||||||
defaultFlowUserAgent ||
|
|
||||||
'Quantumult%20X/1.0.30 (iPhone14,2; iOS 15.6)';
|
|
||||||
const requestTimeout = timeout || defaultTimeout;
|
|
||||||
const http = HTTP();
|
const http = HTTP();
|
||||||
try {
|
if (flowUrl) {
|
||||||
$.info(
|
$.info(
|
||||||
`使用 HEAD 方法获取流量信息: ${url}, User-Agent: ${
|
`使用 GET 方法从响应体获取流量信息: ${flowUrl}, User-Agent: ${
|
||||||
userAgent || ''
|
userAgent || ''
|
||||||
}`,
|
}, Insecure: ${!!insecure}, Proxy: ${proxy}`,
|
||||||
);
|
);
|
||||||
const { headers } = await http.head({
|
const { body } = await http.get({
|
||||||
url: url
|
url: flowUrl,
|
||||||
.split(/[\r\n]+/)
|
|
||||||
.map((i) => i.trim())
|
|
||||||
.filter((i) => i.length)[0],
|
|
||||||
headers: {
|
headers: {
|
||||||
'User-Agent': userAgent,
|
'User-Agent': userAgent,
|
||||||
...(isStash && proxy
|
|
||||||
? {
|
|
||||||
'X-Stash-Selected-Proxy':
|
|
||||||
encodeURIComponent(proxy),
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
...(isShadowRocket && proxy
|
|
||||||
? { 'X-Surge-Policy': proxy }
|
|
||||||
: {}),
|
|
||||||
},
|
},
|
||||||
timeout: requestTimeout,
|
timeout: requestTimeout,
|
||||||
...(proxy ? { proxy } : {}),
|
...(proxy ? { proxy } : {}),
|
||||||
...(isLoon && proxy ? { node: proxy } : {}),
|
...(isLoon && proxy ? { node: proxy } : {}),
|
||||||
...(isQX && proxy ? { opts: { policy: proxy } } : {}),
|
...(isQX && proxy ? { opts: { policy: proxy } } : {}),
|
||||||
...(proxy ? getPolicyDescriptor(proxy) : {}),
|
...(proxy ? getPolicyDescriptor(proxy) : {}),
|
||||||
|
...(insecure ? insecure : {}),
|
||||||
});
|
});
|
||||||
flowInfo = getFlowField(headers);
|
flowInfo = body;
|
||||||
} catch (e) {
|
} else {
|
||||||
$.error(
|
try {
|
||||||
`使用 HEAD 方法获取流量信息失败: ${url}, User-Agent: ${
|
$.info(
|
||||||
userAgent || ''
|
`使用 HEAD 方法从响应头获取流量信息: ${url}, User-Agent: ${
|
||||||
}: ${e.message ?? e}`,
|
userAgent || ''
|
||||||
);
|
}, Insecure: ${!!insecure}, Proxy: ${proxy}`,
|
||||||
}
|
);
|
||||||
if (!flowInfo) {
|
const { headers } = await http.head({
|
||||||
$.info(
|
url: url
|
||||||
`使用 GET 方法获取流量信息: ${url}, User-Agent: ${
|
.split(/[\r\n]+/)
|
||||||
userAgent || ''
|
.map((i) => i.trim())
|
||||||
}`,
|
.filter((i) => i.length)[0],
|
||||||
);
|
headers: {
|
||||||
const { headers } = await http.get({
|
'User-Agent': userAgent,
|
||||||
url: url
|
...(isStash && proxy
|
||||||
.split(/[\r\n]+/)
|
? {
|
||||||
.map((i) => i.trim())
|
'X-Stash-Selected-Proxy':
|
||||||
.filter((i) => i.length)[0],
|
encodeURIComponent(proxy),
|
||||||
headers: {
|
}
|
||||||
'User-Agent': userAgent,
|
: {}),
|
||||||
},
|
...(isShadowRocket && proxy
|
||||||
timeout: requestTimeout,
|
? { 'X-Surge-Policy': proxy }
|
||||||
});
|
: {}),
|
||||||
flowInfo = getFlowField(headers);
|
},
|
||||||
|
timeout: requestTimeout,
|
||||||
|
...(proxy ? { proxy } : {}),
|
||||||
|
...(isLoon && proxy ? { node: proxy } : {}),
|
||||||
|
...(isQX && proxy ? { opts: { policy: proxy } } : {}),
|
||||||
|
...(proxy ? getPolicyDescriptor(proxy) : {}),
|
||||||
|
...(insecure ? insecure : {}),
|
||||||
|
});
|
||||||
|
flowInfo = getFlowField(headers);
|
||||||
|
} catch (e) {
|
||||||
|
$.error(
|
||||||
|
`使用 HEAD 方法从响应头获取流量信息失败: ${url}, User-Agent: ${
|
||||||
|
userAgent || ''
|
||||||
|
}, Insecure: ${!!insecure}, Proxy: ${proxy}: ${
|
||||||
|
e.message ?? e
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!flowInfo) {
|
||||||
|
$.info(
|
||||||
|
`使用 GET 方法获取流量信息: ${url}, User-Agent: ${
|
||||||
|
userAgent || ''
|
||||||
|
}, Insecure: ${!!insecure}, Proxy: ${proxy}`,
|
||||||
|
);
|
||||||
|
const { headers } = await http.get({
|
||||||
|
url: url
|
||||||
|
.split(/[\r\n]+/)
|
||||||
|
.map((i) => i.trim())
|
||||||
|
.filter((i) => i.length)[0],
|
||||||
|
headers: {
|
||||||
|
'User-Agent': userAgent,
|
||||||
|
...(isStash && proxy
|
||||||
|
? {
|
||||||
|
'X-Stash-Selected-Proxy':
|
||||||
|
encodeURIComponent(proxy),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(isShadowRocket && proxy
|
||||||
|
? { 'X-Surge-Policy': proxy }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
timeout: requestTimeout,
|
||||||
|
...(proxy ? { proxy } : {}),
|
||||||
|
...(isLoon && proxy ? { node: proxy } : {}),
|
||||||
|
...(isQX && proxy ? { opts: { policy: proxy } } : {}),
|
||||||
|
...(proxy ? getPolicyDescriptor(proxy) : {}),
|
||||||
|
...(insecure ? insecure : {}),
|
||||||
|
});
|
||||||
|
flowInfo = getFlowField(headers);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (flowInfo) {
|
if (flowInfo) {
|
||||||
headersResourceCache.set(url, flowInfo);
|
flowInfo = flowInfo.trim();
|
||||||
|
}
|
||||||
|
if (flowInfo) {
|
||||||
|
headersResourceCache.set(id, flowInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,8 +202,29 @@ export function parseFlowHeaders(flowHeaders) {
|
|||||||
? Number(expireMatch[1] + expireMatch[2])
|
? Number(expireMatch[1] + expireMatch[2])
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
return { expires, total, usage: { upload, download } };
|
const remainingDaysMatch = flowHeaders.match(/reset_day=([0-9]+)/);
|
||||||
|
const remainingDays = remainingDaysMatch
|
||||||
|
? Number(remainingDaysMatch[1])
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const appUrlMatch = flowHeaders.match(/app_url=(.*?)\s*?(;|$)/);
|
||||||
|
const appUrl = appUrlMatch ? decodeURIComponent(appUrlMatch[1]) : undefined;
|
||||||
|
|
||||||
|
const planNameMatch = flowHeaders.match(/plan_name=(.*?)\s*?(;|$)/);
|
||||||
|
const planName = planNameMatch
|
||||||
|
? decodeURIComponent(planNameMatch[1])
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
return {
|
||||||
|
expires,
|
||||||
|
total,
|
||||||
|
usage: { upload, download },
|
||||||
|
remainingDays,
|
||||||
|
appUrl,
|
||||||
|
planName,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function flowTransfer(flow, unit = 'B') {
|
export function flowTransfer(flow, unit = 'B') {
|
||||||
const unitList = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
const unitList = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
||||||
let unitIndex = unitList.indexOf(unit);
|
let unitIndex = unitList.indexOf(unit);
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import $ from '@/core/app';
|
||||||
|
|
||||||
const ISOFlags = {
|
const ISOFlags = {
|
||||||
'🏳️🌈': ['EXP', 'BAND'],
|
'🏳️🌈': ['EXP', 'BAND'],
|
||||||
'🇸🇱': ['TEST', 'SOS'],
|
'🇸🇱': ['TEST', 'SOS'],
|
||||||
@@ -149,6 +151,7 @@ export function getFlag(name) {
|
|||||||
'滑铁卢',
|
'滑铁卢',
|
||||||
'多伦多',
|
'多伦多',
|
||||||
'Waterloo',
|
'Waterloo',
|
||||||
|
'Toronto',
|
||||||
],
|
],
|
||||||
'🇨🇭': ['Switzerland', '瑞士', '苏黎世', 'Zurich'],
|
'🇨🇭': ['Switzerland', '瑞士', '苏黎世', 'Zurich'],
|
||||||
'🇨🇱': ['Chile', '智利'],
|
'🇨🇱': ['Chile', '智利'],
|
||||||
@@ -243,7 +246,7 @@ export function getFlag(name) {
|
|||||||
'🇮🇪': ['Ireland', '爱尔兰', '愛爾蘭', '都柏林'],
|
'🇮🇪': ['Ireland', '爱尔兰', '愛爾蘭', '都柏林'],
|
||||||
'🇮🇱': ['Israel', '以色列'],
|
'🇮🇱': ['Israel', '以色列'],
|
||||||
'🇮🇲': ['Isle of Man', '马恩岛', '馬恩島'],
|
'🇮🇲': ['Isle of Man', '马恩岛', '馬恩島'],
|
||||||
'🇮🇳': ['India', '印度', '孟买', 'MFumbai'],
|
'🇮🇳': ['India', '印度', '孟买', 'MFumbai', 'Mumbai'],
|
||||||
'🇮🇷': ['Iran', '伊朗'],
|
'🇮🇷': ['Iran', '伊朗'],
|
||||||
'🇮🇸': ['Iceland', '冰岛', '冰島'],
|
'🇮🇸': ['Iceland', '冰岛', '冰島'],
|
||||||
'🇮🇹': ['Italy', '意大利', '義大利', '米兰', 'Nachash'],
|
'🇮🇹': ['Italy', '意大利', '義大利', '米兰', 'Nachash'],
|
||||||
@@ -259,7 +262,14 @@ export function getFlag(name) {
|
|||||||
'🇲🇹': ['Malta', '马耳他'],
|
'🇲🇹': ['Malta', '马耳他'],
|
||||||
'🇲🇽': ['Mexico', '墨西哥'],
|
'🇲🇽': ['Mexico', '墨西哥'],
|
||||||
'🇲🇾': ['Malaysia', '马来', '馬來', '吉隆坡', '大馬'],
|
'🇲🇾': ['Malaysia', '马来', '馬來', '吉隆坡', '大馬'],
|
||||||
'🇳🇱': ['Netherlands', '荷兰', '荷蘭', '尼德蘭', '阿姆斯特丹'],
|
'🇳🇱': [
|
||||||
|
'Netherlands',
|
||||||
|
'荷兰',
|
||||||
|
'荷蘭',
|
||||||
|
'尼德蘭',
|
||||||
|
'阿姆斯特丹',
|
||||||
|
'Amsterdam',
|
||||||
|
],
|
||||||
'🇳🇴': ['Norway', '挪威'],
|
'🇳🇴': ['Norway', '挪威'],
|
||||||
'🇳🇵': ['Nepal', '尼泊尔'],
|
'🇳🇵': ['Nepal', '尼泊尔'],
|
||||||
'🇳🇿': ['New Zealand', '新西兰', '新西蘭'],
|
'🇳🇿': ['New Zealand', '新西兰', '新西蘭'],
|
||||||
@@ -267,7 +277,7 @@ export function getFlag(name) {
|
|||||||
'🇵🇪': ['Peru', '秘鲁', '祕魯'],
|
'🇵🇪': ['Peru', '秘鲁', '祕魯'],
|
||||||
'🇵🇭': ['Philippines', '菲律宾', '菲律賓'],
|
'🇵🇭': ['Philippines', '菲律宾', '菲律賓'],
|
||||||
'🇵🇰': ['Pakistan', '巴基斯坦'],
|
'🇵🇰': ['Pakistan', '巴基斯坦'],
|
||||||
'🇵🇱': ['Poland', '波兰', '波蘭'],
|
'🇵🇱': ['Poland', '波兰', '波蘭', '华沙', 'Warsaw'],
|
||||||
'🇵🇷': ['Puerto Rico', '波多黎各'],
|
'🇵🇷': ['Puerto Rico', '波多黎各'],
|
||||||
'🇵🇹': ['Portugal', '葡萄牙'],
|
'🇵🇹': ['Portugal', '葡萄牙'],
|
||||||
'🇵🇾': ['Paraguay', '巴拉圭'],
|
'🇵🇾': ['Paraguay', '巴拉圭'],
|
||||||
@@ -291,8 +301,8 @@ export function getFlag(name) {
|
|||||||
'沪俄',
|
'沪俄',
|
||||||
'Moscow',
|
'Moscow',
|
||||||
],
|
],
|
||||||
'🇸🇦': ['Saudi', '沙特阿拉伯', '沙特'],
|
'🇸🇦': ['Saudi', '沙特阿拉伯', '沙特', 'Riyadh', '利雅得'],
|
||||||
'🇸🇪': ['Sweden', '瑞典'],
|
'🇸🇪': ['Sweden', '瑞典', '斯德哥尔摩', 'Stockholm'],
|
||||||
'🇸🇬': [
|
'🇸🇬': [
|
||||||
'Singapore',
|
'Singapore',
|
||||||
'新加坡',
|
'新加坡',
|
||||||
@@ -312,7 +322,7 @@ export function getFlag(name) {
|
|||||||
'🇸🇰': ['Slovakia', '斯洛伐克'],
|
'🇸🇰': ['Slovakia', '斯洛伐克'],
|
||||||
'🇹🇭': ['Thailand', '泰国', '泰國', '曼谷'],
|
'🇹🇭': ['Thailand', '泰国', '泰國', '曼谷'],
|
||||||
'🇹🇳': ['Tunisia', '突尼斯'],
|
'🇹🇳': ['Tunisia', '突尼斯'],
|
||||||
'🇹🇷': ['Turkey', '土耳其', '伊斯坦布尔'],
|
'🇹🇷': ['Turkey', '土耳其', '伊斯坦布尔', 'Istanbul'],
|
||||||
'🇹🇼': [
|
'🇹🇼': [
|
||||||
'Taiwan',
|
'Taiwan',
|
||||||
'台湾',
|
'台湾',
|
||||||
@@ -327,6 +337,7 @@ export function getFlag(name) {
|
|||||||
'台',
|
'台',
|
||||||
'臺',
|
'臺',
|
||||||
'Taipei',
|
'Taipei',
|
||||||
|
'Tai Wan',
|
||||||
],
|
],
|
||||||
'🇺🇦': ['Ukraine', '乌克兰', '烏克蘭'],
|
'🇺🇦': ['Ukraine', '乌克兰', '烏克蘭'],
|
||||||
'🇺🇸': [
|
'🇺🇸': [
|
||||||
@@ -338,6 +349,7 @@ export function getFlag(name) {
|
|||||||
'波特兰',
|
'波特兰',
|
||||||
'达拉斯',
|
'达拉斯',
|
||||||
'俄勒冈',
|
'俄勒冈',
|
||||||
|
'Oregon',
|
||||||
'凤凰城',
|
'凤凰城',
|
||||||
'费利蒙',
|
'费利蒙',
|
||||||
'硅谷',
|
'硅谷',
|
||||||
@@ -351,10 +363,17 @@ export function getFlag(name) {
|
|||||||
'沪美',
|
'沪美',
|
||||||
'哥伦布',
|
'哥伦布',
|
||||||
'纽约',
|
'纽约',
|
||||||
|
'New York',
|
||||||
'Los Angeles',
|
'Los Angeles',
|
||||||
'San Jose',
|
'San Jose',
|
||||||
'Sillicon Valley',
|
'Sillicon Valley',
|
||||||
'Michigan',
|
'Michigan',
|
||||||
|
'俄亥俄',
|
||||||
|
'Ohio',
|
||||||
|
'马纳萨斯',
|
||||||
|
'Manassas',
|
||||||
|
'弗吉尼亚',
|
||||||
|
'Virginia',
|
||||||
],
|
],
|
||||||
'🇺🇾': ['Uruguay', '乌拉圭'],
|
'🇺🇾': ['Uruguay', '乌拉圭'],
|
||||||
'🇻🇪': ['Venezuela', '委内瑞拉'],
|
'🇻🇪': ['Venezuela', '委内瑞拉'],
|
||||||
@@ -415,8 +434,12 @@ export function getFlag(name) {
|
|||||||
RegExp(`(^|[^a-zA-Z])${keyword}([^a-zA-Z]|$)`).test(name),
|
RegExp(`(^|[^a-zA-Z])${keyword}([^a-zA-Z]|$)`).test(name),
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
//console.log(`ISOFlag = ${flag}`)
|
const isCN2 =
|
||||||
return (Flag = flag);
|
flag == '🇨🇳' &&
|
||||||
|
RegExp(`(^|[^a-zA-Z])CN2([^a-zA-Z]|$)`).test(name);
|
||||||
|
if (!isCN2) {
|
||||||
|
return (Flag = flag);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -427,3 +450,51 @@ export function getFlag(name) {
|
|||||||
export function getISO(name) {
|
export function getISO(name) {
|
||||||
return ISOFlags[getFlag(name)]?.[0];
|
return ISOFlags[getFlag(name)]?.[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// remove flag
|
||||||
|
export function removeFlag(str) {
|
||||||
|
return str
|
||||||
|
.replace(/[\uD83C][\uDDE6-\uDDFF][\uD83C][\uDDE6-\uDDFF]|🏴☠️|🏳️🌈/g, '')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MMDB {
|
||||||
|
constructor({ country, asn } = {}) {
|
||||||
|
if ($.env.isNode) {
|
||||||
|
const Reader = eval(`require("@maxmind/geoip2-node")`).Reader;
|
||||||
|
const fs = eval("require('fs')");
|
||||||
|
const countryFile =
|
||||||
|
country || eval('process.env.SUB_STORE_MMDB_COUNTRY_PATH');
|
||||||
|
const asnFile = asn || eval('process.env.SUB_STORE_MMDB_ASN_PATH');
|
||||||
|
// $.info(
|
||||||
|
// `GeoLite2 Country MMDB: ${countryFile}, exists: ${fs.existsSync(
|
||||||
|
// countryFile,
|
||||||
|
// )}`,
|
||||||
|
// );
|
||||||
|
if (countryFile) {
|
||||||
|
this.countryReader = Reader.openBuffer(
|
||||||
|
fs.readFileSync(countryFile),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// $.info(
|
||||||
|
// `GeoLite2 ASN MMDB: ${asnFile}, exists: ${fs.existsSync(
|
||||||
|
// asnFile,
|
||||||
|
// )}`,
|
||||||
|
// );
|
||||||
|
if (asnFile) {
|
||||||
|
if (!fs.existsSync(asnFile))
|
||||||
|
throw new Error('GeoLite2 ASN MMDB does not exist');
|
||||||
|
this.asnReader = Reader.openBuffer(fs.readFileSync(asnFile));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
geoip(ip) {
|
||||||
|
return this.countryReader?.country(ip)?.country?.isoCode;
|
||||||
|
}
|
||||||
|
ipaso(ip) {
|
||||||
|
return this.asnReader?.asn(ip)?.autonomousSystemOrganization;
|
||||||
|
}
|
||||||
|
ipasn(ip) {
|
||||||
|
return this.asnReader?.asn(ip)?.autonomousSystemNumber;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,10 +1,21 @@
|
|||||||
import { HTTP } from '@/vendor/open-api';
|
import { HTTP, ENV } from '@/vendor/open-api';
|
||||||
|
import { getPolicyDescriptor } from '@/utils';
|
||||||
|
import $ from '@/core/app';
|
||||||
|
import { SETTINGS_KEY } from '@/constants';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gist backup
|
* Gist backup
|
||||||
*/
|
*/
|
||||||
export default class Gist {
|
export default class Gist {
|
||||||
constructor({ token, key, syncPlatform }) {
|
constructor({ token, key, syncPlatform }) {
|
||||||
|
const { isStash, isLoon, isShadowRocket, isQX } = ENV();
|
||||||
|
const { defaultProxy, defaultTimeout: timeout } = $.read(SETTINGS_KEY);
|
||||||
|
let proxy = defaultProxy;
|
||||||
|
if ($.env.isNode) {
|
||||||
|
proxy =
|
||||||
|
proxy || eval('process.env.SUB_STORE_BACKEND_DEFAULT_PROXY');
|
||||||
|
}
|
||||||
|
|
||||||
if (syncPlatform === 'gitlab') {
|
if (syncPlatform === 'gitlab') {
|
||||||
this.headers = {
|
this.headers = {
|
||||||
'PRIVATE-TOKEN': `${token}`,
|
'PRIVATE-TOKEN': `${token}`,
|
||||||
@@ -13,7 +24,25 @@ export default class Gist {
|
|||||||
};
|
};
|
||||||
this.http = HTTP({
|
this.http = HTTP({
|
||||||
baseURL: 'https://gitlab.com/api/v4',
|
baseURL: 'https://gitlab.com/api/v4',
|
||||||
headers: { ...this.headers },
|
headers: {
|
||||||
|
...this.headers,
|
||||||
|
...(isStash && proxy
|
||||||
|
? {
|
||||||
|
'X-Stash-Selected-Proxy':
|
||||||
|
encodeURIComponent(proxy),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(isShadowRocket && proxy
|
||||||
|
? { 'X-Surge-Policy': proxy }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
|
||||||
|
...(proxy ? { proxy } : {}),
|
||||||
|
...(isLoon && proxy ? { node: proxy } : {}),
|
||||||
|
...(isQX && proxy ? { opts: { policy: proxy } } : {}),
|
||||||
|
...(proxy ? getPolicyDescriptor(proxy) : {}),
|
||||||
|
timeout: timeout || 8000,
|
||||||
|
|
||||||
events: {
|
events: {
|
||||||
onResponse: (resp) => {
|
onResponse: (resp) => {
|
||||||
if (/^[45]/.test(String(resp.statusCode))) {
|
if (/^[45]/.test(String(resp.statusCode))) {
|
||||||
@@ -35,7 +64,25 @@ export default class Gist {
|
|||||||
};
|
};
|
||||||
this.http = HTTP({
|
this.http = HTTP({
|
||||||
baseURL: 'https://api.github.com',
|
baseURL: 'https://api.github.com',
|
||||||
headers: { ...this.headers },
|
headers: {
|
||||||
|
...this.headers,
|
||||||
|
...(isStash && proxy
|
||||||
|
? {
|
||||||
|
'X-Stash-Selected-Proxy':
|
||||||
|
encodeURIComponent(proxy),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(isShadowRocket && proxy
|
||||||
|
? { 'X-Surge-Policy': proxy }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
|
||||||
|
...(proxy ? { proxy } : {}),
|
||||||
|
...(isLoon && proxy ? { node: proxy } : {}),
|
||||||
|
...(isQX && proxy ? { opts: { policy: proxy } } : {}),
|
||||||
|
...(proxy ? getPolicyDescriptor(proxy) : {}),
|
||||||
|
timeout: timeout || 8000,
|
||||||
|
|
||||||
events: {
|
events: {
|
||||||
onResponse: (resp) => {
|
onResponse: (resp) => {
|
||||||
if (/^[45]/.test(String(resp.statusCode))) {
|
if (/^[45]/.test(String(resp.statusCode))) {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import * as ipAddress from 'ip-address';
|
||||||
// source: https://stackoverflow.com/a/36760050
|
// source: https://stackoverflow.com/a/36760050
|
||||||
const IPV4_REGEX = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$/;
|
const IPV4_REGEX = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$/;
|
||||||
|
|
||||||
@@ -46,54 +47,78 @@ function getPolicyDescriptor(str) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const utf8ArrayToStr =
|
// const utf8ArrayToStr =
|
||||||
typeof TextDecoder !== 'undefined'
|
// typeof TextDecoder !== 'undefined'
|
||||||
? (v) => new TextDecoder().decode(new Uint8Array(v))
|
// ? (v) => new TextDecoder().decode(new Uint8Array(v))
|
||||||
: (function () {
|
// : (function () {
|
||||||
var charCache = new Array(128); // Preallocate the cache for the common single byte chars
|
// var charCache = new Array(128); // Preallocate the cache for the common single byte chars
|
||||||
var charFromCodePt = String.fromCodePoint || String.fromCharCode;
|
// var charFromCodePt = String.fromCodePoint || String.fromCharCode;
|
||||||
var result = [];
|
// var result = [];
|
||||||
|
|
||||||
return function (array) {
|
// return function (array) {
|
||||||
var codePt, byte1;
|
// var codePt, byte1;
|
||||||
var buffLen = array.length;
|
// var buffLen = array.length;
|
||||||
|
|
||||||
result.length = 0;
|
// result.length = 0;
|
||||||
|
|
||||||
for (var i = 0; i < buffLen; ) {
|
// for (var i = 0; i < buffLen; ) {
|
||||||
byte1 = array[i++];
|
// byte1 = array[i++];
|
||||||
|
|
||||||
if (byte1 <= 0x7f) {
|
// if (byte1 <= 0x7f) {
|
||||||
codePt = byte1;
|
// codePt = byte1;
|
||||||
} else if (byte1 <= 0xdf) {
|
// } else if (byte1 <= 0xdf) {
|
||||||
codePt = ((byte1 & 0x1f) << 6) | (array[i++] & 0x3f);
|
// codePt = ((byte1 & 0x1f) << 6) | (array[i++] & 0x3f);
|
||||||
} else if (byte1 <= 0xef) {
|
// } else if (byte1 <= 0xef) {
|
||||||
codePt =
|
// codePt =
|
||||||
((byte1 & 0x0f) << 12) |
|
// ((byte1 & 0x0f) << 12) |
|
||||||
((array[i++] & 0x3f) << 6) |
|
// ((array[i++] & 0x3f) << 6) |
|
||||||
(array[i++] & 0x3f);
|
// (array[i++] & 0x3f);
|
||||||
} else if (String.fromCodePoint) {
|
// } else if (String.fromCodePoint) {
|
||||||
codePt =
|
// codePt =
|
||||||
((byte1 & 0x07) << 18) |
|
// ((byte1 & 0x07) << 18) |
|
||||||
((array[i++] & 0x3f) << 12) |
|
// ((array[i++] & 0x3f) << 12) |
|
||||||
((array[i++] & 0x3f) << 6) |
|
// ((array[i++] & 0x3f) << 6) |
|
||||||
(array[i++] & 0x3f);
|
// (array[i++] & 0x3f);
|
||||||
} else {
|
// } else {
|
||||||
codePt = 63; // Cannot convert four byte code points, so use "?" instead
|
// codePt = 63; // Cannot convert four byte code points, so use "?" instead
|
||||||
i += 3;
|
// i += 3;
|
||||||
}
|
// }
|
||||||
|
|
||||||
result.push(
|
// result.push(
|
||||||
charCache[codePt] ||
|
// charCache[codePt] ||
|
||||||
(charCache[codePt] = charFromCodePt(codePt)),
|
// (charCache[codePt] = charFromCodePt(codePt)),
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
|
|
||||||
return result.join('');
|
// return result.join('');
|
||||||
};
|
// };
|
||||||
})();
|
// })();
|
||||||
|
|
||||||
|
function getRandomInt(min, max) {
|
||||||
|
min = Math.ceil(min);
|
||||||
|
max = Math.floor(max);
|
||||||
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRandomPort(portString) {
|
||||||
|
let portParts = portString.split(/,|\//);
|
||||||
|
let randomPart = portParts[Math.floor(Math.random() * portParts.length)];
|
||||||
|
if (randomPart.includes('-')) {
|
||||||
|
let [min, max] = randomPart.split('-').map(Number);
|
||||||
|
return getRandomInt(min, max);
|
||||||
|
} else {
|
||||||
|
return Number(randomPart);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberToString(value) {
|
||||||
|
return Number.isSafeInteger(value)
|
||||||
|
? String(value)
|
||||||
|
: BigInt(value).toString();
|
||||||
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
ipAddress,
|
||||||
isIPv4,
|
isIPv4,
|
||||||
isIPv6,
|
isIPv6,
|
||||||
isValidPortNumber,
|
isValidPortNumber,
|
||||||
@@ -101,6 +126,8 @@ export {
|
|||||||
getIfNotBlank,
|
getIfNotBlank,
|
||||||
isPresent,
|
isPresent,
|
||||||
getIfPresent,
|
getIfPresent,
|
||||||
utf8ArrayToStr,
|
// utf8ArrayToStr,
|
||||||
getPolicyDescriptor,
|
getPolicyDescriptor,
|
||||||
|
getRandomPort,
|
||||||
|
numberToString,
|
||||||
};
|
};
|
||||||
|
|||||||
11
backend/src/utils/rs.js
Normal file
11
backend/src/utils/rs.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import rs from 'jsrsasign';
|
||||||
|
|
||||||
|
export function generateFingerprint(caStr) {
|
||||||
|
const hex = rs.pemtohex(caStr);
|
||||||
|
const fingerPrint = rs.KJUR.crypto.Util.hashHex(hex, 'sha256');
|
||||||
|
return fingerPrint.match(/.{2}/g).join(':').toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
export default {
|
||||||
|
generateFingerprint,
|
||||||
|
};
|
||||||
@@ -2,18 +2,24 @@ export function getUserAgentFromHeaders(headers) {
|
|||||||
const keys = Object.keys(headers);
|
const keys = Object.keys(headers);
|
||||||
let UA = '';
|
let UA = '';
|
||||||
let ua = '';
|
let ua = '';
|
||||||
|
let accept = '';
|
||||||
for (let k of keys) {
|
for (let k of keys) {
|
||||||
if (/USER-AGENT/i.test(k)) {
|
const lower = k.toLowerCase();
|
||||||
|
if (lower === 'user-agent') {
|
||||||
UA = headers[k];
|
UA = headers[k];
|
||||||
ua = UA.toLowerCase();
|
ua = UA.toLowerCase();
|
||||||
break;
|
} else if (lower === 'accept') {
|
||||||
|
accept = headers[k];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { UA, ua };
|
return { UA, ua, accept };
|
||||||
}
|
}
|
||||||
export function getPlatformFromUserAgent({ ua, UA }) {
|
|
||||||
|
export function getPlatformFromUserAgent({ ua, UA, accept }) {
|
||||||
if (UA.indexOf('Quantumult%20X') !== -1) {
|
if (UA.indexOf('Quantumult%20X') !== -1) {
|
||||||
return 'QX';
|
return 'QX';
|
||||||
|
} else if (ua.indexOf('egern') !== -1) {
|
||||||
|
return 'Egern';
|
||||||
} else if (UA.indexOf('Surfboard') !== -1) {
|
} else if (UA.indexOf('Surfboard') !== -1) {
|
||||||
return 'Surfboard';
|
return 'Surfboard';
|
||||||
} else if (UA.indexOf('Surge Mac') !== -1) {
|
} else if (UA.indexOf('Surge Mac') !== -1) {
|
||||||
@@ -28,7 +34,9 @@ export function getPlatformFromUserAgent({ ua, UA }) {
|
|||||||
return 'Stash';
|
return 'Stash';
|
||||||
} else if (
|
} else if (
|
||||||
ua === 'meta' ||
|
ua === 'meta' ||
|
||||||
(ua.indexOf('clash') !== -1 && ua.indexOf('meta') !== -1)
|
(ua.indexOf('clash') !== -1 && ua.indexOf('meta') !== -1) ||
|
||||||
|
ua.indexOf('clash-verge') !== -1 ||
|
||||||
|
ua.indexOf('flclash') !== -1
|
||||||
) {
|
) {
|
||||||
return 'ClashMeta';
|
return 'ClashMeta';
|
||||||
} else if (ua.indexOf('clash') !== -1) {
|
} else if (ua.indexOf('clash') !== -1) {
|
||||||
@@ -37,11 +45,14 @@ export function getPlatformFromUserAgent({ ua, UA }) {
|
|||||||
return 'V2Ray';
|
return 'V2Ray';
|
||||||
} else if (ua.indexOf('sing-box') !== -1) {
|
} else if (ua.indexOf('sing-box') !== -1) {
|
||||||
return 'sing-box';
|
return 'sing-box';
|
||||||
} else {
|
} else if (accept.indexOf('application/json') === 0) {
|
||||||
return 'JSON';
|
return 'JSON';
|
||||||
|
} else {
|
||||||
|
return 'V2Ray';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getPlatformFromHeaders(headers) {
|
export function getPlatformFromHeaders(headers) {
|
||||||
const { UA, ua } = getUserAgentFromHeaders(headers);
|
const { UA, ua, accept } = getUserAgentFromHeaders(headers);
|
||||||
return getPlatformFromUserAgent({ ua, UA });
|
return getPlatformFromUserAgent({ ua, UA, accept });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,16 +17,16 @@ function retry(fn, content, ...args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function safeLoad(content, ...args) {
|
export function safeLoad(content, ...args) {
|
||||||
return retry(YAML.safeLoad, content, ...args);
|
return retry(YAML.safeLoad, JSON.parse(JSON.stringify(content)), ...args);
|
||||||
}
|
}
|
||||||
export function load(content, ...args) {
|
export function load(content, ...args) {
|
||||||
return retry(YAML.load, content, ...args);
|
return retry(YAML.load, JSON.parse(JSON.stringify(content)), ...args);
|
||||||
}
|
}
|
||||||
export function safeDump(...args) {
|
export function safeDump(content, ...args) {
|
||||||
return YAML.safeDump(...args);
|
return YAML.safeDump(JSON.parse(JSON.stringify(content)), ...args);
|
||||||
}
|
}
|
||||||
export function dump(...args) {
|
export function dump(content, ...args) {
|
||||||
return YAML.dump(...args);
|
return YAML.dump(JSON.parse(JSON.stringify(content)), ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
|
|||||||
5
backend/src/vendor/express.js
vendored
5
backend/src/vendor/express.js
vendored
@@ -9,6 +9,7 @@ export default function express({ substore: $, port, host }) {
|
|||||||
'Access-Control-Allow-Methods': 'POST,GET,OPTIONS,PATCH,PUT,DELETE',
|
'Access-Control-Allow-Methods': 'POST,GET,OPTIONS,PATCH,PUT,DELETE',
|
||||||
'Access-Control-Allow-Headers':
|
'Access-Control-Allow-Headers':
|
||||||
'Origin, X-Requested-With, Content-Type, Accept',
|
'Origin, X-Requested-With, Content-Type, Accept',
|
||||||
|
'X-Powered-By': 'Sub-Store',
|
||||||
};
|
};
|
||||||
|
|
||||||
// node support
|
// node support
|
||||||
@@ -161,7 +162,7 @@ export default function express({ substore: $, port, host }) {
|
|||||||
|
|
||||||
function Response() {
|
function Response() {
|
||||||
let statusCode = 200;
|
let statusCode = 200;
|
||||||
const { isQX, isLoon, isSurge } = ENV();
|
const { isQX, isLoon, isSurge, isGUIforCores } = ENV();
|
||||||
const headers = DEFAULT_HEADERS;
|
const headers = DEFAULT_HEADERS;
|
||||||
const STATUS_CODE_MAP = {
|
const STATUS_CODE_MAP = {
|
||||||
200: 'HTTP/1.1 200 OK',
|
200: 'HTTP/1.1 200 OK',
|
||||||
@@ -184,7 +185,7 @@ export default function express({ substore: $, port, host }) {
|
|||||||
body,
|
body,
|
||||||
headers,
|
headers,
|
||||||
};
|
};
|
||||||
if (isQX) {
|
if (isQX || isGUIforCores) {
|
||||||
$done(response);
|
$done(response);
|
||||||
} else if (isLoon || isSurge) {
|
} else if (isLoon || isSurge) {
|
||||||
$done({
|
$done({
|
||||||
|
|||||||
51
backend/src/vendor/open-api.js
vendored
51
backend/src/vendor/open-api.js
vendored
@@ -8,6 +8,7 @@ const isStash =
|
|||||||
const isShadowRocket = 'undefined' !== typeof $rocket;
|
const isShadowRocket = 'undefined' !== typeof $rocket;
|
||||||
const isEgern = 'object' == typeof egern;
|
const isEgern = 'object' == typeof egern;
|
||||||
const isLanceX = 'undefined' != typeof $native;
|
const isLanceX = 'undefined' != typeof $native;
|
||||||
|
const isGUIforCores = typeof $Plugins !== 'undefined';
|
||||||
|
|
||||||
export class OpenAPI {
|
export class OpenAPI {
|
||||||
constructor(name = 'untitled', debug = false) {
|
constructor(name = 'untitled', debug = false) {
|
||||||
@@ -48,7 +49,10 @@ export class OpenAPI {
|
|||||||
this.cache = JSON.parse($prefs.valueForKey(this.name) || '{}');
|
this.cache = JSON.parse($prefs.valueForKey(this.name) || '{}');
|
||||||
if (isLoon || isSurge)
|
if (isLoon || isSurge)
|
||||||
this.cache = JSON.parse($persistentStore.read(this.name) || '{}');
|
this.cache = JSON.parse($persistentStore.read(this.name) || '{}');
|
||||||
|
if (isGUIforCores)
|
||||||
|
this.cache = JSON.parse(
|
||||||
|
$Plugins.SubStoreCache.get(this.name) || '{}',
|
||||||
|
);
|
||||||
if (isNode) {
|
if (isNode) {
|
||||||
// create a json for root cache
|
// create a json for root cache
|
||||||
const basePath =
|
const basePath =
|
||||||
@@ -86,6 +90,7 @@ export class OpenAPI {
|
|||||||
const data = JSON.stringify(this.cache, null, 2);
|
const data = JSON.stringify(this.cache, null, 2);
|
||||||
if (isQX) $prefs.setValueForKey(data, this.name);
|
if (isQX) $prefs.setValueForKey(data, this.name);
|
||||||
if (isLoon || isSurge) $persistentStore.write(data, this.name);
|
if (isLoon || isSurge) $persistentStore.write(data, this.name);
|
||||||
|
if (isGUIforCores) $Plugins.SubStoreCache.set(this.name, data);
|
||||||
if (isNode) {
|
if (isNode) {
|
||||||
const basePath =
|
const basePath =
|
||||||
eval('process.env.SUB_STORE_DATA_BASE_PATH') || '.';
|
eval('process.env.SUB_STORE_DATA_BASE_PATH') || '.';
|
||||||
@@ -118,6 +123,9 @@ export class OpenAPI {
|
|||||||
if (isNode) {
|
if (isNode) {
|
||||||
this.root[key] = data;
|
this.root[key] = data;
|
||||||
}
|
}
|
||||||
|
if (isGUIforCores) {
|
||||||
|
return $Plugins.SubStoreCache.set(key, data);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
this.cache[key] = data;
|
this.cache[key] = data;
|
||||||
}
|
}
|
||||||
@@ -137,6 +145,9 @@ export class OpenAPI {
|
|||||||
if (isNode) {
|
if (isNode) {
|
||||||
return this.root[key];
|
return this.root[key];
|
||||||
}
|
}
|
||||||
|
if (isGUIforCores) {
|
||||||
|
return $Plugins.SubStoreCache.get(key);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
return this.cache[key];
|
return this.cache[key];
|
||||||
}
|
}
|
||||||
@@ -155,6 +166,9 @@ export class OpenAPI {
|
|||||||
if (isNode) {
|
if (isNode) {
|
||||||
delete this.root[key];
|
delete this.root[key];
|
||||||
}
|
}
|
||||||
|
if (isGUIforCores) {
|
||||||
|
return $Plugins.SubStoreCache.remove(key);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
delete this.cache[key];
|
delete this.cache[key];
|
||||||
}
|
}
|
||||||
@@ -220,6 +234,9 @@ export class OpenAPI {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (isGUIforCores) {
|
||||||
|
$Plugins.Notify(title, subtitle + '\n' + content);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// other helper functions
|
// other helper functions
|
||||||
@@ -240,7 +257,7 @@ export class OpenAPI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
done(value = {}) {
|
done(value = {}) {
|
||||||
if (isQX || isLoon || isSurge) {
|
if (isQX || isLoon || isSurge || isGUIforCores) {
|
||||||
$done(value);
|
$done(value);
|
||||||
} else if (isNode) {
|
} else if (isNode) {
|
||||||
if (typeof $context !== 'undefined') {
|
if (typeof $context !== 'undefined') {
|
||||||
@@ -262,11 +279,12 @@ export function ENV() {
|
|||||||
isShadowRocket,
|
isShadowRocket,
|
||||||
isEgern,
|
isEgern,
|
||||||
isLanceX,
|
isLanceX,
|
||||||
|
isGUIforCores,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function HTTP(defaultOptions = { baseURL: '' }) {
|
export function HTTP(defaultOptions = { baseURL: '' }) {
|
||||||
const { isQX, isLoon, isSurge, isNode } = ENV();
|
const { isQX, isLoon, isSurge, isNode, isGUIforCores } = ENV();
|
||||||
const methods = [
|
const methods = [
|
||||||
'GET',
|
'GET',
|
||||||
'POST',
|
'POST',
|
||||||
@@ -323,7 +341,10 @@ export function HTTP(defaultOptions = { baseURL: '' }) {
|
|||||||
const request = isNode
|
const request = isNode
|
||||||
? eval("require('request')")
|
? eval("require('request')")
|
||||||
: $httpClient;
|
: $httpClient;
|
||||||
|
const body = options.body;
|
||||||
const opts = JSON.parse(JSON.stringify(options));
|
const opts = JSON.parse(JSON.stringify(options));
|
||||||
|
opts.body = body;
|
||||||
|
|
||||||
if (!isNode && opts.timeout) {
|
if (!isNode && opts.timeout) {
|
||||||
opts.timeout++;
|
opts.timeout++;
|
||||||
let unit = 'ms';
|
let unit = 'ms';
|
||||||
@@ -356,6 +377,30 @@ export function HTTP(defaultOptions = { baseURL: '' }) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
} else if (isGUIforCores) {
|
||||||
|
worker = new Promise(async (resolve, reject) => {
|
||||||
|
try {
|
||||||
|
const response = await $Plugins.Requests({
|
||||||
|
method,
|
||||||
|
url: options.url,
|
||||||
|
headers: options.headers,
|
||||||
|
body: options.body,
|
||||||
|
options: {
|
||||||
|
Proxy: options.proxy,
|
||||||
|
Timeout: options.timeout
|
||||||
|
? options.timeout / 1000
|
||||||
|
: 15,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
resolve({
|
||||||
|
statusCode: response.status,
|
||||||
|
headers: response.headers,
|
||||||
|
body: response.body,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let timeoutid;
|
let timeoutid;
|
||||||
|
|||||||
38
config/Egern.yaml
Normal file
38
config/Egern.yaml
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
name: Sub-Store
|
||||||
|
description: '支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * *'
|
||||||
|
compat_arguments:
|
||||||
|
ability: http-client-policy
|
||||||
|
cronexp: 55 23 * * *
|
||||||
|
sync: '"Sub-Store Sync"'
|
||||||
|
timeout: '120'
|
||||||
|
engine: auto
|
||||||
|
produce: '"# Sub-Store Produce"'
|
||||||
|
produce_cronexp: 50 */6 * * *
|
||||||
|
produce_sub: '"sub1,sub2"'
|
||||||
|
produce_col: '"col1,col2"'
|
||||||
|
compat_arguments_desc: '\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 ''同步'' 或 ''同步配置''\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n脚本超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存\n\n6️⃣ produce\n\n自定义处理订阅的定时任务名\n一般用于定时处理耗时较长的订阅, 以更新缓存\n这样 Surge 中拉取的时候就能用到缓存, 不至于总是超时\n若设为 # 可取消此定时任务\n默认不开启\n\n7️⃣ produce_cronexp\n\n配置处理订阅的定时任务\n\n默认为每 6 小时\n\n9️⃣ produce_sub\n\n自定义需定时处理的单条订阅名\n多个用 , 连接\n\n🔟 produce_col\n\n自定义需定时处理的组合订阅名\n多个用 , 连接\n\n⚠️ 注意: 是 名称(name) 不是 显示名称(displayName)\n如果名称需要编码, 请编码后再用 , 连接\n顺序: 并发执行单条订阅, 然后并发执行组合订阅'
|
||||||
|
scriptings:
|
||||||
|
- http_request:
|
||||||
|
name: Sub-Store Core
|
||||||
|
match: ^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info)))
|
||||||
|
script_url: https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-1.min.js
|
||||||
|
body_required: true
|
||||||
|
- http_request:
|
||||||
|
name: Sub-Store Simple
|
||||||
|
match: ^https?:\/\/sub\.store
|
||||||
|
script_url: https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-0.min.js
|
||||||
|
body_required: true
|
||||||
|
- schedule:
|
||||||
|
name: '{{{sync}}}'
|
||||||
|
cron: '{{{cronexp}}}'
|
||||||
|
script_url: https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js
|
||||||
|
- schedule:
|
||||||
|
name: '{{{produce}}}'
|
||||||
|
cron: '{{{produce_cronexp}}}'
|
||||||
|
script_url: https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js
|
||||||
|
arguments:
|
||||||
|
_compat.$argument: '"sub={{{produce_sub}}}&col={{{produce_col}}}"'
|
||||||
|
mitm:
|
||||||
|
hostnames:
|
||||||
|
includes:
|
||||||
|
- sub.store
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#!name=Sub-Store
|
#!name=Sub-Store
|
||||||
#!desc=高级订阅管理工具. 定时任务默认为每天 23 点 55 分
|
#!desc=高级订阅管理工具. 定时任务默认为每天 23 点 55 分. 定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'
|
||||||
#!openUrl=https://sub.store
|
#!openUrl=https://sub.store
|
||||||
#!author=Peng-YM
|
#!author=Peng-YM
|
||||||
#!homepage=https://github.com/sub-store-org/Sub-Store
|
#!homepage=https://github.com/sub-store-org/Sub-Store
|
||||||
@@ -14,7 +14,7 @@ DOMAIN,sub-store.vercel.app,PROXY
|
|||||||
hostname=sub.store
|
hostname=sub.store
|
||||||
|
|
||||||
[Script]
|
[Script]
|
||||||
http-request ^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))) script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js, requires-body=true, timeout=120, tag=Sub-Store Core
|
http-request ^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))) script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-1.min.js, requires-body=true, timeout=120, tag=Sub-Store Core
|
||||||
http-request ^https?:\/\/sub\.store script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js, requires-body=true, timeout=120, tag=Sub-Store Simple
|
http-request ^https?:\/\/sub\.store script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-0.min.js, requires-body=true, timeout=120, tag=Sub-Store Simple
|
||||||
|
|
||||||
cron "55 23 * * *" script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js, timeout=120, tag=Sub-Store Sync
|
cron "55 23 * * *" script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js, timeout=120, tag=Sub-Store Sync
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "Sub-Store",
|
"name": "Sub-Store",
|
||||||
"description": "定时任务默认为每天 23 点 55 分",
|
"description": "定时任务默认为每天 23 点 55 分. 定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'",
|
||||||
"task": [
|
"task": [
|
||||||
"55 23 * * * https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js, tag=Sub-Store Sync, img-url=https://raw.githubusercontent.com/58xinian/icon/master/Sub-Store1.png"
|
"55 23 * * * https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js, tag=Sub-Store Sync, img-url=https://raw.githubusercontent.com/58xinian/icon/master/Sub-Store1.png"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
hostname=sub.store
|
hostname=sub.store
|
||||||
|
|
||||||
^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))) url script-analyze-echo-response https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js
|
^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))) url script-analyze-echo-response https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-1.min.js
|
||||||
^https?:\/\/sub\.store url script-analyze-echo-response https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js
|
^https?:\/\/sub\.store url script-analyze-echo-response https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-0.min.js
|
||||||
@@ -6,17 +6,29 @@ Sub-Store Releases: [`https://github.com/sub-store-org/Sub-Store/releases`](http
|
|||||||
|
|
||||||
Telegram 频道: [`https://t.me/cool_scripts` ](https://t.me/cool_scripts)
|
Telegram 频道: [`https://t.me/cool_scripts` ](https://t.me/cool_scripts)
|
||||||
|
|
||||||
## 脚本配置:
|
## 服务器/云平台/Docker/Android 版
|
||||||
|
|
||||||
|
https://xream.notion.site/Sub-Store-abe6a96944724dc6a36833d5c9ab7c87
|
||||||
|
|
||||||
|
## App 版
|
||||||
|
|
||||||
### 1. Loon
|
### 1. Loon
|
||||||
安装使用 插件 [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Loon.plugin`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Loon.plugin) 即可。
|
安装使用 插件 [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Loon.plugin`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Loon.plugin) 即可。
|
||||||
|
|
||||||
### 2. Surge
|
### 2. Surge
|
||||||
|
|
||||||
|
#### 关于 Surge 的格外说明
|
||||||
|
|
||||||
|
Surge Mac 版如何支持 SSR, 如何去除 HTTP 传输层以支持 类似 VMess HTTP 节点等 请查看 [链接参数说明](https://github.com/sub-store-org/Sub-Store/wiki/%E9%93%BE%E6%8E%A5%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E)
|
||||||
|
|
||||||
|
定时处理订阅 功能, 避免 App 内拉取超时, 请查看 [定时处理订阅](https://t.me/zhetengsha/1449)
|
||||||
|
|
||||||
0. 最新 Surge iOS TestFlight 版本 可使用 Beta 版(支持最新 Surge iOS TestFlight 版本的特性): [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Beta.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Beta.sgmodule)
|
0. 最新 Surge iOS TestFlight 版本 可使用 Beta 版(支持最新 Surge iOS TestFlight 版本的特性): [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Beta.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Beta.sgmodule)
|
||||||
|
|
||||||
1. 官方默认版模块(支持 App 内使用编辑参数): [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge.sgmodule)
|
1. 官方默认版模块(支持 App 内使用编辑参数): [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge.sgmodule)
|
||||||
|
|
||||||
|
> 最新版 Surge 已删除 `ability: http-client-policy` 参数, 模块暂不做修改, 对测落地功能无影响
|
||||||
|
|
||||||
2. 经典版, 不支持编辑参数, 固定带 ability 参数版本, 使用 jsc 引擎时, 可能会爆内存, 如果需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 请使用此带 ability 参数版本: [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-ability.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-ability.sgmodule)
|
2. 经典版, 不支持编辑参数, 固定带 ability 参数版本, 使用 jsc 引擎时, 可能会爆内存, 如果需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 请使用此带 ability 参数版本: [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-ability.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-ability.sgmodule)
|
||||||
|
|
||||||
3. 经典版, 不支持编辑参数, 固定不带 ability 参数版本: [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Noability.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Noability.sgmodule)
|
3. 经典版, 不支持编辑参数, 固定不带 ability 参数版本: [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Noability.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Noability.sgmodule)
|
||||||
@@ -31,9 +43,20 @@ Telegram 频道: [`https://t.me/cool_scripts` ](https://t.me/cool_scripts)
|
|||||||
安装使用 覆写 [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Stash.stoverride`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Stash.stoverride) 即可。
|
安装使用 覆写 [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Stash.stoverride`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Stash.stoverride) 即可。
|
||||||
|
|
||||||
### 5. Shadowrocket
|
### 5. Shadowrocket
|
||||||
安装使用 模块 [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge.sgmodule) 即可。
|
安装使用 模块 [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Noability.sgmodule`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Surge-Noability.sgmodule) 即可。
|
||||||
|
|
||||||
|
### 6. Egern
|
||||||
|
安装使用 模块 [`https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Egern.yaml`](https://raw.githubusercontent.com/sub-store-org/Sub-Store/master/config/Egern.yaml) 即可。
|
||||||
|
|
||||||
## 使用 Sub-Store
|
## 使用 Sub-Store
|
||||||
1. 使用 Safari 打开这个 https://sub.store 如网页正常打开并且未弹出任何错误提示,说明 Sub-Store 已经配置成功。
|
1. 使用 Safari 打开这个 https://sub.store 如网页正常打开并且未弹出任何错误提示,说明 Sub-Store 已经配置成功。
|
||||||
2. 可以把 Sub-Store 添加到主屏幕,即可获得类似于 APP 的使用体验。
|
2. 可以把 Sub-Store 添加到主屏幕,即可获得类似于 APP 的使用体验。
|
||||||
3. 更详细的使用指南请参考[文档](https://www.notion.so/Sub-Store-6259586994d34c11a4ced5c406264b46)。
|
3. 更详细的使用指南请参考[文档](https://www.notion.so/Sub-Store-6259586994d34c11a4ced5c406264b46)。
|
||||||
|
|
||||||
|
## 链接参数说明
|
||||||
|
|
||||||
|
https://github.com/sub-store-org/Sub-Store/wiki/%E9%93%BE%E6%8E%A5%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E
|
||||||
|
|
||||||
|
## 脚本使用说明
|
||||||
|
|
||||||
|
https://github.com/sub-store-org/Sub-Store/wiki/%E8%84%9A%E6%9C%AC%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
name: Sub-Store
|
name: Sub-Store
|
||||||
desc: 高级订阅管理工具 @Peng-YM. 定时任务默认为每天 23 点 55 分
|
desc: 高级订阅管理工具 @Peng-YM. 定时任务默认为每天 23 点 55 分. 定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'
|
||||||
icon: https://raw.githubusercontent.com/cc63/ICON/main/Sub-Store.png
|
icon: https://raw.githubusercontent.com/cc63/ICON/main/Sub-Store.png
|
||||||
|
|
||||||
http:
|
http:
|
||||||
@@ -25,13 +25,13 @@ cron:
|
|||||||
|
|
||||||
script-providers:
|
script-providers:
|
||||||
sub-store-0:
|
sub-store-0:
|
||||||
url: https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js
|
url: https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-0.min.js
|
||||||
interval: 86400
|
interval: 86400
|
||||||
|
|
||||||
sub-store-1:
|
sub-store-1:
|
||||||
url: https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js
|
url: https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-1.min.js
|
||||||
interval: 86400
|
interval: 86400
|
||||||
|
|
||||||
cron-sync-artifacts:
|
cron-sync-artifacts:
|
||||||
url: https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js
|
url: https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js
|
||||||
interval: 86400
|
interval: 86400
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
#!name=Sub-Store(β)
|
#!name=Sub-Store(β)
|
||||||
#!desc=支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * *
|
#!desc=支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * *
|
||||||
#!category=订阅管理
|
#!category=订阅管理
|
||||||
#!arguments=ability:http-client-policy,cronexp:55 23 * * *,sync:"Sub-Store Sync",timeout:120,engine:auto
|
#!arguments=ability:http-client-policy,cronexp:55 23 * * *,sync:"Sub-Store Sync",timeout:120,engine:auto,produce:"# Sub-Store Produce",produce_cronexp:50 */6 * * *,produce_sub:"sub1,sub2",produce_col:"col1,col2"
|
||||||
#!arguments-desc=\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存
|
#!arguments-desc=\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n脚本超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存\n\n6️⃣ produce\n\n自定义处理订阅的定时任务名\n一般用于定时处理耗时较长的订阅, 以更新缓存\n这样 Surge 中拉取的时候就能用到缓存, 不至于总是超时\n若设为 # 可取消此定时任务\n默认不开启\n\n7️⃣ produce_cronexp\n\n配置处理订阅的定时任务\n\n默认为每 6 小时\n\n9️⃣ produce_sub\n\n自定义需定时处理的单条订阅名\n多个用 , 连接\n\n🔟 produce_col\n\n自定义需定时处理的组合订阅名\n多个用 , 连接\n\n⚠️ 注意: 是 名称(name) 不是 显示名称(displayName)\n如果名称需要编码, 请编码后再用 , 连接\n顺序: 并发执行单条订阅, 然后并发执行组合订阅
|
||||||
|
|
||||||
[MITM]
|
[MITM]
|
||||||
hostname = %APPEND% sub.store
|
hostname = %APPEND% sub.store
|
||||||
|
|
||||||
[Script]
|
[Script]
|
||||||
Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js,requires-body=true,timeout={{{timeout}}},ability="{{{ability}}}",engine={{{engine}}}
|
Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-1.min.js,requires-body=true,timeout={{{timeout}}},ability="{{{ability}}}",engine={{{engine}}}
|
||||||
|
|
||||||
Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js,requires-body=true,timeout={{{timeout}}},engine={{{engine}}}
|
Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-0.min.js,requires-body=true,timeout={{{timeout}}},engine={{{engine}}}
|
||||||
|
|
||||||
{{{sync}}}=type=cron,cronexp="{{{cronexp}}}",wake-system=1,timeout={{{timeout}}},script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js,engine={{{engine}}}
|
{{{sync}}}=type=cron,cronexp="{{{cronexp}}}",wake-system=1,timeout={{{timeout}}},script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js,engine={{{engine}}}
|
||||||
|
|
||||||
|
{{{produce}}}=type=cron,cronexp="{{{produce_cronexp}}}",wake-system=1,timeout={{{timeout}}},script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js,engine={{{engine}}},argument="sub={{{produce_sub}}}&col={{{produce_col}}}"
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#!name=Sub-Store
|
#!name=Sub-Store
|
||||||
#!desc=高级订阅管理工具 @Peng-YM 无 ability 参数版本,不会爆内存, 如果需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 可以用带 ability 参数. 定时任务默认为每天 23 点 55 分
|
#!desc=高级订阅管理工具 @Peng-YM 无 ability 参数版本,不会爆内存, 如果需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 可以用带 ability 参数. 定时任务默认为每天 23 点 55 分. 定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'
|
||||||
#!category=订阅管理
|
#!category=订阅管理
|
||||||
|
|
||||||
[MITM]
|
[MITM]
|
||||||
@@ -7,7 +7,7 @@ hostname = %APPEND% sub.store
|
|||||||
|
|
||||||
[Script]
|
[Script]
|
||||||
# 主程序 已经去掉 Sub-Store Core 的参数 [,ability=http-client-policy] 不会爆内存,这个参数在 Surge 非常占用内存; 如果不需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 则可以使用此脚本
|
# 主程序 已经去掉 Sub-Store Core 的参数 [,ability=http-client-policy] 不会爆内存,这个参数在 Surge 非常占用内存; 如果不需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 则可以使用此脚本
|
||||||
Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js,requires-body=true,timeout=120
|
Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-1.min.js,requires-body=true,timeout=120
|
||||||
Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js,requires-body=true,timeout=120
|
Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-0.min.js,requires-body=true,timeout=120
|
||||||
|
|
||||||
Sub-Store Sync=type=cron,cronexp=55 23 * * *,wake-system=1,timeout=120,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js
|
Sub-Store Sync=type=cron,cronexp=55 23 * * *,wake-system=1,timeout=120,script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
#!name=Sub-Store
|
#!name=Sub-Store
|
||||||
#!desc=高级订阅管理工具 @Peng-YM 带 ability 参数版本, 使用 jsc 引擎时, 可能会爆内存, 如果不需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 可以用不带 ability 参数版本. 定时任务默认为每天 23 点 55 分
|
#!desc=高级订阅管理工具 @Peng-YM 带 ability 参数版本, 使用 jsc 引擎时, 可能会爆内存, 如果不需要使用指定节点功能 例如[加旗帜脚本或者cname脚本] 可以用不带 ability 参数版本. 定时任务默认为每天 23 点 55 分. 定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'
|
||||||
#!category=订阅管理
|
#!category=订阅管理
|
||||||
|
|
||||||
[MITM]
|
[MITM]
|
||||||
hostname = %APPEND% sub.store
|
hostname = %APPEND% sub.store
|
||||||
|
|
||||||
[Script]
|
[Script]
|
||||||
Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js,requires-body=true,timeout=120,ability=http-client-policy
|
Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-1.min.js,requires-body=true,timeout=120,ability=http-client-policy
|
||||||
Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js,requires-body=true,timeout=120
|
Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-0.min.js,requires-body=true,timeout=120
|
||||||
|
|
||||||
Sub-Store Sync=type=cron,cronexp=55 23 * * *,wake-system=1,timeout=120,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js
|
Sub-Store Sync=type=cron,cronexp=55 23 * * *,wake-system=1,timeout=120,script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
#!name=Sub-Store
|
#!name=Sub-Store
|
||||||
#!desc=支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * *
|
#!desc=支持 Surge 正式版的参数设置功能. 测落地功能 ability: http-client-policy, 同步配置的定时 cronexp: 55 23 * * *
|
||||||
#!category=订阅管理
|
#!category=订阅管理
|
||||||
#!arguments=ability:http-client-policy,cronexp:55 23 * * *,sync:"Sub-Store Sync",timeout:120,engine:auto
|
#!arguments=ability:http-client-policy,cronexp:55 23 * * *,sync:"Sub-Store Sync",timeout:120,engine:auto,produce:"# Sub-Store Produce",produce_cronexp:50 */6 * * *,produce_sub:"sub1,sub2",produce_col:"col1,col2"
|
||||||
#!arguments-desc=\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存
|
#!arguments-desc=\n1️⃣ ability\n\n默认已开启测落地能力\n需要配合脚本操作\n如 https://raw.githubusercontent.com/Keywos/rule/main/cname.js\n填写任意其他值关闭\n\n2️⃣ cronexp\n\n同步配置定时任务\n默认为每天 23 点 55 分\n\n定时任务指定时将订阅/文件上传到私有 Gist. 在前端, 叫做 '同步' 或 '同步配置'\n\n3️⃣ sync\n\n自定义定时任务名\n便于在脚本编辑器中选择\n若设为 # 可取消定时任务\n\n4️⃣ timeout\n\n脚本超时, 单位为秒\n\n5️⃣ engine\n\n默认为自动使用 webview 引擎, 可设为指定 jsc, 但 jsc 容易爆内存\n\n6️⃣ produce\n\n自定义处理订阅的定时任务名\n一般用于定时处理耗时较长的订阅, 以更新缓存\n这样 Surge 中拉取的时候就能用到缓存, 不至于总是超时\n若设为 # 可取消此定时任务\n默认不开启\n\n7️⃣ produce_cronexp\n\n配置处理订阅的定时任务\n\n默认为每 6 小时\n\n9️⃣ produce_sub\n\n自定义需定时处理的单条订阅名\n多个用 , 连接\n\n🔟 produce_col\n\n自定义需定时处理的组合订阅名\n多个用 , 连接\n\n⚠️ 注意: 是 名称(name) 不是 显示名称(displayName)\n如果名称需要编码, 请编码后再用 , 连接\n顺序: 并发执行单条订阅, 然后并发执行组合订阅
|
||||||
|
|
||||||
[MITM]
|
[MITM]
|
||||||
hostname = %APPEND% sub.store
|
hostname = %APPEND% sub.store
|
||||||
|
|
||||||
[Script]
|
[Script]
|
||||||
Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-1.min.js,requires-body=true,timeout={{{timeout}}},ability="{{{ability}}}",engine={{{engine}}}
|
Sub-Store Core=type=http-request,pattern=^https?:\/\/sub\.store\/((download)|api\/(preview|sync|(utils\/node-info))),script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-1.min.js,requires-body=true,timeout={{{timeout}}},ability="{{{ability}}}",engine={{{engine}}}
|
||||||
|
|
||||||
Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/sub-store-0.min.js,requires-body=true,timeout={{{timeout}}},engine={{{engine}}}
|
Sub-Store Simple=type=http-request,pattern=^https?:\/\/sub\.store,script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/sub-store-0.min.js,requires-body=true,timeout={{{timeout}}},engine={{{engine}}}
|
||||||
|
|
||||||
{{{sync}}}=type=cron,cronexp="{{{cronexp}}}",wake-system=1,timeout={{{timeout}}},script-path=https://github.com/sub-store-org/Sub-Store/releases/latest/download/cron-sync-artifacts.min.js,engine={{{engine}}}
|
{{{sync}}}=type=cron,cronexp="{{{cronexp}}}",wake-system=1,timeout={{{timeout}}},script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js,engine={{{engine}}}
|
||||||
|
|
||||||
|
{{{produce}}}=type=cron,cronexp="{{{produce_cronexp}}}",wake-system=1,timeout={{{timeout}}},script-path=https://raw.githubusercontent.com/sub-store-org/Sub-Store/release/cron-sync-artifacts.min.js,engine={{{engine}}},argument="sub={{{produce_sub}}}&col={{{produce_col}}}"
|
||||||
@@ -1,26 +1,49 @@
|
|||||||
function operator(proxies = [], targetPlatform, context) {
|
function operator(proxies = [], targetPlatform, context) {
|
||||||
// 支持快捷操作 不一定要写一个 function
|
// 支持快捷操作 不一定要写一个 function
|
||||||
// 可参考 https://t.me/zhetengsha/970
|
// 可参考 https://t.me/zhetengsha/970
|
||||||
// https://t.me/zhetengsha/1009
|
// https://t.me/zhetengsha/1009
|
||||||
|
|
||||||
|
|
||||||
// proxies 为传入的内部节点数组
|
// proxies 为传入的内部节点数组
|
||||||
// 结构大致参考了 Clash.Meta(mihomo) 有私货
|
|
||||||
// 可在预览界面点击节点查看 JSON 结构 或查看 `target=JSON` 的通用订阅
|
// 可在预览界面点击节点查看 JSON 结构 或查看 `target=JSON` 的通用订阅
|
||||||
// 1. `no-resolve` 为不解析域名
|
// 0. 结构大致参考了 Clash.Meta(mihomo), 可参考 mihomo 的文档, 例如 `xudp`, `smux` 都可以自己设置. 但是有私货, 下面是我能想起来的一些私货
|
||||||
// 2. 域名解析后 会多一个 `resolved` 字段
|
// 1. `_no-resolve` 为不解析域名
|
||||||
// 3. 域名解析后会有`_IPv4`, `_IPv6`, `_IP`(若有多个步骤, 只取第一次成功的 v4 或 v6 数据), `_domain` 字段
|
// 2. 域名解析后 会多一个 `_resolved` 字段, 表示是否解析成功
|
||||||
|
// 3. 域名解析后会有`_IPv4`, `_IPv6`, `_IP`(若有多个步骤, 只取第一次成功的 v4 或 v6 数据), `_IP4P`(若解析类型为 IPv6 且符合 IP4P 类型, 将自动转换), `_domain` 字段, `_resolved_ips` 为解析出的所有 IP
|
||||||
// 4. 节点字段 `exec` 为 `ssr-local` 路径, 默认 `/usr/local/bin/ssr-local`; 端口从 10000 开始递增(暂不支持配置)
|
// 4. 节点字段 `exec` 为 `ssr-local` 路径, 默认 `/usr/local/bin/ssr-local`; 端口从 10000 开始递增(暂不支持配置)
|
||||||
|
// 5. `_subName` 为单条订阅名, `_subDisplayName` 为单条订阅显示名
|
||||||
|
// 6. `_collectionName` 为组合订阅名, `_collectionDisplayName` 为组合订阅显示名
|
||||||
|
// 7. `tls-fingerprint` 为 tls 指纹
|
||||||
|
// 8. `underlying-proxy` 为前置代理
|
||||||
|
// 9. `trojan`, `tuic`, `hysteria`, `hysteria2`, `juicity` 会在解析时设置 `tls`: true (会使用 tls 类协议的通用逻辑), 输出时删除
|
||||||
|
// 10. `sni` 在某些协议里会自动与 `servername` 转换
|
||||||
|
// 11. 读取节点的 ca-str 和 _ca (后端文件路径) 字段, 自动计算 fingerprint (参考 https://t.me/zhetengsha/1512)
|
||||||
|
// 12. 以 Surge 为例, 最新的参数一般我都会跟进, 以 Surge 文档为例, 一些常用的: TUIC/Hysteria 2 的 `ecn`, Snell 的 `reuse` 连接复用, QUIC 策略 block-quic`, Hysteria 2 下载带宽 `down`
|
||||||
|
// 13. `test-url` 为测延迟链接, `test-timeout` 为测延迟超时
|
||||||
|
// 14. `ports` 为端口跳跃, `hop-interval` 变换端口号的时间间隔
|
||||||
|
// 15. `ip-version` 设置节点使用 IP 版本,可选:dual,ipv4,ipv6,ipv4-prefer,ipv6-prefer. 会进行内部转换, 若无法匹配则使用原始值
|
||||||
|
|
||||||
|
// require 为 Node.js 的 require, 在 Node.js 运行环境下 可以用来引入模块
|
||||||
|
|
||||||
// $arguments 为传入的脚本参数
|
// $arguments 为传入的脚本参数
|
||||||
|
|
||||||
|
// $options 为通过链接传入的参数
|
||||||
|
// 例如: { arg1: 'a', arg2: 'b' }
|
||||||
|
// 可这样传:
|
||||||
|
// 先这样处理 encodeURIComponent(JSON.stringify({ arg1: 'a', arg2: 'b' }))
|
||||||
|
// /api/file/foo?$options=%7B%22arg1%22%3A%22a%22%2C%22arg2%22%3A%22b%22%7D
|
||||||
|
// 或这样传:
|
||||||
|
// 先这样处理 encodeURIComponent('arg1=a&arg2=b')
|
||||||
|
// /api/file/foo?$options=arg1%3Da%26arg2%3Db
|
||||||
|
|
||||||
|
// console.log($options)
|
||||||
|
|
||||||
// targetPlatform 为输出的目标平台
|
// targetPlatform 为输出的目标平台
|
||||||
|
|
||||||
// lodash
|
// lodash
|
||||||
|
|
||||||
// $substore 为 OpenAPI
|
// $substore 为 OpenAPI
|
||||||
// 参考 https://github.com/Peng-YM/QuanX/blob/master/Tools/OpenAPI/README.md
|
// 参考 https://github.com/Peng-YM/QuanX/blob/master/Tools/OpenAPI/README.md
|
||||||
|
|
||||||
// scriptResourceCache 缓存
|
// scriptResourceCache 缓存
|
||||||
// 可参考 https://t.me/zhetengsha/1003
|
// 可参考 https://t.me/zhetengsha/1003
|
||||||
// const cache = scriptResourceCache
|
// const cache = scriptResourceCache
|
||||||
@@ -33,16 +56,26 @@ function operator(proxies = [], targetPlatform, context) {
|
|||||||
// parse, // 订阅解析
|
// parse, // 订阅解析
|
||||||
// process, // 节点操作/文件操作
|
// process, // 节点操作/文件操作
|
||||||
// produce, // 输出订阅
|
// produce, // 输出订阅
|
||||||
|
// getRandomPort, // 获取随机端口(参考 ports 端口跳跃的格式 443,8443,5000-6000)
|
||||||
|
// ipAddress, // https://github.com/beaugunderson/ip-address
|
||||||
// isIPv4,
|
// isIPv4,
|
||||||
// isIPv6,
|
// isIPv6,
|
||||||
// isIP,
|
// isIP,
|
||||||
// yaml, // yaml 解析和生成
|
// yaml, // yaml 解析和生成
|
||||||
// getFlag, // 获取 emoji 旗帜
|
// getFlag, // 获取 emoji 旗帜
|
||||||
|
// removeFlag, // 移除 emoji 旗帜
|
||||||
// getISO, // 获取 ISO 3166-1 alpha-2 代码
|
// getISO, // 获取 ISO 3166-1 alpha-2 代码
|
||||||
|
// Gist, // Gist 类
|
||||||
|
// download, // 内部的下载方法, 见 backend/src/utils/download.js
|
||||||
|
// MMDB, // Node.js 环境 可用于模拟 Surge/Loon 的 $utils.ipasn, $utils.ipaso, $utils.geoip. 具体见 https://t.me/zhetengsha/1269
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
// 如果只是为了快速修改或者筛选 可以参考 脚本操作支持节点快捷脚本 https://t.me/zhetengsha/970 和 脚本筛选支持节点快捷脚本 https://t.me/zhetengsha/1009
|
||||||
|
// ⚠️ 注意: 函数式(即本文件这样的 function operator() {}) 和快捷操作(下面使用 $server) 只能二选一
|
||||||
// 示例: 给节点名添加前缀
|
// 示例: 给节点名添加前缀
|
||||||
// $server.name = `[${ProxyUtils.getISO($server.name)}] ${$server.name}`
|
// $server.name = `[${ProxyUtils.getISO($server.name)}] ${$server.name}`
|
||||||
|
// 示例: 给节点名添加旗帜
|
||||||
|
// $server.name = `[${ProxyUtils.getFlag($server.name).replace(/🇹🇼/g, '🇼🇸')}] ${ProxyUtils.removeFlag($server.name)}`
|
||||||
|
|
||||||
// 示例: 从 sni 文件中读取内容并进行节点操作
|
// 示例: 从 sni 文件中读取内容并进行节点操作
|
||||||
// const sni = await produceArtifact({
|
// const sni = await produceArtifact({
|
||||||
@@ -62,7 +95,7 @@ function operator(proxies = [], targetPlatform, context) {
|
|||||||
// }
|
// }
|
||||||
// })
|
// })
|
||||||
// $content = proxies
|
// $content = proxies
|
||||||
|
|
||||||
// 2. sing-box
|
// 2. sing-box
|
||||||
|
|
||||||
// 但是一般不需要这样用, 可参考
|
// 但是一般不需要这样用, 可参考
|
||||||
@@ -94,6 +127,11 @@ function operator(proxies = [], targetPlatform, context) {
|
|||||||
// produceType: 'internal' // 'internal' produces an Array, otherwise produces a String( ProxyUtils.yaml.safeLoad('YAML String').proxies )
|
// produceType: 'internal' // 'internal' produces an Array, otherwise produces a String( ProxyUtils.yaml.safeLoad('YAML String').proxies )
|
||||||
// })
|
// })
|
||||||
|
|
||||||
|
// 4. 一个比较折腾的方案: 在脚本操作中, 把内容同步到另一个 gist
|
||||||
|
// 见 https://t.me/zhetengsha/1428
|
||||||
|
//
|
||||||
|
// const content = ProxyUtils.produce([...proxies], platform)
|
||||||
|
|
||||||
// // YAML
|
// // YAML
|
||||||
// ProxyUtils.yaml.load('YAML String')
|
// ProxyUtils.yaml.load('YAML String')
|
||||||
// ProxyUtils.yaml.safeLoad('YAML String')
|
// ProxyUtils.yaml.safeLoad('YAML String')
|
||||||
@@ -111,16 +149,15 @@ function operator(proxies = [], targetPlatform, context) {
|
|||||||
// yaml.proxies.unshift(...clashMetaProxies)
|
// yaml.proxies.unshift(...clashMetaProxies)
|
||||||
// $content = ProxyUtils.yaml.dump(yaml)
|
// $content = ProxyUtils.yaml.dump(yaml)
|
||||||
|
|
||||||
|
// { $content, $files, $options } will be passed to the next operator
|
||||||
// { $content, $files } will be passed to the next operator
|
|
||||||
// $content is the final content of the file
|
// $content is the final content of the file
|
||||||
|
|
||||||
// flowUtils 为机场订阅流量信息处理工具
|
// flowUtils 为机场订阅流量信息处理工具
|
||||||
// 可参考:
|
// 可参考:
|
||||||
// 1. https://t.me/zhetengsha/948
|
// 1. https://t.me/zhetengsha/948
|
||||||
|
|
||||||
// context 为传入的上下文
|
// context 为传入的上下文
|
||||||
// 有三种情况, 按需判断
|
// 其中 source 为 订阅和组合订阅的数据, 有三种情况, 按需判断 (若只需要取订阅/组合订阅名称 直接用 `_subName` `_subDisplayName` `_collectionName` `_collectionDisplayName` 即可)
|
||||||
|
|
||||||
// 若存在 `source._collection` 且 `source._collection.subscriptions` 中的 key 在 `source` 上也存在, 说明输出结果为组合订阅, 但是脚本设置在单条订阅上
|
// 若存在 `source._collection` 且 `source._collection.subscriptions` 中的 key 在 `source` 上也存在, 说明输出结果为组合订阅, 但是脚本设置在单条订阅上
|
||||||
|
|
||||||
@@ -205,7 +242,7 @@ function operator(proxies = [], targetPlatform, context) {
|
|||||||
// 参数说明
|
// 参数说明
|
||||||
// 可参考 https://github.com/sub-store-org/Sub-Store/wiki/%E9%93%BE%E6%8E%A5%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E
|
// 可参考 https://github.com/sub-store-org/Sub-Store/wiki/%E9%93%BE%E6%8E%A5%E5%8F%82%E6%95%B0%E8%AF%B4%E6%98%8E
|
||||||
|
|
||||||
console.log(JSON.stringify(context, null, 2))
|
console.log(JSON.stringify(context, null, 2));
|
||||||
|
|
||||||
return proxies
|
return proxies;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user