29 Commits
Author SHA1 Message Date
luyoyu 67a8e7631a mod readme 2023-09-13 18:55:27 +08:00
luyoyu 69c962c57e mod readme 2023-09-13 18:40:52 +08:00
luyoyu c774fda80f Merge branch 'master' of https://gitee.com/chuangxxt/share-copilot # 2023-09-13 18:36:30 +08:00
luyoyu 848ca4da0e 删除无用项 2023-09-13 18:34:59 +08:00
luyoyu 20b104543e update README.md.
Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-13 10:18:35 +00:00
luyoyu 3fd12318a7 update README.md.
Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-13 09:50:48 +00:00
luyoyu 84ecafbf94 update README.md.
原理解释

Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-13 09:38:33 +00:00
luyoyu 4fd2515d43 update README.md.
原理解释

Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-13 09:38:06 +00:00
ben Gutier dbdd0adc73 mod readme 2023-09-13 17:17:06 +08:00
ben Gutier 27b23c0831 mod readme 2023-09-13 17:12:51 +08:00
ben Gutier f4cbf0364f mod readme 2023-09-13 17:12:31 +08:00
ben Gutier 89c05e98df mod readme 2023-09-13 17:03:59 +08:00
luyoyu 7f81713d48 update README.md.
mod readme

Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-13 08:49:39 +00:00
luyoyu 89e3e6a264 update README-EN.md.
mod readmeEN
2023-09-13 08:31:17 +00:00
ben Gutier 9290499ebb mod readme 2023-09-13 16:29:17 +08:00
ben Gutier 6f59bab64a mod readme 2023-09-13 16:25:36 +08:00
ben Gutier d7a5a02952 Merge branch 'master' of https://gitee.com/chuangxxt/share-copilot 2023-09-12 16:12:23 +08:00
ben Gutier dafdf2f72e 20239/12 16:11 2023-09-12 16:11:46 +08:00
ben Gutier 5ac6b5863a Squashed commit of the following:
commit 67f6bd3f2f
Author: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
Date:   Tue Sep 12 06:34:59 2023 +0000

    update README.md.

    Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>

commit 9cc98d6114
Author: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
Date:   Tue Sep 12 06:34:47 2023 +0000

    update README.md.

    Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>

commit 47655810a5
Author: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
Date:   Tue Sep 12 06:32:51 2023 +0000

    update README.md.

    Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>

commit dd6ea3c9dc
Author: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
Date:   Tue Sep 12 06:29:58 2023 +0000

    readme图片

    Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-12 16:09:49 +08:00
ben Gutier e1a95fbc62 修改文件夹名称 2023-09-12 16:07:49 +08:00
luyoyu 67f6bd3f2f update README.md.
Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-12 06:34:59 +00:00
luyoyu 9cc98d6114 update README.md.
Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-12 06:34:47 +00:00
luyoyu 47655810a5 update README.md.
Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-12 06:32:51 +00:00
luyoyu dd6ea3c9dc readme图片
Signed-off-by: luyoyu <8829470+chuangxxt@user.noreply.gitee.com>
2023-09-12 06:29:58 +00:00
ben Gutier d4f84153aa Merge branch 'master' of https://gitee.com/chuangxxt/share-copilot 2023-09-12 14:02:48 +08:00
ben Gutier a002cab328 改 2023-09-12 14:02:45 +08:00
ben Gutier aaa1592761 改错 2023-09-11 22:41:56 +08:00
ben Gutier fde826355f . 2023-09-11 17:03:17 +08:00
ben Gutier 7abff5fe83 优化 2023-09-11 12:24:04 +08:00
19 changed files with 571 additions and 413 deletions
+183
View File
@@ -0,0 +1,183 @@
The beta version now supports full interface proxy,
So even code suggestions go through the proxy,
Still in testing.
![输入图片说明](readme/screenshots.gif)
***
# share-copilot
- Acts as a proxy server, forwarding requests to the Copilot plugin's API
- Supports both vscode and Jetbrains plugins
- Supports multiple users sharing a single token
- Optimize request logic to reduce suspended probability、
![软件系统网络架构.png](https://img1.imgtp.com/2023/09/10/qTL8A2u9.png)
***
# 一、Build It Yourself:
```sh
Test Environment: Linux4.18.0-305.3.1.el8.x86_64 GNU/Linux
Requires Go environment;
resolve any issues chatgpt.
```
```sh
git clone https://gitlab.com/luyoyu/share-copilot.git
wget https://dl.google.com/go/go1.21.1.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.21.1.linux-amd64.tar.gz
vim ~/.bashrc
# Add the following environment variables
export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin
# Make the environment variables effective
source ~/.bashrc
# Verify the installation
go version
# CD to the source directory of main.go
cd /share-copilot/source
go build
```
***
# 二、Use the Ready-Made Version:
### 1.Installation
```sh
wget https://gitlab.com/luyoyu/share-copilot/uploads/73bca0887b3ea39622e88cb88d7d0297/share-copilot-linux-amd64.zip
```
```sh
unzip share-copilot-linux-amd64.zip
```
```sh
cd share-copilot
```
```sh
bash install.sh
```
### 2.Configuration
```sh
vim config.json
```
##### 2.1 Explanation of config.json
```js
domain // Listening domain or IP (can be reverse proxied with nginx)
host // IP
port // Port 80 or 443
certPath // Public key path - required for 443
keyPath // Private key path - required for 443
github_api_url // Default, usually not changed
token // Your Copilot token(s), you can put multiple, they will be used randomly in requests
// After logging into the Copilot plugin, find them in %userprofile%\AppData\Local\github-copilot\host.json (starting with "ghu_")
verification // Custom verification
```
##### 2.2 Example
```json
{
"server": {
"domain": "example.com",
"host": "0.0.0.0",
"port": 443,
"certPath":"./example.pem",
"keyPath":"./example.pem"
},
"copilot_config":{
"github_api_url": "https://api.github.com/copilot_internal/v2/token",
"token":[
"yours_token_1",
"yours_token_2",
"yours_token_3"
]},
"verification":""
}
```
The format must be correct;
### 3.Run
```sh
scop r # Run [Ctrl+c to exit] chmod +x share-copilot if Permission denied
scop rb # Run in the background
scop st # Stop
scop v # View status
```
### 4.Complete Example:
##### 4.1 Server-side Configuration (Modify config.json)
```json
{
"server": {
"domain": "api.example.com",
"host": "0.0.0.0",
"port": 443,
"certPath":"./example.pem",
"keyPath":"./example.pem"
},
"copilot_config":{
"github_api_url": "https://api.github.com/copilot_internal/v2/token",
"token":[
"ghu_xMNAYLcJAPqAfiGoobrWffkJoNcGMVJtETKA",
"ghu_GZgKFwraHorAxXXUvsUclOhxiYERPsSJeNuF",
"ghu_SPUTCLvkMKoeMstPJmhSlYsYvCojhkFjGubl"
]},
"verification":"i_am_free"
}
```
------
##### 4.3Local Configuration Changes:
**Using Windows as an example**
- **For Jetbrains Plugin: Modify %userprofile%\AppData\Local\github-copilot\host.json**
```json
{
"github.com":{
"user":"suibian",//Fill in as desired
"oauth_token":"i_am_free",// Corresponds to the "verification" value above
"dev_override":{
"copilot_token_url":"https://api.example.com/copilot_internal/v2/token"
// Your address
}
}
}
```
- **For Vscode Plugin: Modify %userprofile%\.vscode\extensions\github.copilot-xxxx\dist\extension.js**
```js
//Add the following code, note that you'll need to re-add it if the vscode plugin gets updated; Jetbrains does not require this step
process.env.GITHUB_TOKEN="i_am_free"; // Corresponds to the "verification" value above
process.env.GITHUB_API_URL="https://api.example.com"; // Your address
process.env.CODESPACES="true";
process.env.GITHUB_SERVER_URL="https://github.com";
```
------
##### **Successful Testing:**
![demo2.png](https://img1.imgtp.com/2023/09/09/FHDNLixL.png)
+55 -15
View File
@@ -1,16 +1,52 @@
[中文](README.md) / [English](README-EN.md)
------
测试版已经支持全部接口代理,
所有也就是代码提示也走代理,
还在测试中。
![输入图片说明](readme/screenshots.gif)
***
# share-copilot # share-copilot
- 作为代理服务器,中转copilot插件的API的请求 - 作为代理服务器,中转copilot插件的API的请求
- 支持vscode插件和jetbrains插件 - 支持vscode插件和jetbrains插件
- 支持多用户共享一个token - 支持多用户共享一个token
- 优化请求逻辑,降低token被ban概率(别万人骑基本不可能封) - 优化请求逻辑,降低suspended概率(别万人骑基本不会)
```sh
简单说一下本地插件原本的请求逻辑:
1.本地插件携ghu_token请求github的API
2.返回带有时间戳的copilot的token(下面简称co_token),代码提示都是用的co_token
3.co_token到期->ghu_token重新请求->获得新的co_token
-------------------------------------------------------------
代理服务器代理的是 ghu_token请求 这一环节:
1.携ghu_token请求github的API,暂存co_token
2.多用户请求时,判断co_token有没有过期,没过期直接返回,减少ghu_token的请求次数(大约10-20分钟过期)
至于本地co_token,也就是代码提示没有走代理(可以代理,但是要修改插件,jetbrains的插件还要重新build)
猜测风控目前也是停留在请求ghu_token这一层
```
![软件系统网络架构.png](https://img1.imgtp.com/2023/09/10/qTL8A2u9.png) ![软件系统网络架构.png](https://img1.imgtp.com/2023/09/10/qTL8A2u9.png)
***
# 一、自行编译: # 一、自行编译:
``` ```
测试环境:Linux4.18.0-305.3.1.el8.x86_64 GNU/Linux 测试环境:Linux4.18.0-305.3.1.el8.x86_64 GNU/Linux
需要 go环境 出问题自行chatgpt 需要 go环境 出问题自行chatgpt
``` ```
```sh ```sh
git clone https://gitee.com/chuangxxt/share-copilot.git
wget https://dl.google.com/go/go1.21.1.linux-amd64.tar.gz wget https://dl.google.com/go/go1.21.1.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.21.1.linux-amd64.tar.gz tar -C /usr/local -xzf go1.21.1.linux-amd64.tar.gz
@@ -19,22 +55,25 @@ vim ~/.bashrc
export PATH=$PATH:/usr/local/go/bin export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin export PATH=$PATH:$GOPATH/bin
#使生效环境变量 #使生效环境变量
source ~/.bashrc source ~/.bashrc
#验证安装 #验证go配置
go version go version
#cd到main.go源码目录 #cd到main.go源码目录
cd /share-copilot/source cd /share-copilot/src
go build go build
``` ```
***
# 二、使用现成: # 二、使用现成:
### 1.安装 ### 1.安装
```sh ```sh
git clone https://gitlab.com/luyoyu/share-copilot.git wget https://gitee.com/chuangxxt/share-copilot/releases/download/1.0.2/share-copilot-linux-amd64.zip
```
```sh
unzip share-copilot-linux-amd64.zip
``` ```
```sh ```sh
cd share-copilot cd share-copilot
@@ -45,6 +84,10 @@ bash install.sh
### 2.配置 ### 2.配置
```sh
vim config.json #修改配置信息
```
##### 2.1 config.json文件说明 ##### 2.1 config.json文件说明
```js ```js
@@ -92,11 +135,11 @@ verification//自定义验证
### 3.启动 ### 3.启动
``` ```sh
scop r --运行 [Esc退出] scop r #运行 [Ctrl+c退出] 如果运行失败添加可执行权限 chmod +x share-copilot
scop rb --后台运行 scop rb #后台运行
scop st --停止 scop st #停止
scop v --查看状态 scop v #查看是否运行
``` ```
### 4.完整例子: ### 4.完整例子:
@@ -153,7 +196,7 @@ scop v --查看状态
} }
} }
``` ```
- **vscode插件修改:%userprofile%\.vscode\extensions\github.copilot-xxxx\dist\extension.js** - **vscode插件修改:%userprofile%\\.vscode\extensions\github.copilot-xxxx\dist\extension.js**
```js ```js
//添加下列代码,注意vscode插件更新需要重新添加,jetbrains则不用 //添加下列代码,注意vscode插件更新需要重新添加,jetbrains则不用
@@ -168,6 +211,3 @@ process.env.GITHUB_SERVER_URL="https://github.com";
##### **4.4测试成功:** ##### **4.4测试成功:**
![demo2.png](https://img1.imgtp.com/2023/09/09/FHDNLixL.png) ![demo2.png](https://img1.imgtp.com/2023/09/09/FHDNLixL.png)
# 三、求投喂!谢谢您!
![微信截图_20230910204613.png](https://img1.imgtp.com/2023/09/10/G7qMbyxx.png)
-15
View File
@@ -1,15 +0,0 @@
{
"server": {
"domain": "example.con",
"host": "0.0.0.0",
"port": 443,
"certPath":"./example.pem",
"keyPath":"./example.pem"
},
"copilot_config":{
"github_api_url": "https://api.github.com/copilot_internal/v2/token",
"token":[
"yours_token"
]},
"verification":""
}
-46
View File
@@ -1,46 +0,0 @@
#!/bin/bash
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
START_SCRIPT_PATH="/usr/local/bin/scop"
cat > "$START_SCRIPT_PATH" <<EOF
#!/bin/bash
EXECUTABLE_DIR="$SCRIPT_DIR"
EXECUTABLE="\$EXECUTABLE_DIR/share-copilot"
case "\$1" in
r)
echo "Running share-copilot..."
"\$EXECUTABLE"
;;
rb)
echo "Running share-copilot in the background..."
"\$EXECUTABLE" >/dev/null 2>&1 &
;;
st)
echo "Stopping share-copilot..."
pkill -f "\$EXECUTABLE"
;;
v)
if pgrep -f "\$EXECUTABLE" >/dev/null; then
echo "share-copilot is running"
else
echo "share-copilot is not running"
fi
;;
*)
echo "Usage: \$0 {r|rb|st|v}"
exit 1
;;
esac
exit 0
EOF
chmod +x "$START_SCRIPT_PATH"
echo "-----------------
install success!
-----------------
scop r --运行
scop rb --后台运行
scop st --停止
scop v --查看状态
-----------------"
Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

BIN
View File
Binary file not shown.
-7
View File
@@ -1,7 +0,0 @@
/*.pem
/*.idea
/*.gitignore
/*.json
/config.json
/*.exe
/share-copilot
-10
View File
@@ -1,10 +0,0 @@
@echo off
SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build
@echo off
SET CGO_ENABLED=0
SET GOOS=windows
SET GOARCH=amd64
go build
View File
-316
View File
@@ -1,316 +0,0 @@
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"github.com/fatih/color"
"github.com/gin-gonic/gin"
"github.com/go-resty/resty/v2"
"io"
"log"
"math/rand"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
func main() {
//初始化配置文件
configFile = initConfig()
// 创建Gin引擎
gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = io.Discard
engine := gin.New()
// 设置信任的代理
err := engine.SetTrustedProxies([]string{"127.0.0.1"})
if err != nil {
log.Fatal(err)
}
// 初始化有效的token列表
initValidTokenList()
// 定义路由
domainDefault := engine.Group("/", DomainMiddleware(configFile.Server.Domain))
domainDefault.GET("/copilot_internal/v2/token", getGithubToken())
// 初始化服务器
initServer(engine)
// 显示信息
showMsg()
}
// 初始化服务器
func initServer(engine *gin.Engine) {
// 配置支持的应用程序协议
server := &http.Server{
Addr: ":443",
TLSConfig: &tls.Config{
NextProtos: []string{"http/1.1", "http/1.2", "http/2"}, // 支持的应用程序协议列表
},
Handler: engine,
}
// 启动Gin服务器并监听端口
listenAddress := configFile.Server.Host + ":" + strconv.Itoa(configFile.Server.Port)
go func() {
if configFile.Server.Port != 443 {
err := engine.Run(listenAddress)
if err != nil {
log.Fatal(err)
}
} else {
err := server.ListenAndServeTLS(configFile.Server.CertPath, configFile.Server.KeyPath)
if err != nil {
log.Fatal(err)
}
}
}()
}
// 初始化有效的token列表
func initValidTokenList() {
//为了安全起见,应该等待请求完成并处理其响应。
var wg sync.WaitGroup
for _, token := range configFile.CopilotConfig.Token {
wg.Add(1)
go func(token string) {
defer wg.Done()
if getGithubApi(token) {
validTokenList[token] = true
}
}(token)
}
wg.Wait()
}
// 获取Github的token
func getGithubToken() gin.HandlerFunc {
return func(c *gin.Context) {
// 请求计数
requestCount++
// 如果配置了verification,则需要获取请求头中的Authorization令牌
if configFile.Verification != "" {
token := c.GetHeader("Authorization")
tokenStr := strings.ReplaceAll(token, " ", "")
configCert := strings.ReplaceAll(configFile.Verification, " ", "")
if tokenStr != "token"+configCert {
// 拒绝不符合Verification的请求
badRequest(c)
return
}
}
//从有效的token列表中随机获取一个token
token := getRandomToken(validTokenList)
//判断tokenMap 里的token是否存在
if _, exists := tokenMap[token]; exists {
respDataMap := tokenMap[token]
//判断时间戳key是否存在
if _, exists := respDataMap["expires_at"]; exists {
// 获取当前时间的Unix时间戳
currentTime := time.Now().Unix()
if expiresAt, ok := respDataMap["expires_at"].(float64); ok {
// 判断expires_at是否已经过期
expiresAtInt64 := int64(expiresAt)
//提前一分钟请求
if expiresAtInt64 > currentTime+60 {
//fmt.Println("\n未过期无需请求")
proxyResp(c, tokenMap[token])
} else {
//fmt.Println("\n已过期重新请求")
if getGithubApi(token) {
proxyResp(c, tokenMap[token])
return
} else {
badRequest(c)
}
}
} else {
badRequest(c)
}
} else {
//tokenMap里的token对应的返回体不存在expires_at
if getGithubApi(token) {
proxyResp(c, tokenMap[token])
return
} else {
badRequest(c)
}
}
} else {
//不存在则githubApi发送请求,并存到tokenMap
if getGithubApi(token) {
proxyResp(c, tokenMap[token])
return
} else {
badRequest(c)
}
}
}
}
// 请求错误
func badRequest(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Bad credentials",
"documentation_url": "https://docs.github.com/rest"})
}
// 本服务器响应
func proxyResp(c *gin.Context, respDataMap map[string]interface{}) {
// 将map转换为JSON字符串
responseJSON, err := json.Marshal(respDataMap)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "JSON marshaling error"})
}
// 请求成功统计
successCount++
// 将JSON字符串作为响应体返回
c.Header("Content-Type", "application/json")
c.String(http.StatusOK, string(responseJSON))
}
// 请求githubApi
func getGithubApi(token string) bool {
githubApiCount++
// 设置请求头
headers := map[string]string{
"Authorization": "token " + token,
/*"editor-version": c.GetHeader("editor-version"),
"editor-plugin-version": c.GetHeader("editor-plugin-version"),
"user-agent": c.GetHeader("user-agent"),
"accept": c.GetHeader("accept"),
"accept-encoding": c.GetHeader("accept-encoding"),*/
}
// 发起GET请求
response, err := resty.New().R().
SetHeaders(headers).
Get(configFile.CopilotConfig.GithubApiUrl)
if err != nil {
// 处理请求错误
return false
}
// 判断响应状态码
if response.StatusCode() == http.StatusOK {
// 响应状态码为200 OK
respDataMap := map[string]interface{}{}
err = json.Unmarshal(response.Body(), &respDataMap)
if err != nil {
// 处理JSON解析错误
return false
}
//token map
tokenMap[token] = respDataMap
return true
} else {
// 处理其他状态码
delete(validTokenList, token)
return false
}
}
// 初始化配置文件
func initConfig() Config {
// 读取配置文件
exePath, err := os.Executable()
if err != nil {
panic(err)
}
// 获取执行文件所在目录
exeDir := filepath.Dir(exePath)
configFile, err := os.Open(exeDir + "/config.json")
if err != nil {
panic("file \"./config.json\" not found")
}
defer func(configFile *os.File) {
err := configFile.Close()
if err != nil {
panic("close file \"./config.json\" err")
}
}(configFile)
decoder := json.NewDecoder(configFile)
config := Config{}
err = decoder.Decode(&config)
if err != nil {
panic("config format err")
}
return config
}
// 重置请求计数
func resetRequestCount() {
requestCountMutex.Lock()
defer requestCountMutex.Unlock()
requestCount = 0
successCount = 0
}
// 从map中随机获取一个key
func getRandomToken(m map[string]bool) string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
if len(keys) == 0 {
return "" // 返回空字符串或处理其他错误情况
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
randomIndex := r.Intn(len(keys))
return keys[randomIndex]
}
// DomainMiddleware 域名中间件
func DomainMiddleware(domain string) gin.HandlerFunc {
return func(c *gin.Context) {
// 检查域名是否匹配
requestDomain := strings.Split(c.Request.Host, ":")[0]
if requestDomain == domain || requestDomain == "127.0.0.1" {
c.Next()
} else {
c.String(403, "Forbidden")
c.Abort()
}
}
}
// 显示信息
func showMsg() {
var url = ""
if configFile.Server.Port == 80 {
url = "http://" + configFile.Server.Domain
} else if configFile.Server.Port == 443 {
url = "https://" + configFile.Server.Domain
} else {
url = "http://" + configFile.Server.Domain + ":" + strconv.Itoa(configFile.Server.Port)
}
var jetStr = color.WhiteString("[Jetbrains]")
var vsStr = color.WhiteString("[Vscode]")
var valid = color.WhiteString("[Valid tokens]")
fmt.Println(jetStr + ": " + color.HiBlueString(url+"/copilot_internal/v2/token"))
fmt.Println(vsStr + ": " + color.HiBlueString(url))
fmt.Println(valid + ": " + color.HiBlueString(strconv.Itoa(len(validTokenList))))
fmt.Println(color.WhiteString("-----------------------------------------------------------------------"))
for {
requestCountMutex.Lock()
sCount := successCount
tCount := requestCount
gCount := githubApiCount
requestCountMutex.Unlock()
currentTime := time.Now().Format("2006-01-02 15:04:05")
if "00:00:00" == currentTime {
resetRequestCount()
}
var s2 = color.WhiteString("[Succeed]")
var s3 = color.WhiteString("[Failed]")
var s4 = color.WhiteString("[GithubApi]")
// 打印文本
fmt.Printf("\033[G%s - %s: %s %s: %s %s: %s ",
color.HiYellowString(currentTime),
s2, color.GreenString(strconv.Itoa(sCount)),
s3, color.RedString(strconv.Itoa(tCount-sCount)),
s4, color.CyanString(strconv.Itoa(gCount)))
time.Sleep(1 * time.Second) //
}
}
View File
+142
View File
@@ -0,0 +1,142 @@
package main
import (
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
"github.com/go-resty/resty/v2"
"math/rand"
"net/http"
"strings"
"sync"
"time"
)
// 初始化有效的github token列表
func initValidTokenList() {
//为了安全起见,应该等待请求完成并处理其响应。
var wg sync.WaitGroup
for _, token := range configFile.CopilotConfig.Token {
wg.Add(1)
go func(token string) {
defer wg.Done()
if getGithubApi(token) {
validTokenList[token] = true
}
}(token)
}
wg.Wait()
}
// 请求github api
func getGithubApi(token string) bool {
githubApiCount++
// 设置请求头
headers := map[string]string{
"Authorization": "token " + token,
/*"editor-version": c.GetHeader("editor-version"),
"editor-plugin-version": c.GetHeader("editor-plugin-version"),
"user-agent": c.GetHeader("user-agent"),
"accept": c.GetHeader("accept"),
"accept-encoding": c.GetHeader("accept-encoding"),*/
}
// 发起GET请求
response, err := resty.New().R().
SetHeaders(headers).
Get(configFile.CopilotConfig.GithubApiUrl)
if err != nil {
// 处理请求错误
return false
}
// 判断响应状态码
if response.StatusCode() == http.StatusOK {
// 响应状态码为200 OK
respDataMap := map[string]interface{}{}
err = json.Unmarshal(response.Body(), &respDataMap)
if err != nil {
// 处理JSON解析错误
return false
}
//token map
tokenMap[token] = respDataMap
return true
} else {
// 处理其他状态码
delete(validTokenList, token)
return false
}
}
// 获取copilot token
func getGithubToken() gin.HandlerFunc {
return func(c *gin.Context) {
requestCount++
if err := verifyRequest(c); err != nil {
badRequest(c)
return
}
token := getRandomToken(validTokenList)
if respDataMap, exists := getTokenData(token); exists {
if !isTokenExpired(respDataMap) {
proxyResp(c, respDataMap)
return
}
}
if getGithubApi(token) {
proxyResp(c, tokenMap[token])
} else {
badRequest(c)
}
}
}
// 验证请求代理请求token
func verifyRequest(c *gin.Context) error {
if configFile.Verification != "" {
token := c.GetHeader("Authorization")
tokenStr := strings.ReplaceAll(token, " ", "")
configCert := strings.ReplaceAll(configFile.Verification, " ", "")
if tokenStr != "token"+configCert {
return errors.New("verification failed")
}
}
return nil
}
// 从map中获取github token对应的copilot token
func getTokenData(token string) (map[string]interface{}, bool) {
respDataMap, exists := tokenMap[token]
return respDataMap, exists
}
// 检测copilot token是否过期
func isTokenExpired(respDataMap map[string]interface{}) bool {
if expiresAt, ok := respDataMap["expires_at"].(float64); ok {
currentTime := time.Now().Unix()
expiresAtInt64 := int64(expiresAt)
return expiresAtInt64 <= currentTime+60
}
return true
}
// 重置请求计数
func resetRequestCount() {
requestCountMutex.Lock()
defer requestCountMutex.Unlock()
requestCount = 0
successCount = 0
}
// 从map中随机获取一个github token
func getRandomToken(m map[string]bool) string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
if len(keys) == 0 {
return "" // 返回空字符串或处理其他错误情况
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
randomIndex := r.Intn(len(keys))
return keys[randomIndex]
}
View File
View File
+21
View File
@@ -0,0 +1,21 @@
package main
func main() {
// 初始化配置文件
configFile = initConfig()
// 创建Gin引擎
engine := setupGinEngine()
// 初始化有效的token列表
initValidTokenList()
// 定义路由
setupRoutes(engine)
// 初始化并启动服务器
initAndStartServer(engine)
// 显示信息
showMsg()
}
+121
View File
@@ -0,0 +1,121 @@
package main
import (
"crypto/tls"
"encoding/json"
"github.com/gin-gonic/gin"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
)
// 初始化配置文件
func initConfig() Config {
// 读取配置文件
exePath, err := os.Executable()
if err != nil {
panic(err)
}
// 获取执行文件所在目录
exeDir := filepath.Dir(exePath)
configFile, err := os.Open(exeDir + "/config.json")
if err != nil {
panic("file \"./config.json\" not found")
}
defer func(configFile *os.File) {
err := configFile.Close()
if err != nil {
panic("close file \"./config.json\" err")
}
}(configFile)
decoder := json.NewDecoder(configFile)
config := Config{}
err = decoder.Decode(&config)
if err != nil {
panic("config format err")
}
return config
}
// 创建和配置Gin引擎
func setupGinEngine() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = io.Discard
engine := gin.New()
// 设置信任的代理
if err := engine.SetTrustedProxies([]string{"127.0.0.1"}); err != nil {
log.Fatal(err)
}
return engine
}
// 定义路由和中间件
func setupRoutes(engine *gin.Engine) {
domainDefault := engine.Group("/", DomainMiddleware(configFile.Server.Domain))
domainDefault.GET("/copilot_internal/v2/token", getGithubToken())
}
// DomainMiddleware 域名中间件
func DomainMiddleware(domain string) gin.HandlerFunc {
return func(c *gin.Context) {
// 检查域名是否匹配
requestDomain := strings.Split(c.Request.Host, ":")[0]
if requestDomain == domain || requestDomain == "127.0.0.1" {
c.Next()
} else {
c.String(403, "Forbidden")
c.Abort()
}
}
}
// 初始化和启动服务器
func initAndStartServer(engine *gin.Engine) {
listenAddress := configFile.Server.Host + ":" + strconv.Itoa(configFile.Server.Port)
server := createTLSServer(engine, listenAddress)
go func() {
if configFile.Server.Port != 443 {
err := engine.Run(listenAddress)
log.Fatal(err)
} else {
err := server.ListenAndServeTLS(configFile.Server.CertPath, configFile.Server.KeyPath)
log.Fatal(err)
}
}()
}
// 创建TLS服务器配置
func createTLSServer(engine *gin.Engine, address string) *http.Server {
return &http.Server{
Addr: address,
TLSConfig: &tls.Config{
NextProtos: []string{"http/1.1", "http/1.2", "http/2"},
},
Handler: engine,
}
}
// 本服务器响应
func proxyResp(c *gin.Context, respDataMap map[string]interface{}) {
// 将map转换为JSON字符串
responseJSON, err := json.Marshal(respDataMap)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "JSON marshaling error"})
}
// 请求成功统计
successCount++
// 将JSON字符串作为响应体返回
c.Header("Content-Type", "application/json")
c.String(http.StatusOK, string(responseJSON))
}
// 请求错误
func badRequest(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Bad credentials",
"documentation_url": "https://docs.github.com/rest"})
}
+48
View File
@@ -0,0 +1,48 @@
package main
import (
"fmt"
"github.com/fatih/color"
"strconv"
"time"
)
// 控制台显示信息
func showMsg() {
var url = ""
if configFile.Server.Port == 80 {
url = "http://" + configFile.Server.Domain
} else if configFile.Server.Port == 443 {
url = "https://" + configFile.Server.Domain
} else {
url = "http://" + configFile.Server.Domain + ":" + strconv.Itoa(configFile.Server.Port)
}
var jetStr = color.WhiteString("[Jetbrains]")
var vsStr = color.WhiteString("[Vscode]")
var valid = color.WhiteString("[Valid tokens]")
fmt.Println(jetStr + ": " + color.HiBlueString(url+"/copilot_internal/v2/token"))
fmt.Println(vsStr + ": " + color.HiBlueString(url))
fmt.Println(valid + ": " + color.HiBlueString(strconv.Itoa(len(validTokenList))))
fmt.Println(color.WhiteString("-----------------------------------------------------------------------"))
for {
requestCountMutex.Lock()
sCount := successCount
tCount := requestCount
gCount := githubApiCount
requestCountMutex.Unlock()
currentTime := time.Now().Format("2006-01-02 15:04:05")
if "00:00:00" == currentTime {
resetRequestCount()
}
var s2 = color.WhiteString("[Succeed]")
var s3 = color.WhiteString("[Failed]")
var s4 = color.WhiteString("[GithubApi]")
// 打印文本
fmt.Printf("\033[G%s - %s: %s %s: %s %s: %s ",
color.HiYellowString(currentTime),
s2, color.GreenString(strconv.Itoa(sCount)),
s3, color.RedString(strconv.Itoa(tCount-sCount)),
s4, color.CyanString(strconv.Itoa(gCount)))
time.Sleep(1 * time.Second) //
}
}
View File
-3
View File
@@ -1,3 +0,0 @@
START_SCRIPT_PATH="/usr/local/bin/scop"
rm -f "$START_SCRIPT_PATH"
echo "卸载完成!"