feat: add custom inbound-to-outbound binding with per-inbound routing rules

This commit is contained in:
Markson Hon committed 2026-05-11 23:38:32 +08:00
1 parent a7fa018436
commit 5a3a44b65b
10 files changed
+381 -65

No files matched your search

+68 -7
View File
@@ -1,5 +1,5 @@
<template>
<div class="modal-card" style="max-width: 560px; margin: auto">
<div class="modal-card" style="max-width: 640px; margin: auto">
<header class="modal-card-head">
<p class="modal-card-title">{{ $t("customInbound.title") }}</p>
</header>
@@ -12,18 +12,25 @@
narrowed
style="margin-bottom: 1rem"
>
<b-table-column v-slot="props" :label="$t('customInbound.tag')" width="160">
<b-table-column v-slot="props" :label="$t('customInbound.tag')" width="120">
<code>{{ props.row.tag }}</code>
</b-table-column>
<b-table-column v-slot="props" :label="$t('customInbound.protocol')" width="80">
<b-table-column v-slot="props" :label="$t('customInbound.protocol')" width="70">
<b-tag :type="props.row.protocol === 'socks' ? 'is-info' : 'is-success'" size="is-small">
{{ props.row.protocol.toUpperCase() }}
</b-tag>
</b-table-column>
<b-table-column v-slot="props" :label="$t('customInbound.port')" width="100">
<b-table-column v-slot="props" :label="$t('customInbound.port')" width="70">
{{ props.row.port }}
</b-table-column>
<b-table-column v-slot="props" :label="$t('operations.name')" width="80">
<b-table-column v-slot="props" :label="$t('customInbound.outbound')" width="140">
<span v-if="props.row.outbound">
<b-tag size="is-small" type="is-warning">{{ props.row.outbound }}</b-tag>
<span v-if="props.row.outboundType === 'routingA'" class="is-size-7 has-text-grey"> (RoutingA)</span>
</span>
<span v-else class="is-size-7 has-text-grey">—</span>
</b-table-column>
<b-table-column v-slot="props" :label="$t('operations.name')" width="60">
<b-button
size="is-small"
type="is-danger"
@@ -43,7 +50,7 @@
<p class="is-size-6 has-text-weight-semibold" style="margin-bottom: 0.5rem">
{{ $t("customInbound.addNew") }}
</p>
<b-field grouped>
<b-field grouped group-multiline>
<b-field :label="$t('customInbound.tag')" expanded label-position="on-border">
<b-input
v-model="form.tag"
@@ -66,12 +73,42 @@
:placeholder="$t('customInbound.portPlaceholder')"
></b-input>
</b-field>
</b-field>
<!-- Outbound binding -->
<b-field grouped group-multiline>
<b-field :label="$t('customInbound.outbound')" expanded label-position="on-border">
<b-select v-model="form.outbound" expanded :placeholder="$t('customInbound.outboundPlaceholder')">
<option
v-for="ob in outbounds"
:key="ob"
:value="ob"
>{{ ob }}</option>
</b-select>
</b-field>
<b-field :label="$t('customInbound.outboundType')" label-position="on-border">
<b-select v-model="form.outboundType">
<option value="direct">{{ $t("customInbound.outboundTypeDirect") }}</option>
<option value="routingA">{{ $t("customInbound.outboundTypeRoutingA") }}</option>
</b-select>
</b-field>
<b-field label=" " label-position="on-border">
<b-button type="is-primary" :loading="adding" @click="handleAdd">
{{ $t("operations.add") }}
</b-button>
</b-field>
</b-field>
<!-- RoutingA rules editor (shown when outboundType is routingA) -->
<b-field v-if="form.outboundType === 'routingA'" :label="$t('customInbound.routingARules')" label-position="on-border">
<b-input
v-model="form.routingARules"
type="textarea"
:placeholder="$t('customInbound.routingARulesPlaceholder')"
rows="6"
></b-input>
</b-field>
<b-message type="is-info" size="is-small" class="after-line-dot5">
{{ $t("customInbound.hint") }}
</b-message>
@@ -92,15 +129,20 @@ export default {
i18n,
data: () => ({
inbounds: [],
outbounds: [],
form: {
tag: "",
protocol: "socks",
port: "",
outbound: "",
outboundType: "direct",
routingARules: "",
},
adding: false,
}),
created() {
this.fetchInbounds();
this.fetchOutbounds();
},
methods: {
fetchInbounds() {
@@ -110,6 +152,13 @@ export default {
}
});
},
fetchOutbounds() {
this.$axios({ url: apiRoot + "/outbound" }).then((res) => {
if (res.data.code === "SUCCESS") {
this.outbounds = res.data.data.outbounds || [];
}
});
},
handleAdd() {
if (!this.form.tag || !this.form.port) {
this.$buefy.toast.open({
@@ -120,6 +169,15 @@ export default {
});
return;
}
if (!this.form.outbound) {
this.$buefy.toast.open({
message: this.$t("customInbound.outboundRequired"),
type: "is-warning",
position: "is-top",
queue: false,
});
return;
}
this.adding = true;
this.$axios({
url: apiRoot + "/customInbound",
@@ -128,12 +186,15 @@ export default {
tag: this.form.tag.trim(),
protocol: this.form.protocol,
port: Number(this.form.port),
outbound: this.form.outbound,
outboundType: this.form.outboundType,
routingARules: this.form.outboundType === "routingA" ? this.form.routingARules : "",
},
})
.then((res) => {
handleResponse(res, this, () => {
this.inbounds = res.data.data.inbounds || [];
this.form = { tag: "", protocol: "socks", port: "" };
this.form = { tag: "", protocol: "socks", port: "", outbound: "", outboundType: "direct", routingARules: "" };
});
})
.finally(() => {
@@ -8,6 +8,17 @@
<p class="modal-card-title">RoutingA</p>
</header>
<section class="modal-card-body rules">
<!-- Deprecation warning for inbound definitions -->
<b-message
v-if="hasInboundDef"
type="is-warning"
size="is-small"
:active="true"
closable
@close="hasInboundDef = false"
>
{{ $t("routingA.inboundDeprecated") }}
</b-message>
<b-input
v-model="routingA"
type="textarea"
@@ -18,6 +29,7 @@
autocorrect="off"
autocapitalize="off"
spellcheck="false"
@input="checkInboundDef"
/>
</section>
<footer class="modal-card-foot">
@@ -50,6 +62,7 @@ export default {
name: "ModalCustomRoutingA",
data: () => ({
routingA: "",
hasInboundDef: false,
}),
mounted() {
this.$axios({
@@ -61,6 +74,7 @@ export default {
this,
() => {
this.routingA = res.data.data.routingA;
this.checkInboundDef();
},
() => {
this.$parent.close();
@@ -85,10 +99,34 @@ export default {
);
}
},
checkInboundDef() {
// Check if the RoutingA text contains inbound definitions (deprecated feature)
const lines = (this.routingA || "").split("\n");
this.hasInboundDef = lines.some(
(line) =>
line.trim().startsWith("inbound(") || line.trim().startsWith("inbound (")
);
},
handleClickManual() {
window.open("https://github.com/v2rayA/v2rayA/wiki/RoutingA", "_blank");
},
handleClickSubmit() {
// If inbound definitions exist, show a confirmation dialog
if (this.hasInboundDef) {
this.$buefy.dialog.confirm({
message: this.$t("routingA.inboundDeprecatedConfirm"),
type: "is-warning",
confirmText: this.$t("operations.save"),
cancelText: this.$t("operations.cancel"),
onConfirm: () => {
this.submitRoutingA();
},
});
} else {
this.submitRoutingA();
}
},
submitRoutingA() {
this.$axios({
url: apiRoot + "/routingA",
method: "put",
@@ -97,6 +135,16 @@ export default {
},
}).then((res) => {
handleResponse(res, this, () => {
// Show warning from server if any
if (res.data.data && res.data.data.warning) {
this.$buefy.toast.open({
message: res.data.data.warning,
type: "is-warning",
position: "is-top",
duration: 8000,
queue: false,
});
}
this.$parent.close();
});
});
+20 -1
View File
@@ -482,8 +482,27 @@ export default {
this.expandedGroup = null;
}
this.$emit("group-deleted", res.data.data.outbounds);
} else {
// Show error message from server (e.g., bound custom inbounds)
this.$buefy.toast.open({
message: res.data.message || this.$t("common.fail"),
type: "is-warning",
position: "is-top",
duration: 8000,
queue: false,
});
}
} catch (_) {}
} catch (err) {
// Show error from server response
const msg = err?.response?.data?.message || err?.message || this.$t("common.fail");
this.$buefy.toast.open({
message: msg,
type: "is-warning",
position: "is-top",
duration: 8000,
queue: false,
});
}
},
},
mounted() {
+10
View File
@@ -377,6 +377,8 @@ export default {
},
routingA: {
messages: ["click the button 'Help&Manual' for help"],
inboundDeprecated: "Defining inbounds in RoutingA is deprecated. The generated JSON config will NOT include those inbound ports. Please use the custom inbound settings with RoutingA rules instead.",
inboundDeprecatedConfirm: "This RoutingA configuration contains deprecated inbound definitions. The generated config will not include those inbound ports. Continue saving?",
},
outbound: {
addMessage: "Please input the proxy group name you want to add:",
@@ -476,5 +478,13 @@ export default {
hint: "Only SOCKS and HTTP protocols are supported. Tag must be unique and will be used as the v2ray core tag.",
fillAll: "Please fill in all fields",
deleteConfirm: "Delete inbound {tag}?",
outbound: "Bound Outbound Group",
outboundPlaceholder: "Select outbound group",
outboundType: "Binding Mode",
outboundTypeDirect: "Direct Select",
outboundTypeRoutingA: "RoutingA Rules",
outboundRequired: "Please select a bound outbound group",
routingARules: "RoutingA Rules",
routingARulesPlaceholder: "Enter RoutingA routing rules...",
},
};
+11 -1
View File
@@ -369,6 +369,8 @@ export default {
},
routingA: {
messages: ["点击“查看帮助”按钮以获取帮助"],
inboundDeprecated: "RoutingA 中定义入站(inbound)的功能已弃用,生成的 JSON 配置将不会包含对应的入站端口。请使用自定义入站设置中的 RoutingA 规则功能替代。",
inboundDeprecatedConfirm: "当前 RoutingA 配置包含已弃用的入站定义,生成的配置将不会包含这些入站端口。是否继续保存?",
},
outbound: {
addMessage: "请输入你想要添加的代理分组名称:",
@@ -477,7 +479,15 @@ export default {
portPlaceholder: "如 10800",
empty: "暂无自定义入站",
hint: "入站端口仅支持 SOCKS 和 HTTP 协议,标签必须唯一,将作为 v2ray core 的 tag 使用。",
fillAll: "请喆写全部字段",
fillAll: "请填写全部字段",
deleteConfirm: "确认删除入站 {tag}?",
outbound: "绑定出口组",
outboundPlaceholder: "请选择出口组",
outboundType: "绑定方式",
outboundTypeDirect: "直接选择",
outboundTypeRoutingA: "RoutingA 规则",
outboundRequired: "请选择绑定的出口组",
routingARules: "RoutingA 分流规则",
routingARulesPlaceholder: "请输入 RoutingA 分流规则...",
},
};
+120 -53
View File
@@ -656,59 +656,10 @@ func parseRoutingA(t *Template, routingInboundTags []string) error {
},
})
case "inbound":
// reform from outbound
in := coreObj.Inbound{
Tag: o.Name,
Protocol: o.Value.Name,
Listen: server.Address,
Port: server.Port,
Settings: &coreObj.InboundSettings{
UDP: false,
},
Sniffing: coreObj.Sniffing{
Enabled: false,
DestOverride: []string{"http", "tls"},
RouteOnly: false,
},
}
if sniffing := proto.NamedParams["sniffing"]; len(sniffing) > 0 {
// support inbound:a=socks(address: 127.0.0.1, port: 1080, sniffing:tls, sniffing:http)
// support inbound:a=http(address: 127.0.0.1, port: 1081, sniffing:"http,tls")
in.Sniffing.Enabled = true
var sniffs []string
for _, sniff := range sniffing {
fields := strings.Split(sniff, ",")
for i := range fields {
fields[i] = strings.TrimSpace(fields[i])
}
sniffs = append(sniffs, fields...)
}
in.Sniffing.DestOverride = sniffs
}
if proto.Name == "socks" {
if len(server.Users) > 0 {
in.Settings.Auth = "password"
}
if udp := proto.NamedParams["udp"]; len(udp) > 0 {
in.Settings.UDP = udp[0] == "true"
}
if userLevels := proto.NamedParams["userLevel"]; len(userLevels) > 0 {
userLevel, err := strconv.Atoi(userLevels[0])
if err == nil {
in.Settings.UserLevel = userLevel
}
}
}
if len(server.Users) > 0 {
for _, u := range server.Users {
in.Settings.Accounts = append(in.Settings.Accounts, coreObj.Account{
User: u.User,
Pass: u.Pass,
})
}
}
t.Inbounds = append(t.Inbounds, in)
routingInboundTags = append(routingInboundTags, o.Name)
// DEPRECATED: inbound definition in RoutingA is no longer supported.
// Log a warning and skip creating the inbound.
log.Warn("parseRoutingA: inbound definition '%s' is deprecated and will be ignored. "+
"Use custom inbound settings with RoutingA rules instead.", o.Name)
}
case "freedom":
settings := coreObj.Settings{}
@@ -825,6 +776,99 @@ func parseRoutingA(t *Template, routingInboundTags []string) error {
return nil
}
// parseRoutingARules parses RoutingA rule text and returns routing rules
// filtered by the given inboundTag. This is used for custom inbound RoutingA rules.
// It does NOT create any inbounds or outbounds - only routing rules.
func parseRoutingARules(rulesText string, inboundTag string) (rules []coreObj.RoutingRule, err error) {
lines := strings.Split(rulesText, "\n")
hardcodeReplacement := regexp.MustCompile(`\$\$.+?\$\$`)
for i := range lines {
hardcodes := hardcodeReplacement.FindAllString(lines[i], -1)
for _, hardcode := range hardcodes {
env := strings.TrimSuffix(strings.TrimPrefix(hardcode, "$$"), "$$")
val, ok := os.LookupEnv(env)
if !ok {
log.Error("parseRoutingARules: Environment variable \"%v\" is not found", env)
} else {
log.Info("parseRoutingARules: Environment variable %v=%v", env, strconv.Quote(val))
}
lines[i] = strings.Replace(lines[i], hardcode, val, 1)
}
}
parsedRules, err := RoutingA.Parse(strings.Join(lines, "\n"))
if err != nil {
return nil, err
}
for _, rule := range parsedRules {
switch rule := rule.(type) {
case RoutingA.Routing:
rr := deepcopy.Copy(coreObj.RoutingRule{
Type: "field",
OutboundTag: rule.Out,
InboundTag: []string{inboundTag},
}).(coreObj.RoutingRule)
for _, f := range rule.And {
switch f.Name {
case "domain", "domains":
for k, vv := range f.NamedParams {
for _, v := range vv {
if k == "contains" {
rr.Domain = append(rr.Domain, v)
continue
}
if k == "ext" {
datFilenameAndTag := strings.SplitN(v, ":", 2)
if len(datFilenameAndTag) < 2 {
return nil, fmt.Errorf("%v: tag is not given", v)
}
if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) {
return nil, fmt.Errorf("%v: file is not found", datFilenameAndTag[0])
}
}
rr.Domain = append(rr.Domain, fmt.Sprintf("%v:%v", k, v))
}
}
rr.Domain = append(rr.Domain, f.Params...)
case "ip":
for k, vv := range f.NamedParams {
for _, v := range vv {
if k == "ext" {
datFilenameAndTag := strings.SplitN(v, ":", 2)
if len(datFilenameAndTag) < 2 {
return nil, fmt.Errorf("%v: tag is not given", v)
}
if !asset.DoesV2rayAssetExist(datFilenameAndTag[0]) {
return nil, fmt.Errorf("%v: file is not found", datFilenameAndTag[0])
}
}
rr.IP = append(rr.IP, fmt.Sprintf("%v:%v", k, v))
}
}
rr.IP = append(rr.IP, f.Params...)
case "network":
rr.Network = strings.Join(f.Params, ",")
case "port":
rr.Port = strings.Join(f.Params, ",")
case "sourcePort":
rr.SourcePort = strings.Join(f.Params, ",")
case "protocol":
rr.Protocol = f.Params
case "source":
rr.Source = f.Params
case "user":
rr.User = f.Params
case "inboundTag":
rr.InboundTag = f.Params
}
}
if rr.OutboundTag != "" {
rules = append(rules, rr)
}
}
}
return rules, nil
}
func (t *Template) setTransparentRouting() (err error) {
defaultOutbound, _ := t.FirstProxyOutboundName(nil)
switch t.Setting.Transparent {
@@ -1248,6 +1292,29 @@ func (t *Template) setInbound(setting *configure.Setting) error {
ib.Settings = &coreObj.InboundSettings{UDP: true}
}
t.Inbounds = append(t.Inbounds, ib)
// Generate per-inbound routing rules based on the bound outbound group
if ci.Outbound != "" && ci.OutboundType != "" {
switch ci.OutboundType {
case "direct":
// Direct single outbound: route all traffic from this inbound to the bound outbound group
t.Routing.Rules = append(t.Routing.Rules, coreObj.RoutingRule{
Type: "field",
OutboundTag: ci.Outbound,
InboundTag: []string{ci.Tag},
})
case "routingA":
// RoutingA rules: parse and apply with InboundTag filter
if ci.RoutingARules != "" {
rules, err := parseRoutingARules(ci.RoutingARules, ci.Tag)
if err != nil {
log.Warn("setInbound: failed to parse RoutingA rules for inbound %s: %v", ci.Tag, err)
} else {
t.Routing.Rules = append(t.Routing.Rules, rules...)
}
}
}
}
}
if IsTransparentOn(t.Setting) {
switch t.Setting.TransparentType {
+21 -3
View File
@@ -5,10 +5,16 @@ import "github.com/v2rayA/v2rayA/db"
// CustomInbound represents a user-defined inbound proxy port.
// Protocol must be "socks" or "http".
// Tag must be unique and is used as the inbound tag in v2ray config.
// Outbound specifies the outbound group this inbound is bound to.
// OutboundType specifies the binding mode: "direct" or "routingA".
// RoutingARules contains the RoutingA rule text when OutboundType is "routingA".
type CustomInbound struct {
Tag string `json:"tag"`
Protocol string `json:"protocol"` // "socks" or "http"
Port int `json:"port"`
Tag string `json:"tag"`
Protocol string `json:"protocol"` // "socks" or "http"
Port int `json:"port"`
Outbound string `json:"outbound"` // bound outbound group name
OutboundType string `json:"outboundType"` // "direct" or "routingA"
RoutingARules string `json:"routingARules"` // RoutingA rules text (when outboundType="routingA")
}
// GetCustomInbounds returns all custom inbound configs stored in DB.
@@ -25,3 +31,15 @@ func GetCustomInbounds() []CustomInbound {
func SetCustomInbounds(inbounds []CustomInbound) error {
return db.Set("system", "customInbounds", inbounds)
}
// GetCustomInboundsByOutbound returns all custom inbounds bound to the given outbound group.
func GetCustomInboundsByOutbound(outbound string) []CustomInbound {
all := GetCustomInbounds()
var result []CustomInbound
for _, ci := range all {
if ci.Outbound == outbound {
result = append(result, ci)
}
}
return result
}
@@ -5,8 +5,11 @@ import (
"net"
"github.com/gin-gonic/gin"
"github.com/v2rayA/RoutingA"
"github.com/v2rayA/v2rayA/common"
"github.com/v2rayA/v2rayA/db/configure"
"regexp"
"strings"
)
func GetCustomInbound(ctx *gin.Context) {
@@ -36,6 +39,52 @@ func PostCustomInbound(ctx *gin.Context) {
// basic port check already done above
}
// Validate outbound binding
if ci.Outbound == "" {
common.ResponseError(ctx, logError(fmt.Errorf("outbound group is required")))
return
}
if ci.OutboundType != "direct" && ci.OutboundType != "routingA" {
common.ResponseError(ctx, logError(fmt.Errorf("outboundType must be 'direct' or 'routingA'")))
return
}
// Verify the outbound group exists
outbounds := configure.GetOutbounds()
outboundExists := false
for _, ob := range outbounds {
if ob == ci.Outbound {
outboundExists = true
break
}
}
if !outboundExists {
common.ResponseError(ctx, logError(fmt.Errorf("outbound group '%s' does not exist", ci.Outbound)))
return
}
// If outboundType is "routingA", validate the RoutingA rules
if ci.OutboundType == "routingA" {
if ci.RoutingARules == "" {
common.ResponseError(ctx, logError(fmt.Errorf("routingA rules are required when outboundType is 'routingA'")))
return
}
// Parse and validate RoutingA rules
lines := strings.Split(ci.RoutingARules, "\n")
hardcodeReplacement := regexp.MustCompile(`\$\$.+?\$\$`)
for i := range lines {
hardcodes := hardcodeReplacement.FindAllString(lines[i], -1)
for _, hardcode := range hardcodes {
lines[i] = strings.Replace(lines[i], hardcode, "", 1)
}
}
_, err := RoutingA.Parse(strings.Join(lines, "\n"))
if err != nil {
common.ResponseError(ctx, logError(fmt.Errorf("invalid RoutingA rules: %w", err)))
return
}
}
inbounds := configure.GetCustomInbounds()
// check duplicate tag and port
for _, existing := range inbounds {
+16
View File
@@ -88,6 +88,22 @@ func DeleteOutbound(ctx *gin.Context) {
common.ResponseError(ctx, logError("outbound \"proxy\" cannot be deleted"))
return
}
// Check if any custom inbound is bound to this outbound group
boundInbounds := configure.GetCustomInboundsByOutbound(data.Outbound)
if len(boundInbounds) > 0 {
names := make([]string, len(boundInbounds))
for i, ci := range boundInbounds {
names[i] = fmt.Sprintf("%s (port %d, %s)", ci.Tag, ci.Port, ci.Protocol)
}
common.ResponseError(ctx, logError(fmt.Errorf(
"cannot delete outbound group '%s': the following custom inbounds are bound to it:\n%s\nPlease unbind them first",
data.Outbound,
strings.Join(names, "\n"),
)))
return
}
if w := configure.GetConnectedServersByOutbound(data.Outbound); w != nil {
if err := service.Disconnect(configure.Which{Outbound: data.Outbound}, true); err != nil {
common.ResponseError(ctx, logError(err))
+18
View File
@@ -37,10 +37,28 @@ func PutRoutingA(ctx *gin.Context) {
common.ResponseError(ctx, logError(err))
return
}
// Check for deprecated inbound definitions in RoutingA rules
hasInboundDef := false
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "inbound(") || strings.HasPrefix(trimmed, "inbound (") {
hasInboundDef = true
break
}
}
err = configure.SetRoutingA(&data.RoutingA)
if err != nil {
common.ResponseError(ctx, logError(err))
return
}
if hasInboundDef {
common.ResponseSuccess(ctx, gin.H{
"warning": "RoutingA 中定义入站(inbound)的功能已弃用,生成的 JSON 配置将不会包含对应的入站端口。请使用自定义入站设置中的 RoutingA 规则功能替代。",
})
return
}
common.ResponseSuccess(ctx, nil)
}