Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 50 additions & 2 deletions packages/core/src/mihomo/proxy-sanitizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const STANDARD_BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-
const REALITY_PUBLIC_KEY_PATTERN = /^[A-Za-z0-9_-]{43}$/;
const WIREGUARD_KEY_PATTERN = /^[A-Za-z0-9+/]{43}=$/;
const CERTIFICATE_FINGERPRINT_HEX_PATTERN = /^[A-Fa-f0-9]{64}$/;
const SSH_HOST_KEY_PATTERN = /^ssh-(?:ed25519|rsa|dss|ecdsa-[A-Za-z0-9-]+)\s+[A-Za-z0-9+/=]+(?:\s+.*)?$/;
const SSH_SERVER_FINGERPRINT_PATTERN = /^SHA256:[A-Za-z0-9+/]{43}=?$/;
const VLESS_ENCRYPTION_PATTERN =
/^mlkem768x25519plus\.(?:native|xorpub|random)\.(?:1rtt|0rtt)\.[A-Za-z0-9+/=_-]+(?:\.[A-Za-z0-9+/=_-]+)*$/;
Expand Down Expand Up @@ -95,12 +94,61 @@ function normalizePemPrivateKey(value: unknown): string | null {
return normalized;
}

function isAsciiAlphaNumericOrHyphen(value: string): boolean {
if (!value) return false;
for (const char of value) {
const ok = (char >= "a" && char <= "z") || (char >= "A" && char <= "Z") || (char >= "0" && char <= "9") || char === "-";
if (!ok) return false;
}
return true;
}

function isBase64Token(value: string): boolean {
if (!value) return false;
for (const char of value) {
const ok =
(char >= "a" && char <= "z") ||
(char >= "A" && char <= "Z") ||
(char >= "0" && char <= "9") ||
char === "+" ||
char === "/" ||
char === "=";
if (!ok) return false;
}
return true;
}

function findWhitespaceIndex(value: string): number {
for (let i = 0; i < value.length; i += 1) {
if (value[i].trim() === "") return i;
}
return -1;
}

function isSupportedSshHostKeyType(value: string): boolean {
if (value === "ssh-ed25519" || value === "ssh-rsa" || value === "ssh-dss") return true;
return value.startsWith("ssh-ecdsa-") && isAsciiAlphaNumericOrHyphen(value.slice("ssh-ecdsa-".length));
}

function isSshHostKey(value: string): boolean {
const typeEnd = findWhitespaceIndex(value);
if (typeEnd <= 0) return false;
const keyType = value.slice(0, typeEnd);
if (!isSupportedSshHostKeyType(keyType)) return false;

const rest = value.slice(typeEnd).trimStart();
if (!rest) return false;
const keyEnd = findWhitespaceIndex(rest);
const key = keyEnd === -1 ? rest : rest.slice(0, keyEnd);
return isBase64Token(key);
}

function normalizeSshHostKeys(value: unknown): string[] | undefined {
if (!Array.isArray(value)) return undefined;
const keys = value
.filter((item): item is string => typeof item === "string")
.map((item) => item.trim())
.filter((item) => SSH_HOST_KEY_PATTERN.test(item));
.filter((item) => isSshHostKey(item));
return keys.length > 0 ? keys : undefined;
}

Expand Down
51 changes: 44 additions & 7 deletions packages/core/src/parser/protocols/anytls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,56 @@ function parseIntParam(params: URLSearchParams, keys: string[]): number | undefi
return undefined;
}

function hasUserInfoAuthority(raw: string): boolean {
const hashIndex = raw.indexOf("#");
const beforeHash = hashIndex === -1 ? raw : raw.slice(0, hashIndex);
const queryIndex = beforeHash.indexOf("?");
let authority = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
if (authority.endsWith("/")) authority = authority.slice(0, -1);
return authority.includes("@");
}

function splitAtFirstQuery(raw: string): { token: string; suffix: string } | null {
const queryIndex = raw.indexOf("?");
if (queryIndex === -1) return null;
return { token: raw.slice(0, queryIndex), suffix: raw.slice(queryIndex) };
}

function isBase64UrlToken(value: string): boolean {
if (!value) return false;
for (const char of value) {
const ok =
(char >= "a" && char <= "z") ||
(char >= "A" && char <= "Z") ||
(char >= "0" && char <= "9") ||
char === "+" ||
char === "/" ||
char === "=" ||
char === "_" ||
char === "-";
if (!ok) return false;
}
return true;
}

function stripThroughLastColon(value: string): string {
const colonIndex = value.lastIndexOf(":");
return colonIndex === -1 ? value : value.slice(colonIndex + 1);
}

function normalizeEncodedUserinfoUri(uri: string): { uri: string; usedEncodedUserinfo: boolean } {
const raw = uri.slice("anytls://".length).trim();
if (/^(.*?)@(.*?)(?::(\d+))?\/?(?:\?(.*?))?(?:#(.*?))?$/.test(raw)) {
if (hasUserInfoAuthority(raw)) {
return { uri, usedEncodedUserinfo: false };
}
const match = /^(.*?)(\?.*?)$/.exec(raw);
if (!match) return { uri, usedEncodedUserinfo: false };
const token = match[1].trim();
if (!/^[A-Za-z0-9+/=_-]+$/.test(token) || token.includes('.') || token.includes(':')) {
const parts = splitAtFirstQuery(raw);
if (!parts) return { uri, usedEncodedUserinfo: false };
const token = parts.token.trim();
if (!isBase64UrlToken(token) || token.includes(".") || token.includes(":")) {
return { uri, usedEncodedUserinfo: false };
}
const decoded = decodeBase64(token);
return { uri: `anytls://${decoded}${match[2]}`, usedEncodedUserinfo: true };
return { uri: `anytls://${decoded}${parts.suffix}`, usedEncodedUserinfo: true };
}

function normalizeAnyTlsSecurity(raw: string | null): "tls" {
Expand Down Expand Up @@ -114,7 +151,7 @@ export function parseAnyTLS(uri: string): AnyTLSNode {
const pass = safeDecodeURIComponent(url.password);
if (user || pass) {
const merged = pass ? `${user}:${pass}` : user;
return normalized.usedEncodedUserinfo ? merged.replace(/^.*?:/g, "") : merged;
return normalized.usedEncodedUserinfo ? stripThroughLastColon(merged) : merged;
}

return (
Expand Down
12 changes: 9 additions & 3 deletions packages/core/src/parser/protocols/hysteria2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,14 @@ function parseHopIntervalParam(params: URLSearchParams, keys: string[]): number
return undefined;
}

function trimTrailingSlashes(value: string): string {
let end = value.length;
while (end > 0 && value[end - 1] === "/") end -= 1;
return end === value.length ? value : value.slice(0, end);
}

function splitAuthority(value: string): { userInfo: string; server: string; portSpec: string } {
const raw = value.trim().replace(/\/+$/, "");
const raw = trimTrailingSlashes(value.trim());
if (!raw) return { userInfo: "", server: "", portSpec: "" };

const atIndex = raw.lastIndexOf("@");
Expand All @@ -45,7 +51,7 @@ function splitAuthority(value: string): { userInfo: string; server: string; port
const server = hostPort.slice(1, end);
const rest = hostPort.slice(end + 1);
if (rest.startsWith(":")) {
return { userInfo, server, portSpec: rest.slice(1).replace(/\/+$/, "") };
return { userInfo, server, portSpec: trimTrailingSlashes(rest.slice(1)) };
}
return { userInfo, server, portSpec: "" };
}
Expand All @@ -58,7 +64,7 @@ function splitAuthority(value: string): { userInfo: string; server: string; port
return {
userInfo,
server: hostPort.slice(0, colonIndex),
portSpec: hostPort.slice(colonIndex + 1).replace(/\/+$/, ""),
portSpec: trimTrailingSlashes(hostPort.slice(colonIndex + 1)),
};
}

Expand Down
26 changes: 19 additions & 7 deletions packages/core/src/parser/protocols/simple-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,31 @@ import { parseJsonObject, parseJsonStringMap } from "../json-utils";
type SimpleProxyType = "http" | "https" | "socks5" | "socks4" | "ssh";
type SimpleProxyNode = SocksNode | HttpNode | SshNode;

function takeTerminalEnclosedValue(input: string, open: string, close: string): { value: string; enclosed?: string } {
if (!input.endsWith(close)) return { value: input };
const openIndex = input.lastIndexOf(open);
if (openIndex === -1) return { value: input };
const enclosed = input.slice(openIndex + open.length, input.length - close.length);
if (enclosed.includes(close)) return { value: input };
return {
value: input.slice(0, openIndex),
enclosed,
};
}

function stripMetaSuffix(input: string): { value: string; name?: string } {
let remaining = input.trim();
let name: string | undefined;

const braceMatch = remaining.match(/\{([^}]*)\}$/);
if (braceMatch) {
name = braceMatch[1];
remaining = remaining.slice(0, -braceMatch[0].length);
const brace = takeTerminalEnclosedValue(remaining, "{", "}");
if (brace.enclosed !== undefined) {
name = brace.enclosed;
remaining = brace.value;
}

const bracketMatch = remaining.match(/\[([^\]]*)\]$/);
if (bracketMatch) {
remaining = remaining.slice(0, -bracketMatch[0].length);
const bracket = takeTerminalEnclosedValue(remaining, "[", "]");
if (bracket.enclosed !== undefined) {
remaining = bracket.value;
}

return { value: remaining, name };
Expand Down
54 changes: 48 additions & 6 deletions packages/core/src/parser/protocols/vless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,19 +114,61 @@ function buildXhttpOptsFromQuery(params: URLSearchParams, fallbackPath: string,
};
}

function isDigitString(value: string): boolean {
if (!value) return false;
for (const char of value) {
if (char < "0" || char > "9") return false;
}
return true;
}

function splitAtFirstQuery(raw: string): { token: string; suffix: string } | null {
const queryIndex = raw.indexOf("?");
if (queryIndex === -1) return null;
return { token: raw.slice(0, queryIndex), suffix: raw.slice(queryIndex) };
}

function hasStandardVlessAuthority(raw: string): boolean {
const hashIndex = raw.indexOf("#");
const beforeHash = hashIndex === -1 ? raw : raw.slice(0, hashIndex);
const queryIndex = beforeHash.indexOf("?");
let authority = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
if (authority.endsWith("/")) authority = authority.slice(0, -1);

const atIndex = authority.lastIndexOf("@");
if (atIndex <= 0) return false;
const hostPort = authority.slice(atIndex + 1);
if (!hostPort) return false;

if (hostPort.startsWith("[")) {
const bracketEnd = hostPort.indexOf("]");
if (bracketEnd === -1) return false;
const afterBracket = hostPort.slice(bracketEnd + 1);
return afterBracket.startsWith(":") && isDigitString(afterBracket.slice(1));
}

const colonIndex = hostPort.lastIndexOf(":");
return colonIndex > 0 && isDigitString(hostPort.slice(colonIndex + 1));
}

function stripThroughLastColon(value: string): string {
const colonIndex = value.lastIndexOf(":");
return colonIndex === -1 ? value : value.slice(colonIndex + 1);
}

function normalizeShadowrocketUri(uri: string): { uri: string; isShadowrocket: boolean } {
const raw = uri.slice("vless://".length).trim();
if (/^(.*?)@(.*?):(\d+)\/?(\?(.*?))?(?:#(.*?))?$/.test(raw)) {
if (hasStandardVlessAuthority(raw)) {
return { uri, isShadowrocket: false };
}

const match = /^(.*?)(\?.*?)$/.exec(raw);
if (!match) {
const parts = splitAtFirstQuery(raw);
if (!parts) {
return { uri, isShadowrocket: false };
}

const decoded = decodeBase64(match[1]);
return { uri: `vless://${decoded}${match[2]}`, isShadowrocket: true };
const decoded = decodeBase64(parts.token.trim());
return { uri: `vless://${decoded}${parts.suffix}`, isShadowrocket: true };
}

function parseShadowrocketHeaderValue(raw: string): Record<string, string> | undefined {
Expand Down Expand Up @@ -155,7 +197,7 @@ export function parseVLESS(uri: string): VLESSNode {
}
return user;
})();
const uuid = normalized.isShadowrocket ? uuidRaw.replace(/^.*?:/g, "") : uuidRaw;
const uuid = normalized.isShadowrocket ? stripThroughLastColon(uuidRaw) : uuidRaw;
const server = url.hostname;
const port = parseInt(url.port || "443", 10);
const name =
Expand Down
Loading