[GH-ISSUE #6072] [Feature]: Add block outbound option and domainStrategy selector for JSON Subscription routing rules #4203

Open
opened 2026-10-31 20:37:56 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @SpeedeMiner on GitHub (Jul 22, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6072

Description

Currently, the JSON Subscription settings page (/panel/settings#subscription-formats) allows configuring routing rules only with the direct outbound (and the default proxy rule).

However, Xray already supports the block (blackhole) outbound, and the generated JSON subscription already contains a block outbound. The UI simply does not provide a way to use it.

It would also be useful to allow changing the routing.domainStrategy value from the UI instead of keeping it fixed to AsIs.

Proposed changes

  1. Add a Block option alongside the existing Direct option when creating routing rules in JSON Subscription.
  2. Add a Domain Strategy dropdown for the generated JSON configuration.

Suggested values:

  • AsIs
  • IPIfNonMatch
  • IPOnDemand

Example

Current generated routing:

"routing": {
  "domainStrategy": "AsIs",
  "rules": [
    {
      "domain": [
        "geosite:private"
      ],
      "outboundTag": "direct",
      "type": "field"
    }
  ]
}
"routing": {
  "domainStrategy": "IPIfNonMatch",
  "rules": [
    {
      "domain": [
        "geosite:category-ads-all"
      ],
      "outboundTag": "block",
      "type": "field"
    },
    {
      "domain": [
        "geosite:private"
      ],
      "outboundTag": "direct",
      "type": "field"
    }
  ]
}

### Describe the solution you'd like

Allows blocking ads, trackers, malware domains, or unwanted services directly in the generated subscription.
Exposes existing Xray functionality without requiring manual database edits.
Gives users control over domainStrategy, which can improve routing behavior depending on the deployment.
Backward compatible, as existing configurations would continue to use AsIs and direct by default.

Thank you for considering this feature.

### Alternatives you've considered

_No response_

### Concrete use case

_No response_

### Mockups, screenshots, or examples

_No response_

### Which parts of the panel would this affect?

_No response_

### Are you willing to help?

- [ ] I'd like to implement this feature myself and open a PR.
- [ ] I can help test once a PR is open.

### Before submitting

- [x] I searched [existing issues](../issues?q=is%3Aissue) and this feature has not been requested.
- [x] This feature request is written in English.
Originally created by @SpeedeMiner on GitHub (Jul 22, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6072 ### Is your feature request related to a problem? ### Description Currently, the **JSON Subscription** settings page (`/panel/settings#subscription-formats`) allows configuring routing rules only with the `direct` outbound (and the default proxy rule). However, Xray already supports the `block` (`blackhole`) outbound, and the generated JSON subscription already contains a `block` outbound. The UI simply does not provide a way to use it. It would also be useful to allow changing the `routing.domainStrategy` value from the UI instead of keeping it fixed to `AsIs`. ### Proposed changes 1. Add a **Block** option alongside the existing **Direct** option when creating routing rules in **JSON Subscription**. 2. Add a **Domain Strategy** dropdown for the generated JSON configuration. Suggested values: - AsIs - IPIfNonMatch - IPOnDemand ### Example Current generated routing: ```json "routing": { "domainStrategy": "AsIs", "rules": [ { "domain": [ "geosite:private" ], "outboundTag": "direct", "type": "field" } ] } "routing": { "domainStrategy": "IPIfNonMatch", "rules": [ { "domain": [ "geosite:category-ads-all" ], "outboundTag": "block", "type": "field" }, { "domain": [ "geosite:private" ], "outboundTag": "direct", "type": "field" } ] } ### Describe the solution you'd like Allows blocking ads, trackers, malware domains, or unwanted services directly in the generated subscription. Exposes existing Xray functionality without requiring manual database edits. Gives users control over domainStrategy, which can improve routing behavior depending on the deployment. Backward compatible, as existing configurations would continue to use AsIs and direct by default. Thank you for considering this feature. ### Alternatives you've considered _No response_ ### Concrete use case _No response_ ### Mockups, screenshots, or examples _No response_ ### Which parts of the panel would this affect? _No response_ ### Are you willing to help? - [ ] I'd like to implement this feature myself and open a PR. - [ ] I can help test once a PR is open. ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this feature has not been requested. - [x] This feature request is written in English.
Author
Owner

@MHSanaei commented on GitHub (Jul 25, 2026):

@claude

<!-- gh-comment-id:5080312204 --> @MHSanaei commented on GitHub (Jul 25, 2026): @claude
Author
Owner

@github-actions[bot] commented on GitHub (Jul 25, 2026):

Claude finished @MHSanaei's task in 6m 49s —— View job


Analysis

Both requests are implementable. They are not the same size of change: block is frontend-only (the backend already supports it end to end), while domainStrategy needs a new setting plumbed through six files plus make gen.

  • Read the issue
  • Trace the JSON subscription routing pipeline
  • Verify what already works and what is missing
  • Write out the exact change

1. Block outbound: the backend is already done, only the UI is missing

internal/sub/default.json already ships the blackhole outbound in every generated profile:

{
  "tag": "block",
  "protocol": "blackhole",
  "settings": { "response": { "type": "http" } }
}

(internal/sub/default.json:55-63; it is appended to every config via s.defaultOutbounds — internal/sub/json_service.go:241 for inbound profiles, :108 for external links.)

NewSubJsonService merges the subJsonRules setting verbatim and prepends it to the default rules (internal/sub/json_service.go:41-49), so a rule with "outboundTag": "block" works today. There is even a test that already does exactly that — internal/sub/mutation_audit_test.go:29-46 feeds [{"type":"field","domain":["geosite:ads"],"outboundTag":"block"}] and asserts it lands first in routing.rules.

So the only gap is frontend/src/pages/settings/SubscriptionFormatsTab.tsx, which hardcodes direct.

The hazard to avoid

The current helpers locate rules by which key is present, not by outbound tag:

const ipRule = ruleArray.find((r) => r.ip);        // line 103
const dRule  = ruleArray.find((r) => r.domain);    // line 109
let idx = rules.findIndex((r) => r.ip);            // line 123

If block rules are added to the same array, a block rule can be picked up and overwritten by the Direct selectors. Also directEnabled = allSetting.subJsonRules !== '' (line 80) means turning Direct off wipes the whole string, taking block rules with it. Both need to be scoped by outboundTag first.

Proposed replacement for the module constants and state helpers

type SubJsonRule = { type: string; outboundTag: string; domain?: string[]; ip?: string[] };

const DEFAULT_DIRECT_RULES: SubJsonRule[] = [
  { type: 'field', outboundTag: 'direct', domain: ['geosite:category-ir'] },
  { type: 'field', outboundTag: 'direct', ip: ['geoip:private', 'geoip:ir'] },
];
const DEFAULT_BLOCK_RULES: SubJsonRule[] = [
  { type: 'field', outboundTag: 'block', domain: ['geosite:category-ads-all'] },
];
const BLOCK_IP_RULE: SubJsonRule = { type: 'field', outboundTag: 'block', ip: [] };

const blockDomainsOptions = [
  { label: 'Ads All', value: 'geosite:category-ads-all' },
  { label: 'Adult +18', value: 'geosite:category-porn' },
];

function readRules(raw: string): SubJsonRule[] {
  const parsed = readJson<unknown>(raw, null);
  return Array.isArray(parsed) ? (parsed as SubJsonRule[]) : [];
}

function blockFirst(rules: SubJsonRule[]): SubJsonRule[] {
  return [...rules].sort((a, b) => Number(a.outboundTag !== 'block') - Number(b.outboundTag !== 'block'));
}

Inside the component, replacing lines 96-147:

  const ruleArray = useMemo(() => readRules(allSetting.subJsonRules), [allSetting.subJsonRules]);
  const directEnabled = ruleArray.some((r) => r.outboundTag === 'direct');
  const blockEnabled = ruleArray.some((r) => r.outboundTag === 'block');

  const ruleValues = (tag: string, key: 'ip' | 'domain') =>
    ruleArray.find((r) => r.outboundTag === tag && r[key])?.[key] ?? [];

  function writeRules(rules: SubJsonRule[]) {
    updateSetting({ subJsonRules: rules.length > 0 ? JSON.stringify(blockFirst(rules)) : '' });
  }

  function setTagEnabled(tag: string, defaults: SubJsonRule[], enabled: boolean) {
    const rest = ruleArray.filter((r) => r.outboundTag !== tag);
    writeRules(enabled ? [...rest, ...defaults] : rest);
  }

  function setRuleValues(tag: string, key: 'ip' | 'domain', template: SubJsonRule, value: string[]) {
    let rules = [...ruleArray];
    if (value.length === 0) {
      rules = rules.filter((r) => !(r.outboundTag === tag && r[key]));
    } else {
      let index = rules.findIndex((r) => r.outboundTag === tag && r[key]);
      if (index === -1) {
        rules.push({ ...template });
        index = rules.length - 1;
      }
      rules[index] = { ...rules[index], [key]: [...value] };
    }
    writeRules(rules);
  }

The existing Direct tab (key '4') then becomes:

<Switch checked={directEnabled} onChange={(v) => setTagEnabled('direct', DEFAULT_DIRECT_RULES, v)} />
...
  value={ruleValues('direct', 'ip')}
  onChange={(v) => setRuleValues('direct', 'ip', DEFAULT_DIRECT_RULES[1], v)}
...
  value={ruleValues('direct', 'domain')}
  onChange={(v) => setRuleValues('direct', 'domain', DEFAULT_DIRECT_RULES[0], v)}

and a new tab is appended:

      {
        key: '5',
        label: catTabLabel(<StopOutlined />, t('pages.settings.block'), isMobile),
        children: (
          <>
            <SettingListItem paddings="small" description={t('pages.settings.blockDesc')}>
              <Switch checked={blockEnabled} onChange={(v) => setTagEnabled('block', DEFAULT_BLOCK_RULES, v)} />
            </SettingListItem>
            {blockEnabled && (
              <div className="format-settings">
                <SettingListItem paddings="small">
                  <Select
                    mode="tags"
                    value={ruleValues('block', 'domain')}
                    style={{ width: '100%' }}
                    onChange={(v) => setRuleValues('block', 'domain', DEFAULT_BLOCK_RULES[0], v)}
                    options={blockDomainsOptions}
                  />
                </SettingListItem>
                <SettingListItem paddings="small">
                  <Select
                    mode="tags"
                    value={ruleValues('block', 'ip')}
                    style={{ width: '100%' }}
                    onChange={(v) => setRuleValues('block', 'ip', BLOCK_IP_RULE, v)}
                    options={directIPsOptions}
                  />
                </SettingListItem>
              </div>
            )}
          </>
        ),
      },

StopOutlined is added to the @ant-design/icons import.

Three details worth keeping:

  1. Tag name is block, not blocked. The server-side Xray template uses blocked (frontend/src/pages/xray/basics/constants.ts:63), but the subscription profile's blackhole tag is block (internal/sub/default.json:56). A rule pointing at blocked would silently reference a non-existent outbound in the generated client config.
  2. Ordering matters. Xray matches rules top-down, so blockFirst() keeps block ahead of direct; otherwise a domain covered by both lists would go direct.
  3. Do not reuse BLOCK_DOMAINS_OPTIONS from frontend/src/pages/xray/basics/constants.ts:32-50. Most of its entries are ext:geosite_IR.dat:... / ext:geosite_RU.dat:..., which resolve against files in the panel's bin folder. The subscription config runs on the user's device, which usually does not ship those .dat files. That is why the existing directIPsOptions / directDomainsOptions in this file (lines 44-64) use plain geoip: / geosite: values only — the block presets should follow the same rule.

2. Domain strategy: new setting, six files

routing.domainStrategy is fixed at AsIs in internal/sub/default.json:80 and never overwritten. Adding a selector means a new setting key; nothing else reads it.

internal/web/service/setting.go — add to defaultValueMap next to subJsonRules (line 115) and a getter next to GetSubJsonRules (line 864):

	"subJsonRules":                "",
	"subJsonDomainStrategy":       "AsIs",
func (s *SettingService) GetSubJsonDomainStrategy() (string, error) {
	return s.getString("subJsonDomainStrategy")
}

internal/web/entity/entity.go — new field after SubJsonRules (line 103), plus a whitelist check in CheckValid (line 154) so an arbitrary string cannot reach the generated config:

	SubJsonRules                string `json:"subJsonRules" form:"subJsonRules"`
	SubJsonDomainStrategy       string `json:"subJsonDomainStrategy" form:"subJsonDomainStrategy"`
	switch s.SubJsonDomainStrategy {
	case "", "AsIs", "IPIfNonMatch", "IPOnDemand":
	default:
		return common.NewError("sub json domain strategy is not valid:", s.SubJsonDomainStrategy)
	}

internal/sub/json_service.go — NewSubJsonService has ~30 call sites in tests, so a variadic option keeps them all compiling and matches the option pattern already used in controller.go:

type subJsonConfig struct {
	domainStrategy string
}

type SubJsonOption func(*subJsonConfig)

func WithRoutingDomainStrategy(value string) SubJsonOption {
	return func(config *subJsonConfig) { config.domainStrategy = value }
}

Signature and the routing block (replacing lines 41-49):

func NewSubJsonService(mux string, rules string, finalMask string, subService *SubService, options ...SubJsonOption) *SubJsonService {
	config := subJsonConfig{}
	for _, option := range options {
		option(&config)
	}
	if routing, ok := configJson["routing"].(map[string]any); ok {
		if rules != "" {
			var newRules []any
			_ = json.Unmarshal([]byte(rules), &newRules)
			defaultRules, _ := routing["rules"].([]any)
			routing["rules"] = append(newRules, defaultRules...)
		}
		if config.domainStrategy != "" {
			routing["domainStrategy"] = config.domainStrategy
		}
		configJson["routing"] = routing
	}

With no option passed the behaviour is byte-identical to today, so TestSubJsonService_CustomRulesPrepended and TestSubJsonService_EmptyRulesLeavesDefault stay green unchanged.

internal/sub/controller.go — field in subControllerConfig (line 99), option, and the constructor call (line 271):

	subJsonRules          string
	subJsonDomainStrategy string
func WithSUBJsonDomainStrategy(value string) SUBControllerOption {
	return func(config *subControllerConfig) { config.subJsonDomainStrategy = value }
}
		subJsonService: NewSubJsonService(config.subJsonMux, config.subJsonRules, config.subJsonFinalMask, sub,
			WithRoutingDomainStrategy(config.subJsonDomainStrategy)),

internal/sub/sub.go — read it next to SubJsonRules (line 148) and pass it next to WithSUBJsonRules (line 283):

	SubJsonDomainStrategy, err := s.settingService.GetSubJsonDomainStrategy()
	if err != nil {
		SubJsonDomainStrategy = "AsIs"
	}
		WithSUBJsonDomainStrategy(SubJsonDomainStrategy),

Frontend — frontend/src/models/setting.ts:65 and frontend/src/schemas/setting.ts:70:

  subJsonRules = '';
  subJsonDomainStrategy = 'AsIs';
  subJsonDomainStrategy: z.enum(['AsIs', 'IPIfNonMatch', 'IPOnDemand']).optional(),

and the control, which can sit at the top of the routing tab in SubscriptionFormatsTab.tsx:

<SettingListItem
  paddings="small"
 
  description={t('pages.xray.RoutingStrategyDesc')}
>
  <Select
    value={allSetting.subJsonDomainStrategy || 'AsIs'}
    style={{ width: '100%' }}
    options={ROUTING_DOMAIN_STRATEGIES.map((s) => ({ value: s, label: s }))}
    onChange={(v) => updateSetting({ subJsonDomainStrategy: v })}
  />
</SettingListItem>

ROUTING_DOMAIN_STRATEGIES already exists with exactly the three values requested (frontend/src/pages/xray/basics/constants.ts:1), imported as @/pages/xray/basics/constants.


Repo checklist for this change

  • No DB migration needed. Settings are key/value rows created lazily: getString falls back to defaultValueMap when the row is missing (internal/web/service/setting.go:340-350) and GetAllSetting fills absent keys from the same map (:248). Existing installs read AsIs without any write.
  • No endpoints.ts entry — no new g.POST/g.GET route.
  • make gen is required after the entity change: AllSetting / AllSettingView are already in openapigen's StructAllow (tools/openapigen/main.go:66-67), so the new field flows into frontend/src/generated/* and frontend/public/openapi.json automatically. make gen-check fails otherwise.
  • i18n: the labels above deliberately reuse keys that already exist in all 13 locales — pages.xray.RoutingStrategy / RoutingStrategyDesc (en-US.json:1597-1598) and pages.xray.blockips / blockdomains (:1580-1581). Only the Block section title needs new keys, pages.settings.block and pages.settings.blockDesc, and those must be added to all 13 files in internal/web/translation/, alongside the existing direct / directDesc pair (en-US.json:1436-1437).
  • No // comments in the Go/TS above, per CLAUDE.md.
  • Frontend build: frontend/src edits only reach users once Vite regenerates internal/web/dist/.

Suggested tests:

  • Go, in internal/sub/json_service_test.go: NewSubJsonService("", "", "", nil, WithRoutingDomainStrategy("IPIfNonMatch")) sets routing.domainStrategy, and the no-option case still yields AsIs — mirroring the shape of TestSubJsonService_EmptyRulesLeavesDefault.
  • Frontend, modelled on frontend/src/test/subscription-general-tab.test.tsx: enabling Block writes a block rule ahead of the direct rules, disabling Direct leaves the block rules intact, and subJsonRules becomes '' only when nothing remains.

One behavioural note for the changelog: the subscription server reads these settings when it is constructed (internal/sub/sub.go:148, :283), and it is rebuilt on restart (main.go:135-152), so a changed strategy applies exactly like subJsonRules does today — after the panel restarts, not on the next subscription fetch.

This workflow only investigates and replies, so nothing here has been committed; the snippets are written to be applied as-is.

<!-- gh-comment-id:5080313054 --> @github-actions[bot] commented on GitHub (Jul 25, 2026): **Claude finished @MHSanaei's task in 6m 49s** —— [View job](https://github.com/MHSanaei/3x-ui/actions/runs/30172274584) --- ### Analysis Both requests are implementable. They are not the same size of change: **`block` is frontend-only** (the backend already supports it end to end), while **`domainStrategy` needs a new setting** plumbed through six files plus `make gen`. - [x] Read the issue - [x] Trace the JSON subscription routing pipeline - [x] Verify what already works and what is missing - [x] Write out the exact change --- ### 1. Block outbound: the backend is already done, only the UI is missing `internal/sub/default.json` already ships the blackhole outbound in every generated profile: ```json { "tag": "block", "protocol": "blackhole", "settings": { "response": { "type": "http" } } } ``` (`internal/sub/default.json:55-63`; it is appended to every config via `s.defaultOutbounds` — `internal/sub/json_service.go:241` for inbound profiles, `:108` for external links.) `NewSubJsonService` merges the `subJsonRules` setting verbatim and **prepends** it to the default rules (`internal/sub/json_service.go:41-49`), so a rule with `"outboundTag": "block"` works today. There is even a test that already does exactly that — `internal/sub/mutation_audit_test.go:29-46` feeds `[{"type":"field","domain":["geosite:ads"],"outboundTag":"block"}]` and asserts it lands first in `routing.rules`. So the only gap is `frontend/src/pages/settings/SubscriptionFormatsTab.tsx`, which hardcodes `direct`. #### The hazard to avoid The current helpers locate rules by *which key is present*, not by outbound tag: ```tsx const ipRule = ruleArray.find((r) => r.ip); // line 103 const dRule = ruleArray.find((r) => r.domain); // line 109 let idx = rules.findIndex((r) => r.ip); // line 123 ``` If block rules are added to the same array, a block rule can be picked up and overwritten by the Direct selectors. Also `directEnabled = allSetting.subJsonRules !== ''` (line 80) means turning Direct off wipes the whole string, taking block rules with it. Both need to be scoped by `outboundTag` first. #### Proposed replacement for the module constants and state helpers ```tsx type SubJsonRule = { type: string; outboundTag: string; domain?: string[]; ip?: string[] }; const DEFAULT_DIRECT_RULES: SubJsonRule[] = [ { type: 'field', outboundTag: 'direct', domain: ['geosite:category-ir'] }, { type: 'field', outboundTag: 'direct', ip: ['geoip:private', 'geoip:ir'] }, ]; const DEFAULT_BLOCK_RULES: SubJsonRule[] = [ { type: 'field', outboundTag: 'block', domain: ['geosite:category-ads-all'] }, ]; const BLOCK_IP_RULE: SubJsonRule = { type: 'field', outboundTag: 'block', ip: [] }; const blockDomainsOptions = [ { label: 'Ads All', value: 'geosite:category-ads-all' }, { label: 'Adult +18', value: 'geosite:category-porn' }, ]; function readRules(raw: string): SubJsonRule[] { const parsed = readJson<unknown>(raw, null); return Array.isArray(parsed) ? (parsed as SubJsonRule[]) : []; } function blockFirst(rules: SubJsonRule[]): SubJsonRule[] { return [...rules].sort((a, b) => Number(a.outboundTag !== 'block') - Number(b.outboundTag !== 'block')); } ``` Inside the component, replacing lines 96-147: ```tsx const ruleArray = useMemo(() => readRules(allSetting.subJsonRules), [allSetting.subJsonRules]); const directEnabled = ruleArray.some((r) => r.outboundTag === 'direct'); const blockEnabled = ruleArray.some((r) => r.outboundTag === 'block'); const ruleValues = (tag: string, key: 'ip' | 'domain') => ruleArray.find((r) => r.outboundTag === tag && r[key])?.[key] ?? []; function writeRules(rules: SubJsonRule[]) { updateSetting({ subJsonRules: rules.length > 0 ? JSON.stringify(blockFirst(rules)) : '' }); } function setTagEnabled(tag: string, defaults: SubJsonRule[], enabled: boolean) { const rest = ruleArray.filter((r) => r.outboundTag !== tag); writeRules(enabled ? [...rest, ...defaults] : rest); } function setRuleValues(tag: string, key: 'ip' | 'domain', template: SubJsonRule, value: string[]) { let rules = [...ruleArray]; if (value.length === 0) { rules = rules.filter((r) => !(r.outboundTag === tag && r[key])); } else { let index = rules.findIndex((r) => r.outboundTag === tag && r[key]); if (index === -1) { rules.push({ ...template }); index = rules.length - 1; } rules[index] = { ...rules[index], [key]: [...value] }; } writeRules(rules); } ``` The existing Direct tab (key `'4'`) then becomes: ```tsx <Switch checked={directEnabled} onChange={(v) => setTagEnabled('direct', DEFAULT_DIRECT_RULES, v)} /> ... value={ruleValues('direct', 'ip')} onChange={(v) => setRuleValues('direct', 'ip', DEFAULT_DIRECT_RULES[1], v)} ... value={ruleValues('direct', 'domain')} onChange={(v) => setRuleValues('direct', 'domain', DEFAULT_DIRECT_RULES[0], v)} ``` and a new tab is appended: ```tsx { key: '5', label: catTabLabel(<StopOutlined />, t('pages.settings.block'), isMobile), children: ( <> <SettingListItem paddings="small" description={t('pages.settings.blockDesc')}> <Switch checked={blockEnabled} onChange={(v) => setTagEnabled('block', DEFAULT_BLOCK_RULES, v)} /> </SettingListItem> {blockEnabled && ( <div className="format-settings"> <SettingListItem paddings="small"> <Select mode="tags" value={ruleValues('block', 'domain')} style={{ width: '100%' }} onChange={(v) => setRuleValues('block', 'domain', DEFAULT_BLOCK_RULES[0], v)} options={blockDomainsOptions} /> </SettingListItem> <SettingListItem paddings="small"> <Select mode="tags" value={ruleValues('block', 'ip')} style={{ width: '100%' }} onChange={(v) => setRuleValues('block', 'ip', BLOCK_IP_RULE, v)} options={directIPsOptions} /> </SettingListItem> </div> )} </> ), }, ``` `StopOutlined` is added to the `@ant-design/icons` import. Three details worth keeping: 1. **Tag name is `block`, not `blocked`.** The server-side Xray template uses `blocked` (`frontend/src/pages/xray/basics/constants.ts:63`), but the subscription profile's blackhole tag is `block` (`internal/sub/default.json:56`). A rule pointing at `blocked` would silently reference a non-existent outbound in the generated client config. 2. **Ordering matters.** Xray matches rules top-down, so `blockFirst()` keeps block ahead of direct; otherwise a domain covered by both lists would go direct. 3. **Do not reuse `BLOCK_DOMAINS_OPTIONS`** from `frontend/src/pages/xray/basics/constants.ts:32-50`. Most of its entries are `ext:geosite_IR.dat:...` / `ext:geosite_RU.dat:...`, which resolve against files in the panel's `bin` folder. The subscription config runs on the *user's device*, which usually does not ship those `.dat` files. That is why the existing `directIPsOptions` / `directDomainsOptions` in this file (lines 44-64) use plain `geoip:` / `geosite:` values only — the block presets should follow the same rule. --- ### 2. Domain strategy: new setting, six files `routing.domainStrategy` is fixed at `AsIs` in `internal/sub/default.json:80` and never overwritten. Adding a selector means a new setting key; nothing else reads it. **`internal/web/service/setting.go`** — add to `defaultValueMap` next to `subJsonRules` (line 115) and a getter next to `GetSubJsonRules` (line 864): ```go "subJsonRules": "", "subJsonDomainStrategy": "AsIs", ``` ```go func (s *SettingService) GetSubJsonDomainStrategy() (string, error) { return s.getString("subJsonDomainStrategy") } ``` **`internal/web/entity/entity.go`** — new field after `SubJsonRules` (line 103), plus a whitelist check in `CheckValid` (line 154) so an arbitrary string cannot reach the generated config: ```go SubJsonRules string `json:"subJsonRules" form:"subJsonRules"` SubJsonDomainStrategy string `json:"subJsonDomainStrategy" form:"subJsonDomainStrategy"` ``` ```go switch s.SubJsonDomainStrategy { case "", "AsIs", "IPIfNonMatch", "IPOnDemand": default: return common.NewError("sub json domain strategy is not valid:", s.SubJsonDomainStrategy) } ``` **`internal/sub/json_service.go`** — `NewSubJsonService` has ~30 call sites in tests, so a variadic option keeps them all compiling and matches the option pattern already used in `controller.go`: ```go type subJsonConfig struct { domainStrategy string } type SubJsonOption func(*subJsonConfig) func WithRoutingDomainStrategy(value string) SubJsonOption { return func(config *subJsonConfig) { config.domainStrategy = value } } ``` Signature and the routing block (replacing lines 41-49): ```go func NewSubJsonService(mux string, rules string, finalMask string, subService *SubService, options ...SubJsonOption) *SubJsonService { config := subJsonConfig{} for _, option := range options { option(&config) } ``` ```go if routing, ok := configJson["routing"].(map[string]any); ok { if rules != "" { var newRules []any _ = json.Unmarshal([]byte(rules), &newRules) defaultRules, _ := routing["rules"].([]any) routing["rules"] = append(newRules, defaultRules...) } if config.domainStrategy != "" { routing["domainStrategy"] = config.domainStrategy } configJson["routing"] = routing } ``` With no option passed the behaviour is byte-identical to today, so `TestSubJsonService_CustomRulesPrepended` and `TestSubJsonService_EmptyRulesLeavesDefault` stay green unchanged. **`internal/sub/controller.go`** — field in `subControllerConfig` (line 99), option, and the constructor call (line 271): ```go subJsonRules string subJsonDomainStrategy string ``` ```go func WithSUBJsonDomainStrategy(value string) SUBControllerOption { return func(config *subControllerConfig) { config.subJsonDomainStrategy = value } } ``` ```go subJsonService: NewSubJsonService(config.subJsonMux, config.subJsonRules, config.subJsonFinalMask, sub, WithRoutingDomainStrategy(config.subJsonDomainStrategy)), ``` **`internal/sub/sub.go`** — read it next to `SubJsonRules` (line 148) and pass it next to `WithSUBJsonRules` (line 283): ```go SubJsonDomainStrategy, err := s.settingService.GetSubJsonDomainStrategy() if err != nil { SubJsonDomainStrategy = "AsIs" } ``` ```go WithSUBJsonDomainStrategy(SubJsonDomainStrategy), ``` **Frontend** — `frontend/src/models/setting.ts:65` and `frontend/src/schemas/setting.ts:70`: ```ts subJsonRules = ''; subJsonDomainStrategy = 'AsIs'; ``` ```ts subJsonDomainStrategy: z.enum(['AsIs', 'IPIfNonMatch', 'IPOnDemand']).optional(), ``` and the control, which can sit at the top of the routing tab in `SubscriptionFormatsTab.tsx`: ```tsx <SettingListItem paddings="small" description={t('pages.xray.RoutingStrategyDesc')} > <Select value={allSetting.subJsonDomainStrategy || 'AsIs'} style={{ width: '100%' }} options={ROUTING_DOMAIN_STRATEGIES.map((s) => ({ value: s, label: s }))} onChange={(v) => updateSetting({ subJsonDomainStrategy: v })} /> </SettingListItem> ``` `ROUTING_DOMAIN_STRATEGIES` already exists with exactly the three values requested (`frontend/src/pages/xray/basics/constants.ts:1`), imported as `@/pages/xray/basics/constants`. --- ### Repo checklist for this change - **No DB migration needed.** Settings are key/value rows created lazily: `getString` falls back to `defaultValueMap` when the row is missing (`internal/web/service/setting.go:340-350`) and `GetAllSetting` fills absent keys from the same map (`:248`). Existing installs read `AsIs` without any write. - **No `endpoints.ts` entry** — no new `g.POST`/`g.GET` route. - **`make gen` is required** after the entity change: `AllSetting` / `AllSettingView` are already in openapigen's `StructAllow` (`tools/openapigen/main.go:66-67`), so the new field flows into `frontend/src/generated/*` and `frontend/public/openapi.json` automatically. `make gen-check` fails otherwise. - **i18n:** the labels above deliberately reuse keys that already exist in all 13 locales — `pages.xray.RoutingStrategy` / `RoutingStrategyDesc` (`en-US.json:1597-1598`) and `pages.xray.blockips` / `blockdomains` (`:1580-1581`). Only the Block section title needs new keys, `pages.settings.block` and `pages.settings.blockDesc`, and those must be added to **all 13** files in `internal/web/translation/`, alongside the existing `direct` / `directDesc` pair (`en-US.json:1436-1437`). - **No `//` comments** in the Go/TS above, per `CLAUDE.md`. - **Frontend build:** `frontend/src` edits only reach users once Vite regenerates `internal/web/dist/`. Suggested tests: - Go, in `internal/sub/json_service_test.go`: `NewSubJsonService("", "", "", nil, WithRoutingDomainStrategy("IPIfNonMatch"))` sets `routing.domainStrategy`, and the no-option case still yields `AsIs` — mirroring the shape of `TestSubJsonService_EmptyRulesLeavesDefault`. - Frontend, modelled on `frontend/src/test/subscription-general-tab.test.tsx`: enabling Block writes a `block` rule ahead of the `direct` rules, disabling Direct leaves the block rules intact, and `subJsonRules` becomes `''` only when nothing remains. One behavioural note for the changelog: the subscription server reads these settings when it is constructed (`internal/sub/sub.go:148`, `:283`), and it is rebuilt on restart (`main.go:135-152`), so a changed strategy applies exactly like `subJsonRules` does today — after the panel restarts, not on the next subscription fetch. This workflow only investigates and replies, so nothing here has been committed; the snippets are written to be applied as-is.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#4203
No description provided.