diff --git a/frontend/src/lib/xray/inbound-link.ts b/frontend/src/lib/xray/inbound-link.ts index e50f4cf4a..6904c9b03 100644 --- a/frontend/src/lib/xray/inbound-link.ts +++ b/frontend/src/lib/xray/inbound-link.ts @@ -1005,6 +1005,7 @@ export interface GenWireguardLinkInput { port: number; remark?: string; peerIndex: number; + finalmask?: FinalMaskStreamSettings; } // Wireguard share link: wireguard://@: @@ -1029,6 +1030,7 @@ export function genWireguardLink(input: GenWireguardLinkInput): string { if (typeof settings.mtu === 'number' && settings.mtu > 0) { url.searchParams.set('mtu', String(settings.mtu)); } + applyFinalMaskToParams(input.finalmask, url.searchParams); url.hash = encodeURIComponent(remark); return url.toString(); @@ -1722,6 +1724,7 @@ function wireguardFanout( port: e.port, remark: tunnelPeerRemark(remark, e.remark, i, p), peerIndex: i, + finalmask: inbound.streamSettings?.finalmask, }), ), ); diff --git a/frontend/src/test/wireguard-clients-link.test.ts b/frontend/src/test/wireguard-clients-link.test.ts index 4fefb1b7b..26ed8521f 100644 --- a/frontend/src/test/wireguard-clients-link.test.ts +++ b/frontend/src/test/wireguard-clients-link.test.ts @@ -88,3 +88,18 @@ describe('wireguard multi-client link/config fan-out', () => { expect(links[0]).toContain('address=10.0.0.9%2F32'); }); }); + +describe('wireguard finalmask', () => { + it('puts the inbound finalmask into the link as fm', () => { + const base = wgInbound(); + const mask = { tcp: [], udp: [{ type: 'salamander', settings: { password: 'pw' } }] }; + const inbound = InboundSchema.parse({ + ...base, + streamSettings: { network: 'tcp', security: 'none', tcpSettings: {}, finalmask: mask }, + }); + const link = genWireguardLinks({ inbound, remark: 'wg', fallbackHostname: 'h.example' }).split( + '\r\n', + )[0]; + expect(JSON.parse(new URL(link).searchParams.get('fm') ?? '')).toEqual(mask); + }); +}); diff --git a/internal/sub/json_service.go b/internal/sub/json_service.go index 35468cb5f..35fa0ead7 100644 --- a/internal/sub/json_service.go +++ b/internal/sub/json_service.go @@ -740,7 +740,7 @@ func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, c case "masque": newOutbounds = append(newOutbounds, s.genMasque(inbound, newStream, client)) case "wireguard": - wgOutbound := s.genWireguard(subReq, inbound, client) + wgOutbound := s.genWireguard(subReq, inbound, newStream, client) if wgOutbound == nil { continue } @@ -1120,7 +1120,7 @@ func (s *SubJsonService) genMasque(inbound *model.Inbound, newStream map[string] // mirroring genWireguardLink: the peer public key is derived from the inbound // secretKey, the client owns the private key / tunnel address / pre-shared key, // and the peer routes the full tunnel. Returns nil when the client has no key. -func (s *SubJsonService) genWireguard(subReq *SubService, inbound *model.Inbound, client model.Client) json_util.RawMessage { +func (s *SubJsonService) genWireguard(subReq *SubService, inbound *model.Inbound, stream map[string]any, client model.Client) json_util.RawMessage { if client.PrivateKey == "" { return nil } @@ -1160,6 +1160,9 @@ func (s *SubJsonService) genWireguard(subReq *SubService, inbound *model.Inbound "tag": "proxy", "settings": settings, } + if finalmask, ok := stream["finalmask"].(map[string]any); ok && hasFinalMaskContent(finalmask) { + outbound["streamSettings"] = map[string]any{"finalmask": finalmask} + } result, _ := json.MarshalIndent(outbound, "", " ") return result } diff --git a/internal/sub/json_service_test.go b/internal/sub/json_service_test.go index e89950af1..19463c7b0 100644 --- a/internal/sub/json_service_test.go +++ b/internal/sub/json_service_test.go @@ -533,7 +533,7 @@ func TestSubJsonServiceWireguard(t *testing.T) { AllowedIPs: []string{"10.0.0.2/32", "fd00::2/128"}, } - raw := NewSubJsonService("", "", "", "", nil).genWireguard(&SubService{}, inbound, client) + raw := NewSubJsonService("", "", "", "", nil).genWireguard(&SubService{}, inbound, nil, client) if raw == nil { t.Fatal("genWireguard returned nil for a valid wireguard client") } @@ -577,7 +577,7 @@ func TestSubJsonServiceWireguardNoKey(t *testing.T) { inbound := &model.Inbound{Listen: "203.0.113.9", Port: 51820, Protocol: model.WireGuard, Settings: `{}`} client := model.Client{Email: "user"} - if raw := NewSubJsonService("", "", "", "", nil).genWireguard(&SubService{}, inbound, client); raw != nil { + if raw := NewSubJsonService("", "", "", "", nil).genWireguard(&SubService{}, inbound, nil, client); raw != nil { t.Fatalf("genWireguard = %s, want nil for a keyless wireguard client", raw) } } @@ -598,3 +598,25 @@ func TestSubJsonServiceSkipsTUIC(t *testing.T) { t.Fatalf("getConfig emitted %d unsupported TUIC Xray config(s)", len(got)) } } + +func TestGenWireguardOutboundCarriesFinalMask(t *testing.T) { + serverPriv, _, _ := wgutil.GenerateWireguardKeypair() + clientPriv, _, _ := wgutil.GenerateWireguardKeypair() + inbound := &model.Inbound{Listen: "203.0.113.9", Port: 51820, Protocol: model.WireGuard, Settings: `{"secretKey":"` + serverPriv + `"}`} + client := model.Client{Email: "user", PrivateKey: clientPriv, AllowedIPs: []string{"10.0.0.2/32"}} + stream := map[string]any{"finalmask": map[string]any{"udp": []any{map[string]any{"type": "salamander"}}}} + raw := NewSubJsonService("", "", "", "", nil).genWireguard(&SubService{}, inbound, stream, client) + var out struct { + StreamSettings struct { + Finalmask struct { + UDP []struct{ Type string } `json:"udp"` + } `json:"finalmask"` + } `json:"streamSettings"` + } + if err := json.Unmarshal(raw, &out); err != nil { + t.Fatal(err) + } + if len(out.StreamSettings.Finalmask.UDP) != 1 || out.StreamSettings.Finalmask.UDP[0].Type != "salamander" { + t.Fatalf("outbound = %s, want salamander finalmask", raw) + } +} diff --git a/internal/sub/service.go b/internal/sub/service.go index 4287f28d2..5d1c21b62 100644 --- a/internal/sub/service.go +++ b/internal/sub/service.go @@ -1133,11 +1133,16 @@ func (s *SubService) genWireguardLink(inbound *model.Inbound, email string) stri if ka := client.KeepAliveSeconds(); ka > 0 { params["keepalive"] = strconv.Itoa(ka) } + if finalmask, ok := unmarshalStreamSettings(inbound.StreamSettings)["finalmask"].(map[string]any); ok { + applyFinalMaskParams(finalmask, params) + } endpoints := s.advertisedEndpoints(inbound) links := make([]string, 0, len(endpoints)) for _, e := range endpoints { link := fmt.Sprintf("wireguard://%s@%s", encodeUserinfo(client.PrivateKey), joinHostPort(e.Address, e.Port)) - links = append(links, buildLinkWithParams(link, params, s.endpointRemark(inbound, email, e.ep, ""))) + epParams := cloneStringMap(params) + applyEndpointFinalMask(e, epParams) + links = append(links, buildLinkWithParams(link, epParams, s.endpointRemark(inbound, email, e.ep, ""))) } return strings.Join(links, "\n") } diff --git a/internal/sub/service_wireguard_test.go b/internal/sub/service_wireguard_test.go index d58e8ec68..10364a98d 100644 --- a/internal/sub/service_wireguard_test.go +++ b/internal/sub/service_wireguard_test.go @@ -388,3 +388,44 @@ func TestGetSubs_WireGuardEmptyOptionalTunnelFieldsDoNotInheritShared(t *testing t.Fatalf("link inherited shared tunnel fields: %s", links[0]) } } + +func TestGenWireguardLinkCarriesFinalMask(t *testing.T) { + serverPriv, _, _ := wgutil.GenerateWireguardKeypair() + clientPriv, _, _ := wgutil.GenerateWireguardKeypair() + inbound := &model.Inbound{ + Listen: "203.0.113.7", + Port: 51820, + Protocol: model.WireGuard, + Settings: `{"secretKey":"` + serverPriv + `","clients":[{"email":"user","privateKey":"` + clientPriv + `","allowedIPs":["10.0.0.2/32"]}]}`, + StreamSettings: `{"finalmask":{"udp":[{"type":"salamander","settings":{"password":"pw"}}]}}`, + } + link := (&SubService{}).genWireguardLink(inbound, "user") + u, err := url.Parse(link) + if err != nil { + t.Fatal(err) + } + fm := u.Query().Get("fm") + if !strings.Contains(fm, `"type":"salamander"`) || !strings.Contains(fm, `"password":"pw"`) { + t.Fatalf("fm = %q, want salamander mask", fm) + } +} + +func TestGenWireguardLinkMergesHostFinalMask(t *testing.T) { + serverPriv, _, _ := wgutil.GenerateWireguardKeypair() + clientPriv, _, _ := wgutil.GenerateWireguardKeypair() + inbound := &model.Inbound{ + Listen: "203.0.113.7", + Port: 51820, + Protocol: model.WireGuard, + Settings: `{"secretKey":"` + serverPriv + `","clients":[{"email":"user","privateKey":"` + clientPriv + `","allowedIPs":["10.0.0.2/32"]}]}`, + StreamSettings: `{"externalProxy":[{"dest":"edge.example.com","port":443,"forceTls":"same","finalMask":"{\"udp\":[{\"type\":\"salamander\",\"settings\":{\"password\":\"host\"}}]}"}]}`, + } + link := (&SubService{}).genWireguardLink(inbound, "user") + u, err := url.Parse(link) + if err != nil { + t.Fatal(err) + } + if u.Host != "edge.example.com:443" || !strings.Contains(u.Query().Get("fm"), `"password":"host"`) { + t.Fatalf("link = %s, want host endpoint with host finalmask", link) + } +}