-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
334 lines (287 loc) · 11.4 KB
/
main.go
File metadata and controls
334 lines (287 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package main
import (
"bufio"
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/user"
"path/filepath"
"strconv"
"time"
"github.com/google/uuid"
)
const (
IFLOW_BASE_URL = "https://apis.iflow.cn/v1" // эндпоинт из CLI
PROXY_PORT = "8318"
LOG_FILE = "proxy.log"
)
var (
apikey string
logFilePath string
)
type IFlowSettings struct {
ApiKey string `json:"apiKey"`
}
// getIFlowAPIKey читает API ключ из файла настроек пользователя (~/.iflow/settings.json).
func getIFlowAPIKey() (string, error) {
usr, err := user.Current()
if err != nil {
return "", fmt.Errorf("user: %w", err)
}
configPath := filepath.Join(usr.HomeDir, ".iflow", "settings.json")
data, err := os.ReadFile(configPath)
if err != nil {
return "", fmt.Errorf("read config: %w", err)
}
var settings IFlowSettings
if err := json.Unmarshal(data, &settings); err != nil {
return "", fmt.Errorf("parse config: %w", err)
}
if settings.ApiKey == "" {
return "", fmt.Errorf("API key empty")
}
return settings.ApiKey, nil
}
// createSignature создает HMAC-SHA256 подпись для аутентификации в iFlow API.
// Параметры включают User-Agent, sessionID и временную метку.
func createSignature(userAgent, sessionID string, timestamp int64, key string) string {
payload := fmt.Sprintf("%s:%s:%d", userAgent, sessionID, timestamp)
h := hmac.New(sha256.New, []byte(key))
h.Write([]byte(payload))
return hex.EncodeToString(h.Sum(nil))
}
// logToFile записывает отладочную информацию в файл proxy.log вместе с меткой времени.
func logToFile(format string, args ...interface{}) {
f, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Printf("log open: %v", err)
return
}
defer f.Close()
ts := time.Now().Format("2006-01-02 15:04:05")
fmt.Fprintf(f, "[%s] %s\n", ts, fmt.Sprintf(format, args...))
}
// corsMiddleware добавляет HTTP заголовки для поддержки Cross-Origin Resource Sharing.
// Позволяет браузерам и расширениям (Kilo Code и др.) обращаться к прокси напрямую.
func corsMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "*")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next(w, r)
}
}
// ─── /v1/models ──────────────────────────────────────────────────────────────
type ModelsResponse struct {
Data []ModelItem `json:"data"`
Object string `json:"object"`
}
type ModelItem struct {
ID string `json:"id"`
Object string `json:"object"`
OwnedBy string `json:"owned_by"`
Created int64 `json:"created"`
}
func modelsHandler(w http.ResponseWriter, r *http.Request) {
logToFile("→ Models request: %s %s (Path: %s)", r.Method, r.URL.Path, r.URL.Path)
if r.URL.Path != "/v1/models" {
logToFile("✗ Models: Path mismatch - expected /v1/models, got %s", r.URL.Path)
http.Error(w, "Not Found", http.StatusNotFound)
return
}
// Генерируем уникальный sessionID для запроса
requestSessionID := "session-" + uuid.New().String()
// Создаем запрос к iFlow API для получения списка моделей
userAgent := "iFlow-Cli"
timestamp := time.Now().UnixMilli()
signature := createSignature(userAgent, requestSessionID, timestamp, apikey)
upstreamReq, err := http.NewRequest("GET", IFLOW_BASE_URL+"/models", nil)
if err != nil {
logToFile("✗ Models: Create upstream request: %v", err)
http.Error(w, "Create upstream: "+err.Error(), http.StatusInternalServerError)
return
}
// Заголовки аутентификации для iFlow все как в iflow CLI (включая специальные заголовки)
upstreamReq.Header.Set("Content-Type", "application/json")
upstreamReq.Header.Set("Authorization", "Bearer "+apikey)
upstreamReq.Header.Set("User-Agent", userAgent)
upstreamReq.Header.Set("session-id", requestSessionID)
upstreamReq.Header.Set("conversation-id", "")
upstreamReq.Header.Set("x-iflow-timestamp", strconv.FormatInt(timestamp, 10))
upstreamReq.Header.Set("x-iflow-signature", signature)
// Выполняем запрос
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(upstreamReq)
if err != nil {
logToFile("✗ Models: Upstream request: %v", err)
http.Error(w, "Upstream: "+err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
// Читаем тело ответа
respBody, err := io.ReadAll(resp.Body)
if err != nil {
logToFile("✗ Models: Read response body: %v", err)
http.Error(w, "Read response: "+err.Error(), http.StatusBadGateway)
return
}
// Логируем полученный ответ для отладки
logToFile("← Models upstream response: %s", string(respBody))
// Парсим ответ от API
var upstreamResponse ModelsResponse
if err := json.Unmarshal(respBody, &upstreamResponse); err != nil {
logToFile("✗ Models: Parse upstream response: %v", err)
http.Error(w, "Parse response: "+err.Error(), http.StatusBadGateway)
return
}
// Добавляем захардкоженные модели, которые должны быть доступны
// (даже если они не возвращаются в списке API, они будут работать через прокси - проверенно практикой =)
hardcodedModels := []ModelItem{
{ID: "glm-5", Object: "model", Created: 1770000000, OwnedBy: "iflow"},
{ID: "glm-4.7", Object: "model", Created: 1760000000, OwnedBy: "iflow"},
{ID: "kimi-k2.5", Object: "model", Created: 1769472000, OwnedBy: "moonshot"},
{ID: "kimi-k2-thinking", Object: "model", Created: 1762387200, OwnedBy: "moonshot"},
{ID: "minimax-m2.5", Object: "model", Created: 1750000000, OwnedBy: "minimax"},
}
// Объединяем списки, убирая дубликаты
modelMap := make(map[string]ModelItem)
// Сначала добавляем модели из API
for _, model := range upstreamResponse.Data {
modelMap[model.ID] = model
}
// Затем добавляем захардкоженные модели (они перезапишут существующие, если есть)
for _, model := range hardcodedModels {
modelMap[model.ID] = model
}
// Формируем итоговый список
var allModels []ModelItem
for _, model := range modelMap {
allModels = append(allModels, model)
}
response := ModelsResponse{
Object: "list",
Data: allModels,
}
// Логируем JSON ответ для отладки
jsonBytes, _ := json.MarshalIndent(response, "", " ")
logToFile("← Models response: %s", string(jsonBytes))
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
logToFile("← Models: %d", resp.StatusCode)
}
// ─── /v1/chat/completions — ПРОСТОЙ ПРОКСИ БЕЗ ТРАНСФОРМАЦИЙ ───────────────
func proxyHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/chat/completions" {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
// Читаем тело запроса "как есть"
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Read body: "+err.Error(), http.StatusBadRequest)
return
}
defer r.Body.Close()
logToFile("→ Request: %s %s", r.Method, r.URL.Path)
// Генерируем уникальный sessionID для запроса
requestSessionID := "session-" + uuid.New().String()
// Готовим запрос к iFlow: тело передаём без изменений
userAgent := "iFlow-Cli"
timestamp := time.Now().UnixMilli()
signature := createSignature(userAgent, requestSessionID, timestamp, apikey)
upstreamReq, err := http.NewRequest("POST", IFLOW_BASE_URL+"/chat/completions", bytes.NewReader(body))
if err != nil {
logToFile("✗ Request: Create upstream request: %v", err)
http.Error(w, "Create upstream: "+err.Error(), http.StatusInternalServerError)
return
}
// Заголовки аутентификации для iFlow
upstreamReq.Header.Set("Content-Type", "application/json")
upstreamReq.Header.Set("Authorization", "Bearer "+apikey)
upstreamReq.Header.Set("User-Agent", userAgent)
upstreamReq.Header.Set("session-id", requestSessionID)
upstreamReq.Header.Set("conversation-id", "")
upstreamReq.Header.Set("x-iflow-timestamp", strconv.FormatInt(timestamp, 10))
upstreamReq.Header.Set("x-iflow-signature", signature)
// Выполняем запрос (увеличен таймаут до 300с)
client := &http.Client{Timeout: 300 * time.Second}
resp, err := client.Do(upstreamReq)
if err != nil {
logToFile("✗ Request: Upstream request error: %v", err)
http.Error(w, "Upstream: "+err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
// Пробрасываем заголовки ответа (кроме конфликтующих)
for k, vals := range resp.Header {
if k == "Content-Type" || k == "Content-Length" || k == "Transfer-Encoding" {
continue
}
for _, v := range vals {
w.Header().Add(k, v)
}
}
// Определяем тип ответа
isStream := resp.Header.Get("Content-Type") == "text/event-stream"
// Если мы ожидаем стрим, но пришла ошибка (не 200), то это точно не стрим
if resp.StatusCode != http.StatusOK && !isStream {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
logToFile("← Response (Error): %d", resp.StatusCode)
return
}
if isStream {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(resp.StatusCode)
reader := bufio.NewReader(resp.Body)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
if err != io.EOF {
logToFile("✗ Stream: Read error: %v", err)
}
break
}
w.Write(line)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
} else {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
logToFile("← Response: %d", resp.StatusCode)
}
// ─── Main ───────────────────────────────────────────────────────────────────
func main() {
execPath, _ := os.Executable()
logFilePath = filepath.Join(filepath.Dir(execPath), LOG_FILE)
var err error
apikey, err = getIFlowAPIKey()
if err != nil {
log.Fatalf("API key: %v", err)
}
log.Printf("✓ Simple proxy started (no content transformation)")
log.Printf("✓ Logging to: %s", logFilePath)
http.HandleFunc("/v1/chat/completions", corsMiddleware(proxyHandler))
http.HandleFunc("/v1/models", corsMiddleware(modelsHandler))
addr := ":" + PROXY_PORT
fmt.Printf("🚀 iFlow Proxy (SIMPLE) → http://localhost%s\n", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}