diff options
| author | MHSanaei <ho3ein.sanaei@gmail.com> | 2024-01-11 09:27:21 +0300 |
|---|---|---|
| committer | MHSanaei <ho3ein.sanaei@gmail.com> | 2024-01-11 09:27:21 +0300 |
| commit | bee690429f5a5a4639679236b414d42dbdd6b762 (patch) | |
| tree | 0134c71ef87a417f9dc32bec6bdb1e9530c13c3a | |
| parent | 2111632702ad8b370bf3dc224b40f0c7385001ab (diff) | |
WARP via wireguard
Co-Authored-By: Alireza Ahmadi <alireza7@gmail.com>
| -rw-r--r-- | web/assets/js/model/outbound.js | 2 | ||||
| -rw-r--r-- | web/controller/xray_setting.go | 23 | ||||
| -rw-r--r-- | web/html/xui/warp_modal.html | 204 | ||||
| -rw-r--r-- | web/html/xui/xray.html | 70 | ||||
| -rw-r--r-- | web/service/setting.go | 12 | ||||
| -rw-r--r-- | web/service/xray_setting.go | 144 |
6 files changed, 420 insertions, 35 deletions
diff --git a/web/assets/js/model/outbound.js b/web/assets/js/model/outbound.js index b8ce2f77..0191c4a4 100644 --- a/web/assets/js/model/outbound.js +++ b/web/assets/js/model/outbound.js @@ -988,7 +988,7 @@ Outbound.WireguardSettings.Peer = class extends CommonClass { return { publicKey: this.publicKey, preSharedKey: this.psk.length>0 ? this.psk : undefined, - allowedIPs: this.allowedIPs ? this.allowedIPs.split(",") : undefined, + allowedIPs: this.allowedIPs ? this.allowedIPs : undefined, endpoint: this.endpoint, keepAlive: this.keepAlive?? undefined, }; diff --git a/web/controller/xray_setting.go b/web/controller/xray_setting.go index d4deacd9..09e9115f 100644 --- a/web/controller/xray_setting.go +++ b/web/controller/xray_setting.go @@ -26,6 +26,7 @@ func (a *XraySettingController) initRouter(g *gin.RouterGroup) { g.POST("/update", a.updateSetting) g.GET("/getXrayResult", a.getXrayResult) g.GET("/getDefaultJsonConfig", a.getDefaultXrayConfig) + g.POST("/warp/:action", a.warp) } func (a *XraySettingController) getXraySetting(c *gin.Context) { @@ -61,3 +62,25 @@ func (a *XraySettingController) getDefaultXrayConfig(c *gin.Context) { func (a *XraySettingController) getXrayResult(c *gin.Context) { jsonObj(c, a.XrayService.GetXrayResult(), nil) } + +func (a *XraySettingController) warp(c *gin.Context) { + action := c.Param("action") + var resp string + var err error + switch action { + case "data": + resp, err = a.XraySettingService.GetWarp() + case "config": + resp, err = a.XraySettingService.GetWarpConfig() + case "reg": + skey := c.PostForm("privateKey") + pkey := c.PostForm("publicKey") + resp, err = a.XraySettingService.RegWarp(skey, pkey) + case "license": + license := c.PostForm("license") + println(license) + resp, err = a.XraySettingService.SetWarpLicence(license) + } + + jsonObj(c, resp, err) +} diff --git a/web/html/xui/warp_modal.html b/web/html/xui/warp_modal.html new file mode 100644 index 00000000..c9f86603 --- /dev/null +++ b/web/html/xui/warp_modal.html @@ -0,0 +1,204 @@ +{{define "warpModal"}} +<a-modal id="warp-modal" v-model="warpModal.visible" title="Cloudflare WARP" + :confirm-loading="warpModal.confirmLoading" :closable="true" :mask-closable="true" + :footer="null" :class="themeSwitcher.currentTheme"> + <template v-if="ObjectUtil.isEmpty(warpModal.warpData)"> + <a-button icon="api" @click="register" :loading="warpModal.confirmLoading">{{ i18n "pages.inbounds.create" }}</a-button> + </template> + <template v-else> + <table style="margin: 5px 0; width: 100%;"> + <tr class="client-table-odd-row"> + <td>Access Token</td> + <td>[[ warpModal.warpData.access_token ]]</td> + </tr> + <tr> + <td>Devide ID</td> + <td>[[ warpModal.warpData.device_id ]]</td> + </tr> + <tr class="client-table-odd-row"> + <td>License Key</td> + <td>[[ warpModal.warpData.license_key ]]</td> + </tr> + <tr> + <td>Private Key</td> + <td>[[ warpModal.warpData.private_key ]]</td> + </tr> + </table> + <a-divider style="margin: 0;">{{ i18n "pages.settings.toasts.modifySettings" }}</a-divider> + <a-collapse style="margin: 10px 0;"> + <a-collapse-panel header='WARP/WARP+ License Key'> + <a-form :colon="false" :label-col="{ md: {span:6} }" :wrapper-col="{ md: {span:14} }"> + <a-form-item label="License Key"> + <a-input v-model="warpPlus"></a-input> + <a-button @click="updateLicense(warpPlus)" :disabled="warpPlus.length<26" :loading="warpModal.confirmLoading">{{ i18n "pages.inbounds.update" }}</a-button> + </a-form-item> + </a-form> + </a-collapse-panel> + </a-collapse> + <a-divider style="margin: 0;">{{ i18n "pages.settings.toasts.getSettings" }}</a-divider> + <a-button icon="sync" @click="getConfig" style="margin-bottom: 10px;" :loading="warpModal.confirmLoading">{{ i18n "info" }}</a-button> + <template v-if="!ObjectUtil.isEmpty(warpModal.warpConfig)"> + <table style="width: 100%"> + <tr class="client-table-odd-row"> + <td>Device Name</td> + <td>[[ warpModal.warpConfig.name ]]</td> + </tr> + <tr> + <td>Device Model</td> + <td>[[ warpModal.warpConfig.model ]]</td> + </tr> + <tr class="client-table-odd-row"> + <td>Device Active</td> + <td>[[ warpModal.warpConfig.enabled ]]</td> + </tr> + <template v-if="!ObjectUtil.isEmpty(warpModal.warpConfig.account)"> + <tr> + <td>Account Type</td> + <td>[[ warpModal.warpConfig.account.account_type ]]</td> + </tr> + <tr class="client-table-odd-row"> + <td>Role</td> + <td>[[ warpModal.warpConfig.account.role ]]</td> + </tr> + <tr> + <td>Premium Data</td> + <td>[[ sizeFormat(warpModal.warpConfig.account.premium_data) ]]</td> + </tr> + <tr class="client-table-odd-row"> + <td>Quota</td> + <td>[[ sizeFormat(warpModal.warpConfig.account.quota) ]]</td> + </tr> + <tr v-if="!ObjectUtil.isEmpty(warpModal.warpConfig.account.usage)"> + <td>Usage</td> + <td>[[ sizeFormat(warpModal.warpConfig.account.usage) ]]</td> + </tr> + </template> + </table> + <a-divider style="margin: 10px 0;">WARP {{ i18n "pages.xray.rules.outbound" }}</a-divider> + <a-form :label-col="{ md: {span:8} }" :wrapper-col="{ md: {span:14} }"> + <a-form-item label="{{ i18n "status" }}"> + <template v-if="warpOutboundIndex>=0"> + <a-tag color="green">{{ i18n "enabled" }}</a-tag> + <a-button @click="resetOutbound" :loading="warpModal.confirmLoading">{{ i18n "reset" }}</a-button> + </template> + <template v-else> + <a-tag color="orange">{{ i18n "disabled" }}</a-tag> + <a-button @click="addOutbound" :loading="warpModal.confirmLoading">{{ i18n "pages.xray.outbound.addOutbound" }}</a-button> + </template> + </a-form-item> + </a-form> + </template> + </template> +</a-modal> +<script> + + const warpModal = { + visible: false, + confirmLoading: false, + warpData: null, + warpConfig: null, + warpOutbound: null, + show() { + this.visible = true; + this.warpConfig = null; + this.getData(); + + }, + close() { + this.visible = false; + this.loading(false); + }, + loading(loading) { + this.confirmLoading = loading; + }, + async getData(){ + this.loading(true); + const msg = await HttpUtil.post('/xui/xray/warp/data'); + this.loading(false); + if (msg.success) { + this.warpData = msg.obj.length>0 ? JSON.parse(msg.obj): null; + } + }, + }; + + new Vue({ + delimiters: ['[[', ']]'], + el: '#warp-modal', + data: { + warpModal: warpModal, + warpPlus: '', + }, + methods: { + collectConfig() { + config = warpModal.warpConfig.config; + peer = config.peers[0]; + if(config){ + warpModal.warpOutbound = Outbound.fromJson({ + tag: 'warp', + protocol: Protocols.Wireguard, + settings: { + mtu: 1420, + secretKey: warpModal.warpData.private_key, + address: Object.values(config.interface.addresses), + peers: [{ + publicKey: peer.public_key, + endpoint: peer.endpoint.host, + }], + kernelMode: false + } + }); + } + }, + async register(){ + warpModal.loading(true); + keys = Wireguard.generateKeypair(); + const msg = await HttpUtil.post('/xui/xray/warp/reg',keys); + if (msg.success) { + resp = JSON.parse(msg.obj); + warpModal.warpData = resp.data; + warpModal.warpConfig = resp.config; + this.collectConfig(); + } + warpModal.loading(false); + }, + async updateLicense(l){ + warpModal.loading(true); + const msg = await HttpUtil.post('/xui/xray/warp/license',{license: l}); + if (msg.success) { + warpModal.warpData = JSON.parse(msg.obj); + warpModal.warpConfig = null; + this.warpPlus = ''; + } + warpModal.loading(false); + }, + async getConfig(){ + warpModal.loading(true); + const msg = await HttpUtil.post('/xui/xray/warp/config'); + warpModal.loading(false); + if (msg.success) { + warpModal.warpConfig = JSON.parse(msg.obj); + this.collectConfig(); + } + }, + addOutbound(){ + app.templateSettings.outbounds.push(warpModal.warpOutbound.toJson()); + app.outboundSettings = JSON.stringify(app.templateSettings.outbounds); + warpModal.close(); + }, + resetOutbound(){ + app.templateSettings.outbounds[this.warpOutboundIndex] = warpModal.warpOutbound.toJson(); + app.outboundSettings = JSON.stringify(app.templateSettings.outbounds); + warpModal.close(); + } + }, + computed: { + warpOutboundIndex: { + get: function() { + return app.templateSettings ? app.templateSettings.outbounds.findIndex((o) => o.tag == 'warp') : -1; + } + } + } + }); + +</script> +{{end}} diff --git a/web/html/xui/xray.html b/web/html/xui/xray.html index 0cf7fd05..24035316 100644 --- a/web/html/xui/xray.html +++ b/web/html/xui/xray.html @@ -6,6 +6,7 @@ <link rel="stylesheet" href="{{ .base_path }}assets/codemirror/xq.css?{{ .cur_ver }}"> <link rel="stylesheet" href="{{ .base_path }}assets/codemirror/lint/lint.css"> +<script src="{{ .base_path }}assets/base64/base64.min.js"></script> <script src="{{ .base_path }}assets/js/model/outbound.js"></script> <script src="{{ .base_path }}assets/codemirror/codemirror.js"></script> <script src="{{ .base_path }}assets/codemirror/javascript.js"></script> @@ -80,12 +81,16 @@ </a-space> </a-col> <a-col :xs="24" :sm="16"> - <a-back-top :target="() => document.getElementById('content-layout')" visibility-height="200"> - </a-back-top> - <a-alert type="warning" style="float: right; width: fit-content" - message='{{ i18n "pages.settings.infoDesc" }}' - show-icon - > + <template> + <div> + <a-back-top :target="() => document.getElementById('content-layout')" visibility-height="200"> + </a-back-top> + <a-alert type="warning" style="float: right; width: fit-content" + message='{{ i18n "pages.settings.infoDesc" }}' + show-icon + > + </div> + </template> </a-col> </a-row> </a-card> @@ -217,10 +222,12 @@ </template> </a-alert> </a-row> + <template v-if="WarpExist"> <setting-list-item type="switch" title='{{ i18n "pages.xray.GoogleWARP"}}' desc='{{ i18n "pages.xray.GoogleWARPDesc"}}' v-model="GoogleWARPSettings"></setting-list-item> <setting-list-item type="switch" title='{{ i18n "pages.xray.OpenAIWARP"}}' desc='{{ i18n "pages.xray.OpenAIWARPDesc"}}' v-model="OpenAIWARPSettings"></setting-list-item> <setting-list-item type="switch" title='{{ i18n "pages.xray.NetflixWARP"}}' desc='{{ i18n "pages.xray.NetflixWARPDesc"}}' v-model="NetflixWARPSettings"></setting-list-item> <setting-list-item type="switch" title='{{ i18n "pages.xray.SpotifyWARP"}}' desc='{{ i18n "pages.xray.SpotifyWARPDesc"}}' v-model="SpotifyWARPSettings"></setting-list-item> + </template> </a-collapse-panel> </a-collapse> </a-tab-pane> @@ -334,6 +341,7 @@ </a-tab-pane> <a-tab-pane key="tpl-3" tab='{{ i18n "pages.xray.Outbounds"}}' style="padding-top: 20px;" force-render="true"> <a-button type="primary" icon="plus" @click="addOutbound()" style="margin-bottom: 10px;">{{ i18n "pages.xray.outbound.addOutbound" }}</a-button> + <a-button type="primary" @click="showWarp()" style="margin-bottom: 10px;">WARP</a-button> <a-table :columns="outboundColumns" bordered :row-key="r => r.key" :data-source="outboundData" @@ -421,12 +429,13 @@ {{template "ruleModal"}} {{template "outModal"}} {{template "reverseModal"}} +{{template "warpModal"}} <script> const rulesColumns = [ { title: "#", align: 'center', width: 15, scopedSlots: { customRender: 'action' } }, { title: '{{ i18n "pages.xray.rules.source"}}', children: [ { title: 'IP', dataIndex: "source", align: 'center', width: 20, ellipsis: true }, - { title: 'port', dataIndex: 'sourcePort', align: 'center', width: 10, ellipsis: true } ]}, + { title: 'Port', dataIndex: 'sourcePort', align: 'center', width: 10, ellipsis: true } ]}, { title: '{{ i18n "pages.inbounds.network"}}', children: [ { title: 'L4', dataIndex: 'network', align: 'center', width: 10 }, { title: 'Protocol', dataIndex: 'protocol', align: 'center', width: 10, ellipsis: true }, @@ -461,6 +470,7 @@ { title: '{{ i18n "pages.xray.outbound.tag"}}', dataIndex: 'tag', align: 'center', width: 50 }, { title: '{{ i18n "pages.xray.outbound.domain"}}', dataIndex: 'domain', align: 'center', width: 50 }, ]; + const app = new Vue({ delimiters: ['[[', ']]'], el: '#app', @@ -505,23 +515,10 @@ domainStrategy: "UseIPv4" } }, - warpSettings: { - tag: "WARP", - protocol: "socks", - settings: { - servers: [ - { - address: "127.0.0.1", - port: 40000 - } - ] - } - }, directSettings: { tag: "direct", protocol: "freedom" }, - OutboundDomainStrategies: ["AsIs", "UseIP", "UseIPv4", "UseIPv6"], routingDomainStrategies: ["AsIs", "IPIfNonMatch", "IPOnDemand"], settingsData: { protocols: { @@ -532,7 +529,7 @@ cn: ["geoip:cn"], ir: ["ext:geoip_IR.dat:ir"], ru: ["geoip:ru"], - vn: ["ext:geoip_VN.dat:vn"], + vn: ["ext:geoip_VN.dat:vn"], }, domains: { ads: [ @@ -562,11 +559,11 @@ "regexp:.*\\.xn--mgba3a4f16a$", // .ایران "ext:geosite_IR.dat:ir" ], - vn: [ - "regexp:.*\\.vn$", + vn: [ + "regexp:.*\\.vn$", "ext:geosite_VN.dat:vn", "ext:geosite_VN.dat:ads" - ] + ] }, familyProtectDNS: { "servers": [ @@ -670,13 +667,13 @@ } }, syncRulesWithOutbound(tag, setting) { - const newTemplateSettings = {...this.templateSettings}; + const newTemplateSettings = this.templateSettings; const haveRules = newTemplateSettings.routing.rules.some((r) => r?.outboundTag === tag); const outboundIndex = newTemplateSettings.outbounds.findIndex((o) => o.tag === tag); - if (!haveRules && outboundIndex >= 0) { - newTemplateSettings.outbounds.splice(outboundIndex, 1); + if (!haveRules && outboundIndex > 0) { + newTemplateSettings.outbounds.splice(outboundIndex); } - if (haveRules && outboundIndex === -1) { + if (haveRules && outboundIndex < 0) { newTemplateSettings.outbounds.push(setting); } this.templateSettings = newTemplateSettings; @@ -774,6 +771,8 @@ break; case Protocols.DNS: return [o.settings.address + ':' + o.settings.port]; + case Protocols.Wireguard: + return o.settings.peers.map(peer => peer.endpoint); default: return null; } @@ -939,13 +938,16 @@ rules = this.templateSettings.routing.rules; rules.splice(index,1); this.routingRuleSettings = JSON.stringify(rules); + }, + showWarp(){ + warpModal.show(); } }, async mounted() { await this.getXraySetting(); await this.getXrayResult(); while (true) { - await PromiseUtil.sleep(600); + await PromiseUtil.sleep(800); this.saveBtnDisable = this.oldXraySetting === this.xraySetting; } }, @@ -1113,11 +1115,10 @@ }, warpDomains: { get: function () { - return this.templateRuleGetter({ outboundTag: "WARP", property: "domain" }); + return this.templateRuleGetter({ outboundTag: "warp", property: "domain" }); }, set: function (newValue) { - this.templateRuleSetter({ outboundTag: "WARP", property: "domain", data: newValue }); - this.syncRulesWithOutbound("WARP", this.warpSettings); + this.templateRuleSetter({ outboundTag: "warp", property: "domain", data: newValue }); } }, manualBlockedIPs: { @@ -1435,6 +1436,11 @@ } } }, + WarpExist: { + get: function() { + return this.templateSettings ? this.templateSettings.outbounds.findIndex((o) => o.tag == "warp")>=0 : false; + }, + }, GoogleWARPSettings: { get: function () { return doAllItemsExist(this.settingsData.domains.google, this.warpDomains); diff --git a/web/service/setting.go b/web/service/setting.go index 25770373..89c78662 100644 --- a/web/service/setting.go +++ b/web/service/setting.go @@ -58,6 +58,7 @@ var defaultValueMap = map[string]string{ "subShowInfo": "true", "subURI": "", "datepicker": "gregorian", + "warp": "", } type SettingService struct { @@ -423,6 +424,10 @@ func (s *SettingService) GetSubShowInfo() (bool, error) { return s.getBool("subShowInfo") } +func (s *SettingService) GetPageSize() (int, error) { + return s.getInt("pageSize") +} + func (s *SettingService) GetSubURI() (string, error) { return s.getString("subURI") } @@ -431,8 +436,11 @@ func (s *SettingService) GetDatepicker() (string, error) { return s.getString("datepicker") } -func (s *SettingService) GetPageSize() (int, error) { - return s.getInt("pageSize") +func (s *SettingService) GetWarp() (string, error) { + return s.getString("warp") +} +func (s *SettingService) SetWarp(data string) error { + return s.setString("warp", data) } func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error { diff --git a/web/service/xray_setting.go b/web/service/xray_setting.go index 4550bde2..1d2e696e 100644 --- a/web/service/xray_setting.go +++ b/web/service/xray_setting.go @@ -1,8 +1,13 @@ package service import ( + "bytes" _ "embed" "encoding/json" + "fmt" + "net/http" + "os" + "time" "x-ui/util/common" "x-ui/xray" ) @@ -26,3 +31,142 @@ func (s *XraySettingService) CheckXrayConfig(XrayTemplateConfig string) error { } return nil } + +func (s *XraySettingService) GetWarpData() (string, error) { + warp, err := s.SettingService.GetWarp() + if err != nil { + return "", err + } + return warp, nil +} + +func (s *XraySettingService) GetWarpConfig() (string, error) { + var warpData map[string]string + warp, err := s.SettingService.GetWarp() + if err != nil { + return "", err + } + err = json.Unmarshal([]byte(warp), &warpData) + if err != nil { + return "", err + } + + url := fmt.Sprintf("https://api.cloudflareclient.com/v0a2158/reg/%s", warpData["device_id"]) + + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return "", err + } + req.Header.Set("Authorization", "Bearer "+warpData["access_token"]) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + buffer := bytes.NewBuffer(make([]byte, 8192)) + buffer.Reset() + _, err = buffer.ReadFrom(resp.Body) + if err != nil { + return "", err + } + + return buffer.String(), nil +} + +func (s *XraySettingService) RegWarp(secretKey string, publicKey string) (string, error) { + tos := time.Now().UTC().Format("2006-01-02T15:04:05.000Z") + hostName, _ := os.Hostname() + data := fmt.Sprintf(`{"key":"%s","tos":"%s","type": "PC","model": "x-ui", "name": "%s"}`, publicKey, tos, hostName) + + url := fmt.Sprintf("https://api.cloudflareclient.com/v0a2158/reg") + + req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data))) + if err != nil { + return "", err + } + + req.Header.Add("CF-Client-Version", "a-7.21-0721") + req.Header.Add("Content-Type", "application/json") + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + buffer := bytes.NewBuffer(make([]byte, 8192)) + buffer.Reset() + _, err = buffer.ReadFrom(resp.Body) + if err != nil { + return "", err + } + + var rspData map[string]interface{} + err = json.Unmarshal(buffer.Bytes(), &rspData) + if err != nil { + return "", err + } + + deviceId := rspData["id"].(string) + token := rspData["token"].(string) + license, ok := rspData["account"].(map[string]interface{})["license"].(string) + if !ok { + fmt.Println("Error accessing license value.") + return "", err + } + + warpData := fmt.Sprintf("{\n \"access_token\": \"%s\",\n \"device_id\": \"%s\",", token, deviceId) + warpData += fmt.Sprintf("\n \"license_key\": \"%s\",\n \"private_key\": \"%s\"\n}", license, secretKey) + + s.SettingService.SetWarp(warpData) + + result := fmt.Sprintf("{\n \"data\": %s,\n \"config\": %s\n}", warpData, buffer.String()) + + return result, nil +} + +func (s *XraySettingService) SetWarpLicence(license string) (string, error) { + var warpData map[string]string + warp, err := s.SettingService.GetWarp() + if err != nil { + return "", err + } + err = json.Unmarshal([]byte(warp), &warpData) + if err != nil { + return "", err + } + + url := fmt.Sprintf("https://api.cloudflareclient.com/v0a2158/reg/%s/account", warpData["device_id"]) + data := fmt.Sprintf(`{"license": "%s"}`, license) + + req, err := http.NewRequest("PUT", url, bytes.NewBuffer([]byte(data))) + if err != nil { + return "", err + } + req.Header.Set("Authorization", "Bearer "+warpData["access_token"]) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + buffer := bytes.NewBuffer(make([]byte, 8192)) + buffer.Reset() + _, err = buffer.ReadFrom(resp.Body) + if err != nil { + return "", err + } + + warpData["license_key"] = license + newWarpData, err := json.MarshalIndent(warpData, "", " ") + if err != nil { + return "", err + } + s.SettingService.SetWarp(string(newWarpData)) + println(string(newWarpData)) + + return string(newWarpData), nil +} |
