├── LICENSE ├── build.sh ├── config.toml ├── frp-web-h5 ├── .env.example ├── .gitignore ├── .vscode │ └── extensions.json ├── README.md ├── index.html ├── jsconfig.json ├── package.json ├── public │ └── favicon.ico ├── src │ ├── App.vue │ ├── api │ │ └── api.js │ ├── assets │ │ ├── base.css │ │ ├── logo.svg │ │ └── main.css │ ├── components │ │ ├── ModalTipsComponent.vue │ │ └── ModalWaitingComponent.vue │ ├── main.js │ ├── router │ │ └── index.js │ ├── utils │ │ ├── request.js │ │ └── strings.js │ └── views │ │ ├── Document.vue │ │ └── HomeView.vue └── vite.config.js ├── go.mod ├── handler └── api.go ├── main.go ├── model ├── config.go ├── local-server.go └── vhost.go ├── screenshot ├── screenshot1.png └── screenshot2.png └── utils ├── file.go ├── format.go ├── http.go ├── input.go ├── path.go ├── port.go └── signal.go /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | VERSION=v0.1 4 | 5 | PROJECT_PATH=$PWD 6 | 7 | echo '开始打包web' 8 | cd $PROJECT_PATH/frp-web-h5 9 | npm i 10 | npm run build 11 | 12 | echo '开始打包可执行程序' 13 | cd $PROJECT_PATH 14 | go get 15 | GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o frp-web-linux-amd64-$VERSION 16 | GOOS=windows GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o frp-web-windows-amd64-$VERSION.exe 17 | GOOS=darwin GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o frp-web-darwin-amd64-$VERSION 18 | 19 | 20 | cd $PROJECT_PATH 21 | ls -lh frp-web* 22 | 23 | -------------------------------------------------------------------------------- /config.toml: -------------------------------------------------------------------------------- 1 | [app] 2 | server = "http://api-frp.lixiang4u.xyz:7200" 3 | instance1 = "127.0.0.1:61234" # 防止客户端多开,导致frp配置异常 4 | -------------------------------------------------------------------------------- /frp-web-h5/.env.example: -------------------------------------------------------------------------------- 1 | VITE_BASE_URL="http://127.0.0.1:8000" -------------------------------------------------------------------------------- /frp-web-h5/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | .DS_Store 12 | dist 13 | dist-ssr 14 | coverage 15 | *.local 16 | 17 | /cypress/videos/ 18 | /cypress/screenshots/ 19 | 20 | # Editor directories and files 21 | .vscode/* 22 | !.vscode/extensions.json 23 | .idea 24 | *.suo 25 | *.ntvs* 26 | *.njsproj 27 | *.sln 28 | *.sw? 29 | 30 | *.tsbuildinfo 31 | -------------------------------------------------------------------------------- /frp-web-h5/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["Vue.volar", "Vue.vscode-typescript-vue-plugin"] 3 | } 4 | -------------------------------------------------------------------------------- /frp-web-h5/README.md: -------------------------------------------------------------------------------- 1 | # frp-web-h5 2 | 3 | This template should help get you started developing with Vue 3 in Vite. 4 | 5 | ## Recommended IDE Setup 6 | 7 | [VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin). 8 | 9 | ## Customize configuration 10 | 11 | See [Vite Configuration Reference](https://vitejs.dev/config/). 12 | 13 | ## Project Setup 14 | 15 | ```sh 16 | npm install 17 | ``` 18 | 19 | ### Compile and Hot-Reload for Development 20 | 21 | ```sh 22 | npm run dev 23 | ``` 24 | 25 | ### Compile and Minify for Production 26 | 27 | ```sh 28 | npm run build 29 | ``` 30 | -------------------------------------------------------------------------------- /frp-web-h5/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | frp-web 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /frp-web-h5/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "paths": { 4 | "@/*": ["./src/*"] 5 | } 6 | }, 7 | "exclude": ["node_modules", "dist"] 8 | } 9 | -------------------------------------------------------------------------------- /frp-web-h5/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frp-web-h5", 3 | "version": "0.0.0", 4 | "private": true, 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "preview": "vite preview" 10 | }, 11 | "dependencies": { 12 | "@vicons/material": "^0.12.0", 13 | "axios": "^1.6.7", 14 | "vue": "^3.4.15", 15 | "vue-router": "^4.2.5" 16 | }, 17 | "devDependencies": { 18 | "@vitejs/plugin-vue": "^5.0.3", 19 | "naive-ui": "^2.38.1", 20 | "vite": "^5.0.11" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /frp-web-h5/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lixiang4u/frp-web/3376cbe5e50da7e17d141a9cb1573a870509a3a0/frp-web-h5/public/favicon.ico -------------------------------------------------------------------------------- /frp-web-h5/src/App.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 12 | 13 | 15 | -------------------------------------------------------------------------------- /frp-web-h5/src/api/api.js: -------------------------------------------------------------------------------- 1 | import request from "../utils/request"; 2 | 3 | export default { 4 | getConfig: () => { 5 | return request.get( 6 | '/api/config' 7 | ) 8 | }, 9 | newVhost: (data) => { 10 | return request.post( 11 | '/api/vhost', data 12 | ) 13 | }, 14 | getVhosts: () => { 15 | return request.get( 16 | '/api/vhosts' 17 | ) 18 | }, 19 | removeVhost: (vhostId) => { 20 | return request.delete( 21 | `/api/vhost/${vhostId}` 22 | ) 23 | }, 24 | reloadVhost: () => { 25 | return request.post( 26 | `/api/frp/reload` 27 | ) 28 | }, 29 | getUsePort: () => { 30 | return request.post( 31 | `/api/use-port-check` 32 | ) 33 | }, 34 | 35 | } 36 | -------------------------------------------------------------------------------- /frp-web-h5/src/assets/base.css: -------------------------------------------------------------------------------- 1 | /* color palette from */ 2 | :root { 3 | --vt-c-white: #ffffff; 4 | --vt-c-white-soft: #f8f8f8; 5 | --vt-c-white-mute: #f2f2f2; 6 | 7 | --vt-c-black: #181818; 8 | --vt-c-black-soft: #222222; 9 | --vt-c-black-mute: #282828; 10 | 11 | --vt-c-indigo: #2c3e50; 12 | 13 | --vt-c-divider-light-1: rgba(60, 60, 60, 0.29); 14 | --vt-c-divider-light-2: rgba(60, 60, 60, 0.12); 15 | --vt-c-divider-dark-1: rgba(84, 84, 84, 0.65); 16 | --vt-c-divider-dark-2: rgba(84, 84, 84, 0.48); 17 | 18 | --vt-c-text-light-1: var(--vt-c-indigo); 19 | --vt-c-text-light-2: rgba(60, 60, 60, 0.66); 20 | --vt-c-text-dark-1: var(--vt-c-white); 21 | --vt-c-text-dark-2: rgba(235, 235, 235, 0.64); 22 | } 23 | 24 | /* semantic color variables for this project */ 25 | :root { 26 | --color-background: var(--vt-c-white); 27 | --color-background-soft: var(--vt-c-white-soft); 28 | --color-background-mute: var(--vt-c-white-mute); 29 | 30 | --color-border: var(--vt-c-divider-light-2); 31 | --color-border-hover: var(--vt-c-divider-light-1); 32 | 33 | --color-heading: var(--vt-c-text-light-1); 34 | --color-text: var(--vt-c-text-light-1); 35 | 36 | --section-gap: 160px; 37 | } 38 | 39 | @media (prefers-color-scheme: dark) { 40 | :root { 41 | --color-background: var(--vt-c-black); 42 | --color-background-soft: var(--vt-c-black-soft); 43 | --color-background-mute: var(--vt-c-black-mute); 44 | 45 | --color-border: var(--vt-c-divider-dark-2); 46 | --color-border-hover: var(--vt-c-divider-dark-1); 47 | 48 | --color-heading: var(--vt-c-text-dark-1); 49 | --color-text: var(--vt-c-text-dark-2); 50 | } 51 | } 52 | 53 | *, 54 | *::before, 55 | *::after { 56 | box-sizing: border-box; 57 | margin: 0; 58 | font-weight: normal; 59 | } 60 | 61 | body { 62 | min-height: 100vh; 63 | color: var(--color-text); 64 | background: var(--color-background); 65 | transition: 66 | color 0.5s, 67 | background-color 0.5s; 68 | line-height: 1.6; 69 | font-family: 70 | Inter, 71 | -apple-system, 72 | BlinkMacSystemFont, 73 | 'Segoe UI', 74 | Roboto, 75 | Oxygen, 76 | Ubuntu, 77 | Cantarell, 78 | 'Fira Sans', 79 | 'Droid Sans', 80 | 'Helvetica Neue', 81 | sans-serif; 82 | font-size: 15px; 83 | text-rendering: optimizeLegibility; 84 | -webkit-font-smoothing: antialiased; 85 | -moz-osx-font-smoothing: grayscale; 86 | } 87 | -------------------------------------------------------------------------------- /frp-web-h5/src/assets/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /frp-web-h5/src/assets/main.css: -------------------------------------------------------------------------------- 1 | @import './base.css'; 2 | 3 | #app { 4 | max-width: 1280px; 5 | margin: 0 auto; 6 | padding: 2rem; 7 | font-weight: normal; 8 | } 9 | 10 | a, 11 | .green { 12 | text-decoration: none; 13 | color: hsla(160, 100%, 37%, 1); 14 | transition: 0.4s; 15 | padding: 3px; 16 | } 17 | 18 | @media (hover: hover) { 19 | a:hover { 20 | background-color: hsla(160, 100%, 37%, 0.2); 21 | } 22 | } 23 | 24 | @media (min-width: 1024px) { 25 | body { 26 | display: flex; 27 | place-items: center; 28 | } 29 | 30 | #app { 31 | display: grid; 32 | grid-template-columns: 1fr 1fr; 33 | padding: 0 2rem; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /frp-web-h5/src/components/ModalTipsComponent.vue: -------------------------------------------------------------------------------- 1 | 34 | 35 | 146 | 147 | -------------------------------------------------------------------------------- /frp-web-h5/src/components/ModalWaitingComponent.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 37 | 38 | -------------------------------------------------------------------------------- /frp-web-h5/src/main.js: -------------------------------------------------------------------------------- 1 | import { createApp } from 'vue' 2 | import App from './App.vue' 3 | import router from './router' 4 | import naive from 'naive-ui' 5 | 6 | const app = createApp(App) 7 | 8 | app.use(router) 9 | app.use(naive) 10 | 11 | app.mount('#app') 12 | -------------------------------------------------------------------------------- /frp-web-h5/src/router/index.js: -------------------------------------------------------------------------------- 1 | import { createRouter, createWebHistory } from 'vue-router' 2 | import HomeView from '../views/HomeView.vue' 3 | 4 | const router = createRouter({ 5 | history: createWebHistory(import.meta.env.BASE_URL), 6 | routes: [ 7 | { 8 | path: '/', 9 | name: 'home', 10 | component: HomeView 11 | }, 12 | { 13 | path: '/doc', 14 | name: 'doc', 15 | // route level code-splitting 16 | // this generates a separate chunk (About.[hash].js) for this route 17 | // which is lazy-loaded when the route is visited. 18 | component: () => import('../views/Document.vue') 19 | } 20 | ] 21 | }) 22 | 23 | export default router 24 | -------------------------------------------------------------------------------- /frp-web-h5/src/utils/request.js: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | 3 | const request = axios.create({ 4 | timeout: 50000, 5 | }) 6 | 7 | 8 | request.interceptors.request.use(value => { 9 | if (!value.headers['token']) { 10 | value.headers['token'] = 'frp-token' 11 | } 12 | 13 | // console.log('[request.data]', value) 14 | return value 15 | }, error => { 16 | // console.log('[request.error]', error) 17 | return Promise.reject(error) 18 | }) 19 | 20 | 21 | request.interceptors.response.use(resp => { 22 | // console.log('[response.data]', resp) 23 | if (resp.data.code === 200) { 24 | return resp 25 | } 26 | return Promise.reject(resp.data) 27 | }, error => { 28 | // console.log('[response.error]', error) 29 | return Promise.reject(error) 30 | }) 31 | 32 | 33 | export default request 34 | -------------------------------------------------------------------------------- /frp-web-h5/src/utils/strings.js: -------------------------------------------------------------------------------- 1 | const randomString = (e) => { 2 | e = e || 32; 3 | let t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678", 4 | a = t.length, 5 | n = ""; 6 | for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a)); 7 | return n.toLowerCase() 8 | } 9 | 10 | export default { 11 | randomString, 12 | } 13 | -------------------------------------------------------------------------------- /frp-web-h5/src/views/Document.vue: -------------------------------------------------------------------------------- 1 | 15 | 16 | 19 | 20 | -------------------------------------------------------------------------------- /frp-web-h5/src/views/HomeView.vue: -------------------------------------------------------------------------------- 1 | 177 | 178 | 684 | 685 | -------------------------------------------------------------------------------- /frp-web-h5/vite.config.js: -------------------------------------------------------------------------------- 1 | import { fileURLToPath, URL } from 'node:url' 2 | 3 | import { defineConfig } from 'vite' 4 | import vue from '@vitejs/plugin-vue' 5 | 6 | // https://vitejs.dev/config/ 7 | export default defineConfig({ 8 | plugins: [ 9 | vue(), 10 | ], 11 | resolve: { 12 | alias: { 13 | '@': fileURLToPath(new URL('./src', import.meta.url)) 14 | } 15 | }, 16 | base:'/frp-web', 17 | }) 18 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/lixiang4u/frp-web 2 | 3 | go 1.22.0 4 | 5 | require ( 6 | github.com/denisbrodbeck/machineid v1.0.1 7 | github.com/fatedier/frp v0.54.0 8 | github.com/gin-contrib/cors v1.5.0 9 | github.com/gin-gonic/gin v1.9.1 10 | github.com/rodaine/table v1.1.0 11 | github.com/spf13/viper v1.18.2 12 | ) 13 | 14 | require ( 15 | github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c // indirect 16 | github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 // indirect 17 | github.com/bytedance/sonic v1.10.1 // indirect 18 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect 19 | github.com/chenzhuoyu/iasm v0.9.0 // indirect 20 | github.com/coreos/go-oidc/v3 v3.6.0 // indirect 21 | github.com/fatedier/beego v0.0.0-20171024143340-6c6a4f5bd5eb // indirect 22 | github.com/fatedier/golib v0.1.1-0.20230725122706-dcbaee8eef40 // indirect 23 | github.com/fatedier/kcp-go v2.0.4-0.20190803094908-fe8645b0a904+incompatible // indirect 24 | github.com/fsnotify/fsnotify v1.7.0 // indirect 25 | github.com/gabriel-vasile/mimetype v1.4.2 // indirect 26 | github.com/gin-contrib/sse v0.1.0 // indirect 27 | github.com/go-jose/go-jose/v3 v3.0.3 // indirect 28 | github.com/go-playground/locales v0.14.1 // indirect 29 | github.com/go-playground/universal-translator v0.18.1 // indirect 30 | github.com/go-playground/validator/v10 v10.15.5 // indirect 31 | github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect 32 | github.com/goccy/go-json v0.10.2 // indirect 33 | github.com/golang/mock v1.6.0 // indirect 34 | github.com/golang/protobuf v1.5.3 // indirect 35 | github.com/golang/snappy v0.0.4 // indirect 36 | github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect 37 | github.com/gorilla/mux v1.8.0 // indirect 38 | github.com/hashicorp/hcl v1.0.0 // indirect 39 | github.com/hashicorp/yamux v0.1.1 // indirect 40 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 41 | github.com/json-iterator/go v1.1.12 // indirect 42 | github.com/klauspost/cpuid/v2 v2.2.5 // indirect 43 | github.com/klauspost/reedsolomon v1.9.15 // indirect 44 | github.com/leodido/go-urn v1.2.4 // indirect 45 | github.com/magiconair/properties v1.8.7 // indirect 46 | github.com/mattn/go-isatty v0.0.19 // indirect 47 | github.com/mitchellh/mapstructure v1.5.0 // indirect 48 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 49 | github.com/modern-go/reflect2 v1.0.2 // indirect 50 | github.com/onsi/ginkgo/v2 v2.11.0 // indirect 51 | github.com/pelletier/go-toml/v2 v2.1.0 // indirect 52 | github.com/pion/dtls/v2 v2.2.7 // indirect 53 | github.com/pion/logging v0.2.2 // indirect 54 | github.com/pion/stun v0.6.1 // indirect 55 | github.com/pion/transport/v2 v2.2.1 // indirect 56 | github.com/pires/go-proxyproto v0.7.0 // indirect 57 | github.com/pkg/errors v0.9.1 // indirect 58 | github.com/quic-go/qtls-go1-20 v0.3.1 // indirect 59 | github.com/quic-go/quic-go v0.44.0 // indirect 60 | github.com/sagikazarmark/locafero v0.4.0 // indirect 61 | github.com/sagikazarmark/slog-shim v0.1.0 // indirect 62 | github.com/samber/lo v1.38.1 // indirect 63 | github.com/sourcegraph/conc v0.3.0 // indirect 64 | github.com/spf13/afero v1.11.0 // indirect 65 | github.com/spf13/cast v1.6.0 // indirect 66 | github.com/spf13/cobra v1.8.0 // indirect 67 | github.com/spf13/pflag v1.0.5 // indirect 68 | github.com/subosito/gotenv v1.6.0 // indirect 69 | github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 // indirect 70 | github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b // indirect 71 | github.com/tjfoc/gmsm v1.4.1 // indirect 72 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect 73 | github.com/ugorji/go/codec v1.2.11 // indirect 74 | go.uber.org/atomic v1.9.0 // indirect 75 | go.uber.org/mock v0.4.0 // indirect 76 | go.uber.org/multierr v1.9.0 // indirect 77 | golang.org/x/arch v0.5.0 // indirect 78 | golang.org/x/crypto v0.23.0 // indirect 79 | golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect 80 | golang.org/x/mod v0.17.0 // indirect 81 | golang.org/x/net v0.25.0 // indirect 82 | golang.org/x/oauth2 v0.15.0 // indirect 83 | golang.org/x/sync v0.7.0 // indirect 84 | golang.org/x/sys v0.20.0 // indirect 85 | golang.org/x/text v0.15.0 // indirect 86 | golang.org/x/time v0.5.0 // indirect 87 | golang.org/x/tools v0.21.0 // indirect 88 | google.golang.org/appengine v1.6.7 // indirect 89 | google.golang.org/protobuf v1.34.1 // indirect 90 | gopkg.in/ini.v1 v1.67.0 // indirect 91 | gopkg.in/yaml.v2 v2.4.0 // indirect 92 | gopkg.in/yaml.v3 v3.0.1 // indirect 93 | k8s.io/apimachinery v0.27.4 // indirect 94 | sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect 95 | sigs.k8s.io/yaml v1.3.0 // indirect 96 | ) 97 | -------------------------------------------------------------------------------- /handler/api.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "github.com/fatedier/frp/client" 8 | v1 "github.com/fatedier/frp/pkg/config/v1" 9 | "github.com/gin-gonic/gin" 10 | "github.com/go-jose/go-jose/v3/json" 11 | "github.com/lixiang4u/frp-web/model" 12 | "github.com/lixiang4u/frp-web/utils" 13 | "io/fs" 14 | "log" 15 | "net" 16 | "net/http" 17 | "net/url" 18 | "os" 19 | "path/filepath" 20 | "strings" 21 | ) 22 | 23 | func ApiRecover(h gin.HandlerFunc) gin.HandlerFunc { 24 | defer func() { 25 | if err := recover(); err != nil { 26 | log.Println("[recover]", err) 27 | } 28 | }() 29 | 30 | return func(ctx *gin.Context) { 31 | h(ctx) 32 | } 33 | } 34 | 35 | func ApiAuth(h gin.HandlerFunc) gin.HandlerFunc { 36 | return func(ctx *gin.Context) { 37 | ok, err := utils.IsIntranet(ctx.Request.Host) 38 | if err != nil { 39 | ctx.JSON(http.StatusOK, gin.H{ 40 | "code": http.StatusInternalServerError, 41 | "msg": "请求来源异常", 42 | "debug": err.Error(), 43 | }) 44 | return 45 | } 46 | if !ok { 47 | ctx.JSON(http.StatusOK, gin.H{ 48 | "code": http.StatusInternalServerError, 49 | "msg": "请求来源异常,该请求只能内网访问", 50 | "debug": ctx.Request.Host, 51 | }) 52 | return 53 | } 54 | h(ctx) 55 | } 56 | } 57 | 58 | func ApiServerConfig(ctx *gin.Context) { 59 | code, buf, _ := utils.HttpGet(fmt.Sprintf("%s/api/config", model.ApiServerHost)) 60 | 61 | var resp gin.H 62 | _ = json.Unmarshal(buf, &resp) 63 | 64 | resp["machine_id"] = model.AppMachineId 65 | 66 | ctx.JSON(code, resp) 67 | } 68 | 69 | func ApiServerVhostList(ctx *gin.Context) { 70 | var params = url.Values{} 71 | params.Add("machine_id", model.AppMachineId) 72 | code, buf, _ := utils.HttpGet(fmt.Sprintf("%s/api/vhosts", model.ApiServerHost), params) 73 | 74 | var resp gin.H 75 | _ = json.Unmarshal(buf, &resp) 76 | 77 | ctx.JSON(code, resp) 78 | } 79 | 80 | func ApiServerCreateVhost(ctx *gin.Context) { 81 | type Req struct { 82 | Id string `json:"id" form:"id"` 83 | Type string `json:"type" form:"type"` 84 | LocalAddr string `json:"local_addr" form:"local_addr"` 85 | RemotePort int `json:"remote_port" form:"remote_port"` 86 | Name string `json:"name" form:"name"` // 代码名称 87 | Status bool `json:"status" form:"status"` //true.运行,false.未运行 88 | } 89 | var req Req 90 | _ = ctx.ShouldBind(&req) 91 | 92 | var body = utils.ToJsonString(gin.H{ 93 | "id": req.Id, 94 | "type": req.Type, 95 | "machine_id": model.AppMachineId, 96 | "local_addr": req.LocalAddr, 97 | "remote_port": req.RemotePort, 98 | "name": req.Name, 99 | "status": req.Status, 100 | }) 101 | code, buf, _ := utils.HttpPost(fmt.Sprintf("%s/api/vhost", model.ApiServerHost), []byte(body)) 102 | 103 | type Resp struct { 104 | Code int `json:"code"` 105 | Msg string `json:"msg"` 106 | Vhost model.Vhost `json:"vhost"` 107 | } 108 | var resp Resp 109 | _ = json.Unmarshal(buf, &resp) 110 | if resp.Code != http.StatusOK { 111 | ctx.JSON(http.StatusOK, gin.H{ 112 | "code": resp.Code, 113 | "msg": resp.Msg, 114 | }) 115 | return 116 | } 117 | 118 | if resp.Vhost.Type == string(v1.ProxyTypeHTTPS) { 119 | if !strings.Contains(resp.Vhost.CrtPath, "CERTIFICATE") { 120 | _, _, _ = utils.HttpDelete(fmt.Sprintf("%s/api/vhost/%s/%s", model.ApiServerHost, model.AppMachineId, resp.Vhost.Id), nil) 121 | ctx.JSON(http.StatusOK, gin.H{ 122 | "code": 500, 123 | "msg": "证书文件错误(cert)", 124 | }) 125 | return 126 | } 127 | if !strings.Contains(resp.Vhost.KeyPath, "PRIVATE KEY") { 128 | _, _, _ = utils.HttpDelete(fmt.Sprintf("%s/api/vhost/%s/%s", model.ApiServerHost, model.AppMachineId, resp.Vhost.Id), nil) 129 | ctx.JSON(http.StatusOK, gin.H{ 130 | "code": 500, 131 | "msg": "证书文件错误(key)", 132 | }) 133 | return 134 | } 135 | removeCertFile(resp.Vhost.Id) 136 | _, _, err := parseCertToFile(resp.Vhost.Id, []byte(resp.Vhost.CrtPath), []byte(resp.Vhost.KeyPath)) 137 | if err != nil { 138 | _, _, _ = utils.HttpDelete(fmt.Sprintf("%s/api/vhost/%s/%s", model.ApiServerHost, model.AppMachineId, resp.Vhost.Id), nil) 139 | ctx.JSON(http.StatusOK, gin.H{ 140 | "code": 500, 141 | "msg": fmt.Sprintf("证书保存失败:%s", err.Error()), 142 | }) 143 | return 144 | } 145 | } 146 | 147 | ctx.JSON(code, resp) 148 | } 149 | 150 | func ApiServerRemoveVhost(ctx *gin.Context) { 151 | var vhostId = ctx.Param("vhost_id") 152 | 153 | code, buf, _ := utils.HttpDelete(fmt.Sprintf("%s/api/vhost/%s/%s", model.ApiServerHost, model.AppMachineId, vhostId), nil) 154 | 155 | var resp gin.H 156 | _ = json.Unmarshal(buf, &resp) 157 | 158 | ctx.JSON(code, resp) 159 | } 160 | 161 | func ApiUsePortCheck(ctx *gin.Context) { 162 | code, buf, _ := utils.HttpPost(fmt.Sprintf("%s/api/use-port-check", model.ApiServerHost), nil) 163 | 164 | var resp gin.H 165 | _ = json.Unmarshal(buf, &resp) 166 | 167 | ctx.JSON(code, resp) 168 | } 169 | 170 | func ApiFrpReload(ctx *gin.Context) { 171 | _, buf, _ := utils.HttpGet(fmt.Sprintf("%s/api/config", model.ApiServerHost)) 172 | 173 | type Resp struct { 174 | Code int `json:"code"` 175 | Config struct { 176 | BindPort int `json:"bind_port"` 177 | VhostHttpPort int `json:"vhost_http_port"` 178 | VhostHttpsPort int `json:"vhost_https_port"` 179 | Host string `json:"host"` 180 | } `json:"config"` 181 | } 182 | var resp Resp 183 | _ = json.Unmarshal(buf, &resp) 184 | if resp.Code != http.StatusOK { 185 | ctx.JSON(http.StatusOK, gin.H{ 186 | "code": http.StatusInternalServerError, 187 | "msg": "frp服务器信息获取失败", 188 | }) 189 | return 190 | } 191 | 192 | vhosts, err := apiGetVhosts() 193 | if err != nil { 194 | ctx.JSON(http.StatusOK, gin.H{ 195 | "code": http.StatusInternalServerError, 196 | "msg": err.Error(), 197 | }) 198 | return 199 | } 200 | 201 | go func() { 202 | log.Println(fmt.Sprintf("[frpServer] %s:%d", resp.Config.Host, resp.Config.BindPort)) 203 | 204 | if err := runFrpClient(resp.Config.Host, resp.Config.BindPort, vhosts); err != nil { 205 | log.Println("[frpClientError]", err.Error()) 206 | } 207 | }() 208 | 209 | ctx.JSON(http.StatusOK, resp) 210 | } 211 | 212 | func ApiNotRoute(ctx *gin.Context) { 213 | tmpUrl, _ := url.PathUnescape(ctx.Request.RequestURI) 214 | 215 | root, _ := filepath.Abs(filepath.Join(".")) 216 | tmpFile, _ := filepath.Abs(filepath.Join(".", tmpUrl)) 217 | _, err := os.Stat(tmpFile) 218 | if err == nil && strings.HasPrefix(tmpFile, root) { 219 | ctx.Status(http.StatusOK) 220 | ctx.File(tmpFile) 221 | return 222 | } 223 | 224 | ctx.JSON(http.StatusNotFound, gin.H{ 225 | "code": 404, 226 | "msg": "请求地址错误", 227 | "path": tmpUrl, 228 | }) 229 | } 230 | 231 | func handlerVhostConfig(vhosts []model.Vhost) []v1.ProxyConfigurer { 232 | var proxyCfgs = make([]v1.ProxyConfigurer, 0) 233 | for _, vhost := range vhosts { 234 | if !vhost.Status { 235 | continue 236 | } 237 | pc := v1.NewProxyConfigurerByType(v1.ProxyType(vhost.Type)) 238 | tmpTypedConfig := handlerVhostConfigTyped(pc, vhost) 239 | if tmpTypedConfig != nil { 240 | proxyCfgs = append(proxyCfgs, tmpTypedConfig) 241 | } 242 | } 243 | return proxyCfgs 244 | } 245 | 246 | func handlerVhostConfigTyped(pc v1.ProxyConfigurer, vhost model.Vhost) (proxyCfg v1.ProxyConfigurer) { 247 | host, port, _ := net.SplitHostPort(vhost.LocalAddr) 248 | tmpVhostName := fmt.Sprintf("%s-%s-%s(%s)", vhost.Type, port, vhost.Id, vhost.Name) 249 | switch tmpC := pc.(type) { 250 | case *v1.HTTPProxyConfig: 251 | tmpC.Name = tmpVhostName 252 | tmpC.Transport.BandwidthLimitMode = "client" 253 | 254 | tmpC.LocalIP = host 255 | tmpC.LocalPort = utils.StringToInt(port) 256 | 257 | tmpC.CustomDomains = make([]string, 0) 258 | tmpC.CustomDomains = append(tmpC.CustomDomains, vhost.CustomDomain) 259 | if strings.Contains(vhost.CnameDomain, ".") { 260 | tmpC.CustomDomains = append(tmpC.CustomDomains, vhost.CnameDomain) 261 | } 262 | 263 | proxyCfg = tmpC 264 | case *v1.HTTPSProxyConfig: 265 | certFile, keyFile, _ := parseCertToFile(vhost.Id, []byte(vhost.CrtPath), []byte(vhost.KeyPath)) 266 | 267 | // 参考frp实际运行的配置数据结构填充 268 | tmpC.Name = tmpVhostName 269 | tmpC.Transport.BandwidthLimitMode = "client" 270 | 271 | tmpC.LocalIP = host 272 | tmpC.LocalPort = utils.StringToInt(port) 273 | 274 | tmpC.CustomDomains = make([]string, 0) 275 | tmpC.CustomDomains = append(tmpC.CustomDomains, vhost.CustomDomain) 276 | 277 | tmpC.Plugin.Type = "https2http" 278 | tmpC.Plugin.ClientPluginOptions = &v1.HTTPS2HTTPPluginOptions{ 279 | Type: "https2http", 280 | LocalAddr: vhost.LocalAddr, 281 | HostHeaderRewrite: tmpC.LocalIP, 282 | RequestHeaders: v1.HeaderOperations{ 283 | Set: map[string]string{ 284 | "x-from-where": "frp", 285 | }, 286 | }, 287 | CrtPath: certFile, 288 | KeyPath: keyFile, 289 | } 290 | 291 | proxyCfg = tmpC 292 | case *v1.TCPProxyConfig: 293 | tmpC.Name = tmpVhostName 294 | tmpC.Transport.BandwidthLimitMode = "client" 295 | 296 | tmpC.LocalIP = host 297 | tmpC.LocalPort = utils.StringToInt(port) 298 | 299 | tmpC.RemotePort = vhost.RemotePort 300 | 301 | proxyCfg = tmpC 302 | case *v1.TCPMuxProxyConfig: 303 | tmpC.Name = tmpVhostName 304 | tmpC.Transport.BandwidthLimitMode = "client" 305 | 306 | tmpC.LocalIP = host 307 | tmpC.LocalPort = utils.StringToInt(port) 308 | 309 | tmpC.CustomDomains = make([]string, 0) 310 | tmpC.CustomDomains = append(tmpC.CustomDomains, vhost.CustomDomain) 311 | 312 | tmpC.Multiplexer = "httpconnect" 313 | 314 | proxyCfg = tmpC 315 | 316 | default: 317 | 318 | } 319 | return proxyCfg 320 | } 321 | 322 | func removeCertFile(vhostId string) { 323 | _ = os.Remove(utils.AppTempFile("certs", fmt.Sprintf("%s-cert.pem", vhostId))) 324 | _ = os.Remove(utils.AppTempFile("certs", fmt.Sprintf("%s-key.pem", vhostId))) 325 | } 326 | 327 | func parseCertToFile(vhostId string, certBuf, keyBuf []byte) (certFile, keyFile string, err error) { 328 | certFile = utils.AppTempFile("certs", fmt.Sprintf("%s-cert.pem", vhostId)) 329 | keyFile = utils.AppTempFile("certs", fmt.Sprintf("%s-key.pem", vhostId)) 330 | if !utils.FileExists(certFile) { 331 | if err = os.WriteFile(certFile, certBuf, fs.ModePerm); err != nil { 332 | log.Println("[CertFileSaveError] ", vhostId, certFile) 333 | return 334 | } 335 | } 336 | if !utils.FileExists(keyFile) { 337 | if err = os.WriteFile(keyFile, keyBuf, fs.ModePerm); err != nil { 338 | log.Println("[KeyFileSaveError] ", vhostId, certFile) 339 | return 340 | } 341 | } 342 | return 343 | } 344 | 345 | func apiGetVhosts() ([]model.Vhost, error) { 346 | var params = url.Values{} 347 | params.Add("machine_id", model.AppMachineId) 348 | 349 | code, buf, _ := utils.HttpGet(fmt.Sprintf("%s/api/vhosts", model.ApiServerHost), params) 350 | 351 | type Resp struct { 352 | Code int `json:"code"` 353 | Msg string `json:"msg"` 354 | Vhosts []model.Vhost `json:"vhosts"` 355 | } 356 | var resp Resp 357 | _ = json.Unmarshal(buf, &resp) 358 | if code != http.StatusOK { 359 | return nil, errors.New(fmt.Sprintf("请求失败:status_code=%d", code)) 360 | } 361 | if resp.Code != http.StatusOK { 362 | return nil, errors.New(resp.Msg) 363 | } 364 | return resp.Vhosts, nil 365 | } 366 | 367 | var svr *client.Service 368 | 369 | func runFrpClient(serverAddr string, serverPort int, vhosts []model.Vhost) (err error) { 370 | var cfg = &v1.ClientCommonConfig{} 371 | cfg.Complete() 372 | 373 | cfg.ServerAddr = serverAddr 374 | cfg.ServerPort = serverPort 375 | 376 | var proxyCfgs = handlerVhostConfig(vhosts) 377 | var visitorCfgs = make([]v1.VisitorConfigurer, 0) 378 | 379 | utils.FrpCloseRecover(svr) 380 | 381 | if len(proxyCfgs) == 0 { 382 | return errors.New("没有vhost可用") 383 | } 384 | 385 | svr, err = client.NewService(client.ServiceOptions{ 386 | Common: cfg, 387 | ProxyCfgs: proxyCfgs, 388 | VisitorCfgs: visitorCfgs, 389 | ConfigFilePath: "", 390 | }) 391 | if err != nil { 392 | return err 393 | } 394 | 395 | shouldGracefulClose := cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic" 396 | // Capture the exit signal if we use kcp or quic. 397 | if shouldGracefulClose { 398 | go utils.FrpTermSignal(svr) 399 | } 400 | err = svr.Run(context.Background()) 401 | if err != nil { 402 | log.Println("[frpRunError]", err.Error()) 403 | } 404 | 405 | return err 406 | } 407 | 408 | func NewClientVhost(localPort int) error { 409 | var body = utils.ToJsonString(gin.H{ 410 | "type": string(v1.ProxyTypeHTTP), 411 | "machine_id": model.AppMachineId, 412 | "local_addr": fmt.Sprintf("127.0.0.1:%d", localPort), 413 | "name": fmt.Sprintf("http-%d(default)", localPort), 414 | "status": true, 415 | }) 416 | code, buf, err := utils.HttpPost(fmt.Sprintf("%s/api/vhost", model.ApiServerHost), []byte(body)) 417 | if err != nil { 418 | return err 419 | } 420 | if code != http.StatusOK { 421 | return errors.New(fmt.Sprintf("statusCode: %d", code)) 422 | } 423 | 424 | var resp gin.H 425 | err = json.Unmarshal(buf, &resp) 426 | if err != nil { 427 | return err 428 | } 429 | if v, ok := resp["code"]; !ok || int(v.(float64)) != http.StatusOK { 430 | msg, _ := resp["msg"] 431 | return errors.New(msg.(string)) 432 | } 433 | 434 | return nil 435 | } 436 | 437 | func ClientVhostList() error { 438 | var params = url.Values{} 439 | params.Add("machine_id", model.AppMachineId) 440 | 441 | code, buf, err := utils.HttpGet(fmt.Sprintf("%s/api/vhosts", model.ApiServerHost), params) 442 | if err != nil { 443 | return err 444 | } 445 | if code != http.StatusOK { 446 | return errors.New(fmt.Sprintf("statusCode: %d", code)) 447 | } 448 | 449 | var resp gin.H 450 | err = json.Unmarshal(buf, &resp) 451 | if err != nil { 452 | return err 453 | } 454 | if v, ok := resp["code"]; !ok || int(v.(float64)) != http.StatusOK { 455 | msg, _ := resp["msg"] 456 | return errors.New(msg.(string)) 457 | } 458 | 459 | return nil 460 | 461 | } 462 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "embed" 5 | "encoding/json" 6 | "fmt" 7 | "github.com/gin-contrib/cors" 8 | "github.com/gin-gonic/gin" 9 | "github.com/lixiang4u/frp-web/handler" 10 | "github.com/lixiang4u/frp-web/model" 11 | "github.com/lixiang4u/frp-web/utils" 12 | "io/fs" 13 | "log" 14 | "mime" 15 | "net" 16 | "net/http" 17 | "os" 18 | "os/exec" 19 | "os/signal" 20 | "path/filepath" 21 | "runtime" 22 | "strings" 23 | "syscall" 24 | "time" 25 | ) 26 | 27 | //go:embed frp-web-h5/dist/* 28 | var frpWebContent embed.FS 29 | 30 | var ( 31 | frpWebRoot = "frp-web" // 同 frp-web-h5/vite.config.js 中 base 值 32 | port = utils.IWantUseHttpPort() 33 | localServerFile = utils.AppTempFile("local-web-server.json") 34 | ) 35 | 36 | func main() { 37 | sig := make(chan os.Signal, 1) 38 | signal.Notify(sig, syscall.SIGINT, syscall.SIGKILL) 39 | 40 | appOneInstanceCheck(port) 41 | go getVhostListOrCreate(port) 42 | go httpServer(port) 43 | 44 | select { 45 | case _sig := <-sig: 46 | _ = os.Remove(localServerFile) 47 | log.Println(fmt.Sprintf("[stop] %v\n", _sig)) 48 | } 49 | 50 | } 51 | 52 | func httpServer(port int) { 53 | r := gin.Default() 54 | 55 | r.Use(cors.New(cors.Config{ 56 | AllowOrigins: []string{"*"}, 57 | AllowMethods: []string{"*"}, 58 | AllowHeaders: []string{"*"}, 59 | ExposeHeaders: []string{"Content-Length"}, 60 | AllowCredentials: true, 61 | AllowOriginFunc: func(origin string) bool { 62 | return true 63 | }, 64 | MaxAge: 12 * time.Hour, 65 | })) 66 | 67 | r.GET(fmt.Sprintf("/%s", frpWebRoot), frpWebFileServer) 68 | r.GET(fmt.Sprintf("/%s/*filepath", frpWebRoot), frpWebFileServer) 69 | 70 | r.GET("/api/config", handler.ApiRecover(handler.ApiAuth(handler.ApiServerConfig))) 71 | r.POST("/api/vhost", handler.ApiRecover(handler.ApiAuth(handler.ApiServerCreateVhost))) 72 | r.GET("/api/vhosts", handler.ApiRecover(handler.ApiAuth(handler.ApiServerVhostList))) 73 | r.DELETE("/api/vhost/:vhost_id", handler.ApiRecover(handler.ApiAuth(handler.ApiServerRemoveVhost))) 74 | r.POST("/api/frp/reload", handler.ApiRecover(handler.ApiAuth(handler.ApiFrpReload))) 75 | r.POST("/api/use-port-check", handler.ApiRecover(handler.ApiAuth(handler.ApiUsePortCheck))) 76 | 77 | r.NoRoute(handler.ApiRecover(handler.ApiNotRoute)) 78 | 79 | go func() { _ = r.Run(fmt.Sprintf(":%d", port)) }() 80 | go openBrowser(port) 81 | } 82 | 83 | func openBrowser(port int) { 84 | var osName = strings.ToLower(runtime.GOOS) 85 | switch osName { 86 | case "windows": 87 | cmd := exec.Command("cmd", "/c", "start", fmt.Sprintf("http://127.0.0.1:%d/%s", port, frpWebRoot)) 88 | _ = cmd.Run() 89 | case "darwin": 90 | cmd := exec.Command("open", fmt.Sprintf("http://127.0.0.1:%d/%s", port, frpWebRoot)) 91 | _ = cmd.Run() 92 | } 93 | } 94 | 95 | func getVhostListOrCreate(localPort int) { 96 | if err := handler.NewClientVhost(localPort); err != nil { 97 | log.Println("[NewClientVhostError]", err.Error()) 98 | utils.WaitInputExit() 99 | } 100 | if err := handler.ClientVhostList(); err != nil { 101 | log.Println("[ClientVhostListError]", err.Error()) 102 | utils.WaitInputExit() 103 | } 104 | } 105 | 106 | func appOneInstanceCheck(port int) { 107 | var isRun = make(chan bool, 1) 108 | 109 | go func() { 110 | if len(model.AppInstance1) == 0 { 111 | return 112 | } 113 | l, err := net.Listen("tcp", model.AppInstance1) 114 | if err != nil { 115 | log.Println("[程序使用(tcp://127.0.0.1:61234)检测多开问题]", err.Error()) 116 | 117 | // 如果启动了则打开网页 118 | var ls = model.LocalServer{} 119 | buf, _ := os.ReadFile(localServerFile) 120 | if err = json.Unmarshal(buf, &ls); err == nil && ls.Port > 0 { 121 | openBrowser(ls.Port) 122 | } 123 | 124 | isRun <- false 125 | } else { 126 | go func() { _, _ = l.Accept() }() 127 | 128 | // 如果没启动,则写入启动文件 129 | var ls = model.LocalServer{ 130 | Url: fmt.Sprintf("http://127.0.0.1:%d/%s", port, frpWebRoot), 131 | Port: port, 132 | } 133 | _ = os.WriteFile(localServerFile, []byte(utils.ToJsonString(ls)), fs.ModePerm) 134 | 135 | isRun <- true 136 | } 137 | }() 138 | if !<-isRun { 139 | utils.WaitInputExit() 140 | os.Exit(1) 141 | } 142 | 143 | } 144 | 145 | func frpWebFileServer(ctx *gin.Context) { 146 | var fp = ctx.Param("filepath") 147 | if len(fp) == 0 || fp == "/" { 148 | fp = "index.html" 149 | } 150 | var cf = strings.ReplaceAll(filepath.Join("frp-web-h5", "dist", fp), "\\", "/") 151 | buf, err := fs.ReadFile(frpWebContent, cf) 152 | if err != nil { 153 | ctx.JSON(http.StatusNotFound, gin.H{ 154 | "code": 404, 155 | "msg": "请求地址错误(embed.FS)", 156 | "path": ctx.Param("filepath"), 157 | }) 158 | return 159 | } 160 | ctx.Data(http.StatusOK, mime.TypeByExtension(filepath.Ext(cf)), buf) 161 | } 162 | -------------------------------------------------------------------------------- /model/config.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "github.com/denisbrodbeck/machineid" 5 | "github.com/fatedier/frp/pkg/util/util" 6 | "github.com/lixiang4u/frp-web/utils" 7 | "github.com/spf13/viper" 8 | "log" 9 | "strings" 10 | ) 11 | 12 | var ( 13 | ApiServerHost string 14 | AppMachineId string 15 | AppInstance1 string 16 | ) 17 | 18 | func init() { 19 | machineId, err := machineid.ID() 20 | if err != nil { 21 | log.Println("[MachineIdError]", err.Error()) 22 | utils.WaitInputExit() 23 | } 24 | log.Println("[MachineId]", machineId) 25 | AppMachineId = machineId 26 | 27 | viper.SetConfigFile("config.toml") 28 | _ = viper.ReadInConfig() 29 | 30 | ApiServerHost = util.EmptyOr(strings.TrimRight(viper.GetString("app.server"), "/"), "http://api-frp.lixiang4u.xyz:7200") 31 | AppInstance1 = util.EmptyOr(strings.TrimSpace(viper.GetString("app.instance1")), "127.0.0.1:61234") 32 | 33 | if len(ApiServerHost) == 0 { 34 | log.Println("[configError] app.server 配置不能为空") 35 | utils.WaitInputExit() 36 | } 37 | if len(AppInstance1) == 0 { 38 | log.Println("[configError] app.instance1 配置不能为空") 39 | utils.WaitInputExit() 40 | } 41 | 42 | // 重新设置并写入配置 43 | viper.Set("app.server", ApiServerHost) 44 | viper.Set("app.instance1", AppInstance1) 45 | _ = viper.WriteConfig() 46 | } 47 | -------------------------------------------------------------------------------- /model/local-server.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | type LocalServer struct { 4 | Url string `json:"url"` 5 | Port int `json:"port"` 6 | } 7 | -------------------------------------------------------------------------------- /model/vhost.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | type Vhost struct { 4 | Id string `json:"id"` 5 | Type string `json:"type"` 6 | Name string `json:"name"` 7 | CustomDomain string `json:"custom_domain"` // frp自动分配的域名 8 | CnameDomain string `json:"cname_domain"` // 自定义域名,通过cname指向custom_domain 9 | LocalAddr string `json:"local_addr"` 10 | RemotePort int `json:"remote_port"` 11 | CrtPath string `json:"crt_path"` 12 | KeyPath string `json:"key_path"` 13 | Status bool `json:"status"` //true.开启,false.关闭 14 | CreatedAt int64 `json:"created_at"` 15 | } 16 | -------------------------------------------------------------------------------- /screenshot/screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lixiang4u/frp-web/3376cbe5e50da7e17d141a9cb1573a870509a3a0/screenshot/screenshot1.png -------------------------------------------------------------------------------- /screenshot/screenshot2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lixiang4u/frp-web/3376cbe5e50da7e17d141a9cb1573a870509a3a0/screenshot/screenshot2.png -------------------------------------------------------------------------------- /utils/file.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "crypto/md5" 5 | "encoding/hex" 6 | "io" 7 | "io/fs" 8 | "os" 9 | ) 10 | 11 | func FileExists(files ...string) bool { 12 | if len(files) == 0 { 13 | return false 14 | } 15 | for _, file := range files { 16 | _, err := os.Stat(file) 17 | if err != nil { 18 | return false 19 | } 20 | } 21 | return true 22 | } 23 | 24 | func HashFile(filename string) (string, error) { 25 | file, err := os.Open(filename) 26 | if err != nil { 27 | return "", err 28 | } 29 | defer func() { _ = file.Close() }() 30 | 31 | hash := md5.New() 32 | if _, err := io.Copy(hash, file); err != nil { 33 | return "", err 34 | } 35 | 36 | sum := hash.Sum(nil) 37 | return hex.EncodeToString(sum), nil 38 | } 39 | 40 | func FileContents(filename string) []byte { 41 | file, err := os.Open(filename) 42 | if err != nil { 43 | return make([]byte, 0) 44 | } 45 | defer func() { _ = file.Close() }() 46 | 47 | buf, err := io.ReadAll(file) 48 | if err != nil { 49 | return make([]byte, 0) 50 | } 51 | return buf 52 | } 53 | 54 | func FileWriteContent(filename string, data []byte) error { 55 | return os.WriteFile(filename, data, fs.ModePerm) 56 | } 57 | -------------------------------------------------------------------------------- /utils/format.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "github.com/go-jose/go-jose/v3/json" 5 | "strconv" 6 | ) 7 | 8 | func ToJsonString(v any) string { 9 | buff, _ := json.MarshalIndent(v, "", "\t") 10 | return string(buff) 11 | } 12 | 13 | func StringToBytes(str string) []byte { 14 | return []byte(str) 15 | } 16 | 17 | func StringToInt(str string) int { 18 | i, _ := strconv.Atoi(str) 19 | return i 20 | } 21 | -------------------------------------------------------------------------------- /utils/http.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | "log" 8 | "net/http" 9 | "net/url" 10 | ) 11 | 12 | func HttpPost(requestUrl string, requestBody []byte) (int, []byte, error) { 13 | log.Println("[requestUrl]", requestUrl) 14 | resp, err := http.Post(requestUrl, "application/json", bytes.NewBuffer(requestBody)) 15 | if err != nil { 16 | log.Println("[postError]", err.Error()) 17 | return http.StatusInternalServerError, nil, err 18 | } 19 | defer func() { _ = resp.Body.Close() }() 20 | 21 | buf, err := io.ReadAll(resp.Body) 22 | if err != nil { 23 | log.Println("[responseReadError]", err.Error()) 24 | return resp.StatusCode, nil, err 25 | } 26 | 27 | return resp.StatusCode, buf, nil 28 | } 29 | 30 | func HttpGet(requestUrl string, params ...url.Values) (int, []byte, error) { 31 | if len(params) != 0 { 32 | requestUrl = fmt.Sprintf("%s?%s", requestUrl, params[0].Encode()) 33 | } 34 | log.Println("[requestUrl]", requestUrl) 35 | resp, err := http.Get(requestUrl) 36 | if err != nil { 37 | log.Println("[postError]", err.Error()) 38 | return http.StatusInternalServerError, nil, err 39 | } 40 | 41 | defer func() { _ = resp.Body.Close() }() 42 | 43 | buf, err := io.ReadAll(resp.Body) 44 | if err != nil { 45 | log.Println("[responseReadError]", err.Error()) 46 | return resp.StatusCode, nil, err 47 | } 48 | 49 | return resp.StatusCode, buf, nil 50 | } 51 | 52 | func HttpDelete(requestUrl string, requestBody []byte) (int, []byte, error) { 53 | log.Println("[requestUrl]", requestUrl) 54 | req, err := http.NewRequest("DELETE", requestUrl, bytes.NewBuffer(requestBody)) 55 | if err != nil { 56 | log.Println("[deleteError]", err.Error()) 57 | return http.StatusInternalServerError, nil, err 58 | } 59 | client := &http.Client{} 60 | resp, err := client.Do(req) 61 | if err != nil { 62 | log.Fatal(err) 63 | } 64 | defer func() { _ = resp.Body.Close() }() 65 | 66 | buf, err := io.ReadAll(resp.Body) 67 | if err != nil { 68 | log.Println("[responseReadError]", err.Error()) 69 | return resp.StatusCode, nil, err 70 | } 71 | 72 | return resp.StatusCode, buf, nil 73 | } 74 | -------------------------------------------------------------------------------- /utils/input.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bufio" 5 | "os" 6 | ) 7 | 8 | func WaitInput(tips ...string) string { 9 | if len(tips) == 0 { 10 | tips = append(tips, "按回车结束输入") 11 | } 12 | reader := bufio.NewReader(os.Stdin) 13 | str, _ := reader.ReadString('\n') 14 | return str 15 | } 16 | 17 | func WaitInputExit(tips ...string) { 18 | WaitInput(tips...) 19 | os.Exit(1) 20 | } 21 | -------------------------------------------------------------------------------- /utils/path.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "io/fs" 5 | "net" 6 | "os" 7 | "path/filepath" 8 | "strings" 9 | ) 10 | 11 | func AppPath() string { 12 | dir, err := filepath.Abs(filepath.Dir(os.Args[0])) 13 | if err != nil { 14 | return "" 15 | } 16 | return dir 17 | } 18 | 19 | func AppTempFile(elem ...string) string { 20 | elem = append([]string{os.TempDir(), "frp-web"}, elem...) 21 | var tmpFile = filepath.Join(elem...) 22 | _ = os.MkdirAll(filepath.Dir(tmpFile), fs.ModePerm) 23 | return tmpFile 24 | } 25 | 26 | func IsIntranet(address string) (bool, error) { 27 | host, _, err := net.SplitHostPort(address) 28 | if err != nil { 29 | host = address 30 | } 31 | ipAddr, err := net.ResolveIPAddr("ip", host) 32 | if err != nil { 33 | return true, err 34 | } 35 | ip := ipAddr.IP 36 | if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() { 37 | return true, nil 38 | } else if strings.HasSuffix(host, ".local") { 39 | return true, nil 40 | } 41 | return false, nil 42 | } 43 | -------------------------------------------------------------------------------- /utils/port.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | ) 7 | 8 | func IWantUseHttpPort(port ...int) int { 9 | if len(port) > 1 { 10 | panic("端口参数错误") 11 | } 12 | if len(port) == 0 { 13 | port = []int{8000} 14 | } 15 | if len(port) == 0 || port[0] <= 1024 || port[0] > 60000 { 16 | port = []int{8000} 17 | } 18 | listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port[0])) 19 | if err != nil { 20 | return IWantUseHttpPort(port[0] + 1) 21 | } 22 | defer func() { _ = listener.Close() }() 23 | return port[0] 24 | } 25 | -------------------------------------------------------------------------------- /utils/signal.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "github.com/fatedier/frp/client" 5 | "os" 6 | "os/signal" 7 | "syscall" 8 | "time" 9 | ) 10 | 11 | func FrpTermSignal(svr *client.Service) { 12 | ch := make(chan os.Signal, 1) 13 | signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) 14 | <-ch 15 | svr.GracefulClose(500 * time.Millisecond) 16 | } 17 | 18 | func FrpCloseRecover(svr *client.Service) { 19 | defer func() { 20 | recover() 21 | }() 22 | svr.GracefulClose(500 * time.Millisecond) 23 | } 24 | --------------------------------------------------------------------------------