mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-10-25 15:25:01 +03:00
feat(happ): add routing editor, optional ad blocking, and LAN bypass preset (#6545)
* feat(happ): make ad blocking optional in routing presets Add an independent AdBlock toggle for Iran, China, and global presets, applied only when generating routing rules. Update the China preset to Bypass-CN and cover preset behavior and localized controls. * feat: add visual routing editor with JSON support and localization updates - Implemented a new modal for editing routing profiles with basic and advanced tabs. - Added functionality to load, parse, and generate routing profiles in JSON format. - Enhanced user experience with validation and error handling for JSON input. - Updated translations for Russian, Turkish, Ukrainian, Vietnamese, Chinese (Simplified and Traditional) to include new routing editor terms. - Created helper functions for managing routing profiles and generating deep links. - Added unit tests for routing editor functionalities and JSON handling. * feat: update routing editor to preserve null lists in profiles and enhance validation messages
This commit is contained in:
@@ -0,0 +1,204 @@
|
||||
import { useId, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Alert, Input, Modal, Space, Tabs, Typography } from 'antd';
|
||||
|
||||
import JsonEditor from '@/components/form/JsonEditor';
|
||||
import type { HappRoutingProfile } from '@/schemas/happRouting';
|
||||
import {
|
||||
buildHappRoutingDeeplink,
|
||||
loadHappRouting,
|
||||
parseHappRoutingJson,
|
||||
parseHappRoutingList,
|
||||
type HappRoutingListKey,
|
||||
} from './happRoutingEditor';
|
||||
|
||||
interface HappRoutingEditorModalProps {
|
||||
input: string;
|
||||
onCancel: () => void;
|
||||
onGenerate: (deeplink: string) => void;
|
||||
}
|
||||
|
||||
const basicFields: { key: HappRoutingListKey; label: string; placeholder: string }[] = [
|
||||
{
|
||||
key: 'DirectSites',
|
||||
label: 'subHappDirectDomains',
|
||||
placeholder: 'domain:ir\ndomain:cn\nexample.local',
|
||||
},
|
||||
{
|
||||
key: 'ProxySites',
|
||||
label: 'subHappProxyDomains',
|
||||
placeholder: 'geosite:google\nyoutube.com',
|
||||
},
|
||||
{
|
||||
key: 'BlockSites',
|
||||
label: 'subHappBlockDomains',
|
||||
placeholder: 'geosite:category-ads-all\nanalytics.google.com',
|
||||
},
|
||||
{
|
||||
key: 'DirectIp',
|
||||
label: 'subHappDirectIPs',
|
||||
placeholder: 'geoip:ir\n192.168.0.0/16\n10.0.0.0/8',
|
||||
},
|
||||
{
|
||||
key: 'ProxyIp',
|
||||
label: 'subHappProxyIPs',
|
||||
placeholder: '1.1.1.1/32\n8.8.8.8/32',
|
||||
},
|
||||
{
|
||||
key: 'BlockIp',
|
||||
label: 'subHappBlockIPs',
|
||||
placeholder: 'geoip:phishing\n0.0.0.0/8',
|
||||
},
|
||||
];
|
||||
|
||||
type BasicBuffers = Record<HappRoutingListKey, string>;
|
||||
|
||||
function basicBuffers(profile: HappRoutingProfile | null): BasicBuffers {
|
||||
return {
|
||||
DirectSites: profile?.DirectSites?.join('\n') ?? '',
|
||||
ProxySites: profile?.ProxySites?.join('\n') ?? '',
|
||||
BlockSites: profile?.BlockSites?.join('\n') ?? '',
|
||||
DirectIp: profile?.DirectIp?.join('\n') ?? '',
|
||||
ProxyIp: profile?.ProxyIp?.join('\n') ?? '',
|
||||
BlockIp: profile?.BlockIp?.join('\n') ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
function mergeBasicRules(profile: HappRoutingProfile, buffers: BasicBuffers): HappRoutingProfile {
|
||||
const next = { ...profile };
|
||||
// Only replace edited lists; absent lists and all other profile fields must survive unchanged.
|
||||
for (const { key } of basicFields) {
|
||||
if (buffers[key] !== (profile[key]?.join('\n') ?? '')) {
|
||||
next[key] = parseHappRoutingList(buffers[key]);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
const loadErrorKeys = {
|
||||
off: 'subHappEditorLoadOff',
|
||||
remote: 'subHappEditorLoadRemote',
|
||||
invalid: 'subHappEditorLoadInvalid',
|
||||
};
|
||||
|
||||
export default function HappRoutingEditorModal({
|
||||
input,
|
||||
onCancel,
|
||||
onGenerate,
|
||||
}: HappRoutingEditorModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const fieldId = useId();
|
||||
const [loaded] = useState(() => loadHappRouting(input));
|
||||
const [profile, setProfile] = useState(() => (loaded.success ? loaded.profile : null));
|
||||
const [activeTab, setActiveTab] = useState('basic');
|
||||
// Keep raw buffers while typing so trailing newlines and temporarily invalid JSON are not lost.
|
||||
const [buffers, setBuffers] = useState(() => basicBuffers(profile));
|
||||
const [jsonText, setJsonText] = useState(() => (profile ? JSON.stringify(profile, null, 2) : ''));
|
||||
const advancedProfile = activeTab === 'advanced' ? parseHappRoutingJson(jsonText) : null;
|
||||
const invalidJson = activeTab === 'advanced' && advancedProfile === null;
|
||||
|
||||
const switchTab = (nextTab: string) => {
|
||||
if (!profile || nextTab === activeTab) return;
|
||||
if (nextTab === 'advanced') {
|
||||
const next = mergeBasicRules(profile, buffers);
|
||||
setProfile(next);
|
||||
setJsonText(JSON.stringify(next, null, 2));
|
||||
} else {
|
||||
if (!advancedProfile) return;
|
||||
setProfile(advancedProfile);
|
||||
setBuffers(basicBuffers(advancedProfile));
|
||||
}
|
||||
setActiveTab(nextTab);
|
||||
};
|
||||
|
||||
const generate = () => {
|
||||
if (!loaded.success || !profile) return;
|
||||
const next = activeTab === 'advanced' ? advancedProfile : mergeBasicRules(profile, buffers);
|
||||
if (next) onGenerate(buildHappRoutingDeeplink(next, loaded.mode));
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={t('pages.settings.subHappModalTitle')}
|
||||
open
|
||||
onCancel={onCancel}
|
||||
onOk={generate}
|
||||
okText={t('pages.settings.subHappBuildDeeplink')}
|
||||
okButtonProps={{ disabled: !loaded.success || invalidJson }}
|
||||
width={650}
|
||||
>
|
||||
<Space orientation="vertical" style={{ width: '100%', marginTop: 12 }} size="middle">
|
||||
{!loaded.success ? (
|
||||
<Alert type="error" showIcon title={t(`pages.settings.${loadErrorKeys[loaded.error]}`)} />
|
||||
) : loaded.isNew ? (
|
||||
<Alert type="info" showIcon title={t('pages.settings.subHappEditorNew')} />
|
||||
) : null}
|
||||
{loaded.success ? (
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={switchTab}
|
||||
destroyOnHidden
|
||||
items={[
|
||||
{
|
||||
key: 'basic',
|
||||
label: t('pages.settings.subHappEditorBasic'),
|
||||
disabled: invalidJson,
|
||||
children: (
|
||||
<Space orientation="vertical" style={{ width: '100%' }} size="middle">
|
||||
<Typography.Text type="secondary" id={`${fieldId}-hint`}>
|
||||
{t('pages.settings.subHappEditorListHint')}
|
||||
</Typography.Text>
|
||||
{basicFields.map(({ key, label, placeholder }) => (
|
||||
<div key={key}>
|
||||
<label
|
||||
htmlFor={`${fieldId}-${key}`}
|
||||
style={{ display: 'block', fontWeight: 600, marginBottom: 4 }}
|
||||
>
|
||||
{t(`pages.settings.${label}`)}
|
||||
</label>
|
||||
<Input.TextArea
|
||||
id={`${fieldId}-${key}`}
|
||||
aria-describedby={`${fieldId}-hint`}
|
||||
rows={2}
|
||||
value={buffers[key]}
|
||||
placeholder={placeholder}
|
||||
onChange={(event) =>
|
||||
setBuffers((previous) => ({ ...previous, [key]: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'advanced',
|
||||
label: t('pages.settings.subHappEditorAdvanced'),
|
||||
children: (
|
||||
<Space orientation="vertical" style={{ width: '100%' }} size="middle">
|
||||
<Typography.Text type="secondary">
|
||||
{t('pages.settings.subHappEditorAdvancedHint')}
|
||||
</Typography.Text>
|
||||
{invalidJson ? (
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
title={t('pages.settings.subHappEditorInvalidJson')}
|
||||
/>
|
||||
) : null}
|
||||
<JsonEditor
|
||||
value={jsonText}
|
||||
onChange={setJsonText}
|
||||
minHeight="320px"
|
||||
maxHeight="50vh"
|
||||
/>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Input, Modal, Select, Space, Switch, Tabs, message } from 'antd';
|
||||
import { Button, Input, Select, Space, Switch, Tabs, message } from 'antd';
|
||||
import {
|
||||
BranchesOutlined,
|
||||
BuildOutlined,
|
||||
@@ -13,7 +13,8 @@ import {
|
||||
} from '@ant-design/icons';
|
||||
import type { AllSetting } from '@/models/setting';
|
||||
import { SettingListItem } from '@/components/ui';
|
||||
import { buildHappPresetDeeplink, parseList, toBase64Utf8 } from './happPresets';
|
||||
import { buildHappPresetDeeplink } from './happPresets';
|
||||
import HappRoutingEditorModal from './HappRoutingEditorModal';
|
||||
import { catTabLabel } from './catTabLabel';
|
||||
|
||||
interface HappSettingsContentProps {
|
||||
@@ -32,38 +33,20 @@ export default function HappSettingsContent({
|
||||
defaultActiveTab = 'routing',
|
||||
}: HappSettingsContentProps) {
|
||||
const { t } = useTranslation();
|
||||
// Generator choices stay local until Apply updates the draft; page Save persists it.
|
||||
const [selectedPreset, setSelectedPreset] = useState<string>('iran-bypass');
|
||||
const [includeAdblock, setIncludeAdblock] = useState(false);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
|
||||
const [directDomains, setDirectDomains] = useState('');
|
||||
const [proxyDomains, setProxyDomains] = useState('');
|
||||
const [blockDomains, setBlockDomains] = useState('');
|
||||
const [directIPs, setDirectIPs] = useState('');
|
||||
const [proxyIPs, setProxyIPs] = useState('');
|
||||
const [blockIPs, setBlockIPs] = useState('');
|
||||
|
||||
const applyPreset = () => {
|
||||
const payload = buildHappPresetDeeplink(selectedPreset);
|
||||
const payload = buildHappPresetDeeplink(selectedPreset, includeAdblock);
|
||||
if (payload) {
|
||||
updateSetting({ subRoutingRules: payload });
|
||||
message.success(t('pages.settings.subHappPresetApplied'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleBuildDeeplink = () => {
|
||||
const profile = {
|
||||
Name: 'Custom Rules',
|
||||
GlobalProxy: 'true',
|
||||
DirectSites: parseList(directDomains),
|
||||
DirectIp: parseList(directIPs),
|
||||
ProxySites: parseList(proxyDomains),
|
||||
ProxyIp: parseList(proxyIPs),
|
||||
BlockSites: parseList(blockDomains),
|
||||
BlockIp: parseList(blockIPs),
|
||||
DomainStrategy: 'IPIfNonMatch',
|
||||
};
|
||||
|
||||
const deeplink = 'happ://routing/onadd/' + toBase64Utf8(JSON.stringify(profile));
|
||||
const handleBuildDeeplink = (deeplink: string) => {
|
||||
updateSetting({ subRoutingRules: deeplink });
|
||||
setIsModalOpen(false);
|
||||
message.success(t('pages.settings.subHappDeeplinkGenerated'));
|
||||
@@ -112,21 +95,31 @@ export default function HappSettingsContent({
|
||||
title={t('pages.settings.subHappPresets')}
|
||||
description={t('pages.settings.subHappPresetsDesc')}
|
||||
>
|
||||
<Space orientation="horizontal" style={{ width: '100%' }}>
|
||||
<Space orientation="horizontal" wrap style={{ width: '100%' }}>
|
||||
<Select
|
||||
aria-label={t('pages.settings.subHappPresets')}
|
||||
value={selectedPreset}
|
||||
style={{ minWidth: 170 }}
|
||||
onChange={setSelectedPreset}
|
||||
options={[
|
||||
{ value: 'iran-bypass', label: t('pages.settings.subHappPresetIran') },
|
||||
{ value: 'china-direct', label: t('pages.settings.subHappPresetChina') },
|
||||
{ value: 'adblock', label: t('pages.settings.subHappPresetAdblock') },
|
||||
{ value: 'global', label: t('pages.settings.subHappPresetGlobal') },
|
||||
{ value: 'lan-bypass', label: t('pages.settings.subHappPresetLocal') },
|
||||
{ value: 'off', label: t('pages.settings.subHappPresetOff') },
|
||||
]}
|
||||
/>
|
||||
<Space size="small">
|
||||
<Switch
|
||||
aria-label={t('pages.settings.subHappIncludeAdblock')}
|
||||
checked={includeAdblock}
|
||||
disabled={selectedPreset === 'off'}
|
||||
onChange={setIncludeAdblock}
|
||||
/>
|
||||
<span>{t('pages.settings.subHappIncludeAdblock')}</span>
|
||||
</Space>
|
||||
<Button type="primary" onClick={applyPreset}>
|
||||
{t('pages.settings.subHappPresets')}
|
||||
{t('pages.settings.subHappApplyPreset')}
|
||||
</Button>
|
||||
</Space>
|
||||
</SettingListItem>
|
||||
@@ -589,83 +582,14 @@ export default function HappSettingsContent({
|
||||
]}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
title={t('pages.settings.subHappModalTitle')}
|
||||
open={isModalOpen}
|
||||
onCancel={() => setIsModalOpen(false)}
|
||||
onOk={handleBuildDeeplink}
|
||||
okText={t('pages.settings.subHappBuildDeeplink')}
|
||||
width={650}
|
||||
>
|
||||
<Space orientation="vertical" style={{ width: '100%', marginTop: 12 }} size="middle">
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4 }}>
|
||||
{t('pages.settings.subHappDirectDomains')}
|
||||
</div>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
value={directDomains}
|
||||
placeholder="domain:ir, domain:cn, example.local"
|
||||
onChange={(e) => setDirectDomains(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4 }}>
|
||||
{t('pages.settings.subHappProxyDomains')}
|
||||
</div>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
value={proxyDomains}
|
||||
placeholder="geosite:google, youtube.com"
|
||||
onChange={(e) => setProxyDomains(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4 }}>
|
||||
{t('pages.settings.subHappBlockDomains')}
|
||||
</div>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
value={blockDomains}
|
||||
placeholder="geosite:category-ads-all, analytics.google.com"
|
||||
onChange={(e) => setBlockDomains(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4 }}>
|
||||
{t('pages.settings.subHappDirectIPs')}
|
||||
</div>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
value={directIPs}
|
||||
placeholder="geoip:ir, 192.168.0.0/16, 10.0.0.0/8"
|
||||
onChange={(e) => setDirectIPs(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4 }}>
|
||||
{t('pages.settings.subHappProxyIPs')}
|
||||
</div>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
value={proxyIPs}
|
||||
placeholder="1.1.1.1/32, 8.8.8.8/32"
|
||||
onChange={(e) => setProxyIPs(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, marginBottom: 4 }}>
|
||||
{t('pages.settings.subHappBlockIPs')}
|
||||
</div>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
value={blockIPs}
|
||||
placeholder="geoip:phishing, 0.0.0.0/8"
|
||||
onChange={(e) => setBlockIPs(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</Space>
|
||||
</Modal>
|
||||
{/* Mount per opening so canceled edits are discarded and the latest parent draft is loaded. */}
|
||||
{isModalOpen ? (
|
||||
<HappRoutingEditorModal
|
||||
input={allSetting.subRoutingRules}
|
||||
onCancel={() => setIsModalOpen(false)}
|
||||
onGenerate={handleBuildDeeplink}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,16 +7,11 @@ export function toBase64Utf8(str: string): string {
|
||||
);
|
||||
}
|
||||
|
||||
// Splits multiline or comma-separated string into clean unique token arrays.
|
||||
export function parseList(input: string): string[] {
|
||||
return input
|
||||
.split(/[\n,]+/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
// Build standard Happ routing deeplink or special state for curated presets.
|
||||
export function buildHappPresetDeeplink(preset: string): string {
|
||||
export function buildHappPresetDeeplink(preset: string, includeAdblock = false): string {
|
||||
// Ad blocking is opt-in for each generated profile, independent of the base routing rules.
|
||||
const blockSites = includeAdblock ? ['geosite:category-ads-all'] : [];
|
||||
|
||||
switch (preset) {
|
||||
case 'off':
|
||||
return 'happ://routing/off';
|
||||
@@ -27,9 +22,20 @@ export function buildHappPresetDeeplink(preset: string): string {
|
||||
JSON.stringify({
|
||||
Name: 'Iran Bypass',
|
||||
GlobalProxy: 'true',
|
||||
DirectSites: ['domain:ir', 'regexp:.*\\.ir$'],
|
||||
DirectIp: ['geoip:ir', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'],
|
||||
BlockSites: ['geosite:category-ads-all'],
|
||||
RouteOrder: 'block-proxy-direct',
|
||||
DirectSites: ['geosite:private', 'domain:ir', 'geosite:category-ir'],
|
||||
DirectIp: [
|
||||
'geoip:ir',
|
||||
'geoip:private',
|
||||
'127.0.0.0/8',
|
||||
'10.0.0.0/8',
|
||||
'172.16.0.0/12',
|
||||
'192.168.0.0/16',
|
||||
'169.254.0.0/16',
|
||||
'224.0.0.0/4',
|
||||
'255.255.255.255',
|
||||
],
|
||||
BlockSites: blockSites,
|
||||
BlockIp: [],
|
||||
ProxySites: [],
|
||||
ProxyIp: [],
|
||||
@@ -42,32 +48,38 @@ export function buildHappPresetDeeplink(preset: string): string {
|
||||
'happ://routing/onadd/' +
|
||||
toBase64Utf8(
|
||||
JSON.stringify({
|
||||
Name: 'China Direct',
|
||||
Name: 'Bypass-CN',
|
||||
GlobalProxy: 'true',
|
||||
DirectSites: ['geosite:cn', 'geosite:geolocation-cn'],
|
||||
DirectIp: ['geoip:cn', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'],
|
||||
BlockSites: ['geosite:category-ads-all'],
|
||||
BlockIp: [],
|
||||
RouteOrder: 'block-proxy-direct',
|
||||
RemoteDNSType: 'DoH',
|
||||
RemoteDNSDomain: 'https://cloudflare-dns.com/dns-query',
|
||||
RemoteDNSIP: '1.1.1.1',
|
||||
DomesticDNSType: 'DoH',
|
||||
DomesticDNSDomain: 'https://dns.alidns.com/dns-query',
|
||||
DomesticDNSIP: '223.5.5.5',
|
||||
DnsHosts: {
|
||||
'cloudflare-dns.com': '1.1.1.1',
|
||||
'dns.alidns.com': '223.5.5.5',
|
||||
},
|
||||
DirectSites: ['geosite:private', 'geosite:cn', 'geosite:geolocation-cn'],
|
||||
DirectIp: [
|
||||
'geoip:cn',
|
||||
'geoip:private',
|
||||
'127.0.0.0/8',
|
||||
'10.0.0.0/8',
|
||||
'172.16.0.0/12',
|
||||
'192.168.0.0/16',
|
||||
'169.254.0.0/16',
|
||||
'224.0.0.0/4',
|
||||
'255.255.255.255',
|
||||
],
|
||||
ProxySites: [],
|
||||
ProxyIp: [],
|
||||
DomainStrategy: 'IPIfNonMatch',
|
||||
}),
|
||||
)
|
||||
);
|
||||
case 'adblock':
|
||||
return (
|
||||
'happ://routing/onadd/' +
|
||||
toBase64Utf8(
|
||||
JSON.stringify({
|
||||
Name: 'AdBlock',
|
||||
GlobalProxy: 'true',
|
||||
DirectSites: [],
|
||||
DirectIp: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'],
|
||||
BlockSites: ['geosite:category-ads-all'],
|
||||
BlockSites: blockSites,
|
||||
BlockIp: [],
|
||||
ProxySites: [],
|
||||
ProxyIp: [],
|
||||
DomainStrategy: 'IPIfNonMatch',
|
||||
FakeDNS: 'false',
|
||||
UseChunkFiles: 'true',
|
||||
}),
|
||||
)
|
||||
);
|
||||
@@ -80,7 +92,25 @@ export function buildHappPresetDeeplink(preset: string): string {
|
||||
GlobalProxy: 'true',
|
||||
DirectSites: [],
|
||||
DirectIp: [],
|
||||
BlockSites: [],
|
||||
BlockSites: blockSites,
|
||||
BlockIp: [],
|
||||
ProxySites: [],
|
||||
ProxyIp: [],
|
||||
DomainStrategy: 'AsIs',
|
||||
}),
|
||||
)
|
||||
);
|
||||
// LAN bypass has its own identity so applying it does not overwrite the Global profile.
|
||||
case 'lan-bypass':
|
||||
return (
|
||||
'happ://routing/onadd/' +
|
||||
toBase64Utf8(
|
||||
JSON.stringify({
|
||||
Name: 'Global Bypass Local Network',
|
||||
GlobalProxy: 'true',
|
||||
DirectSites: ['geosite:private'],
|
||||
DirectIp: ['geoip:private'],
|
||||
BlockSites: blockSites,
|
||||
BlockIp: [],
|
||||
ProxySites: [],
|
||||
ProxyIp: [],
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { HappRoutingProfileSchema, type HappRoutingProfile } from '@/schemas/happRouting';
|
||||
import { toBase64Utf8 } from './happPresets';
|
||||
import { isRemoteRoutingSource } from './subscriptionShared';
|
||||
|
||||
export type HappRoutingMode = 'add' | 'onadd';
|
||||
export type HappRoutingListKey =
|
||||
| 'DirectSites'
|
||||
| 'DirectIp'
|
||||
| 'ProxySites'
|
||||
| 'ProxyIp'
|
||||
| 'BlockSites'
|
||||
| 'BlockIp';
|
||||
|
||||
export type HappRoutingLoadResult =
|
||||
| { success: true; profile: HappRoutingProfile; mode: HappRoutingMode; isNew: boolean }
|
||||
| { success: false; error: 'off' | 'remote' | 'invalid' };
|
||||
|
||||
export function parseHappRoutingJson(input: string): HappRoutingProfile | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(input);
|
||||
const result = HappRoutingProfileSchema.safeParse(value);
|
||||
// Keep the validated input object; schema output can discard some unknown extension keys.
|
||||
return result.success ? (value as HappRoutingProfile) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function loadHappRouting(input: string): HappRoutingLoadResult {
|
||||
const source = input.trim();
|
||||
if (!source) {
|
||||
return {
|
||||
success: true,
|
||||
profile: {
|
||||
Name: 'Custom Rules',
|
||||
GlobalProxy: 'true',
|
||||
DirectSites: [],
|
||||
DirectIp: [],
|
||||
ProxySites: [],
|
||||
ProxyIp: [],
|
||||
BlockSites: [],
|
||||
BlockIp: [],
|
||||
DomainStrategy: 'IPIfNonMatch',
|
||||
},
|
||||
mode: 'onadd',
|
||||
isNew: true,
|
||||
};
|
||||
}
|
||||
if (source === 'happ://routing/off') return { success: false, error: 'off' };
|
||||
if (isRemoteRoutingSource(source)) return { success: false, error: 'remote' };
|
||||
|
||||
if (source.startsWith('{')) {
|
||||
const profile = parseHappRoutingJson(source);
|
||||
return profile
|
||||
? { success: true, profile, mode: 'onadd', isNew: false }
|
||||
: { success: false, error: 'invalid' };
|
||||
}
|
||||
|
||||
const match = /^happ:\/\/routing\/(onadd|add)\/([A-Za-z0-9+/_-]+={0,2})$/.exec(source);
|
||||
if (!match) return { success: false, error: 'invalid' };
|
||||
|
||||
try {
|
||||
const binary = atob(match[2].replace(/-/g, '+').replace(/_/g, '/'));
|
||||
// Decode UTF-8 strictly so malformed bytes cannot silently change profile names or rules.
|
||||
const json = new TextDecoder('utf-8', { fatal: true }).decode(
|
||||
Uint8Array.from(binary, (character) => character.charCodeAt(0)),
|
||||
);
|
||||
const profile = parseHappRoutingJson(json);
|
||||
return profile
|
||||
? { success: true, profile, mode: match[1] as HappRoutingMode, isNew: false }
|
||||
: { success: false, error: 'invalid' };
|
||||
} catch {
|
||||
return { success: false, error: 'invalid' };
|
||||
}
|
||||
}
|
||||
|
||||
export function buildHappRoutingDeeplink(
|
||||
profile: HappRoutingProfile,
|
||||
mode: HappRoutingMode = 'onadd',
|
||||
): string {
|
||||
return `happ://routing/${mode}/` + toBase64Utf8(JSON.stringify(profile));
|
||||
}
|
||||
|
||||
export function parseHappRoutingList(input: string): string[] {
|
||||
// Commas can belong to regexp rules, so the editor uses one rule per line.
|
||||
return input
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => entry.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
Reference in New Issue
Block a user