Repository navigation
Expand file tree
/
Copy pathmimo.ts
More file actions
243 lines (221 loc) · 9.43 KB
/
Copy pathmimo.ts
File metadata and controls
243 lines (221 loc) · 9.43 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
import type { Hooks, PluginInput } from "@mimo-ai/plugin"
import { Log } from "../util"
import { createServer } from "http"
import crypto from "crypto"
import { exec } from "child_process"
import { Global } from "../global"
import path from "path"
import fs from "fs"
const log = Log.create({ service: "plugin.mimo" })
const PLATFORM_URL = process.env.MIMO_PLATFORM_URL || "https://platform.xiaomimimo.com"
function getKeyName(): string {
const filePath = path.join(Global.Path.data, "mimo-key-name")
try {
const existing = fs.readFileSync(filePath, "utf-8").trim()
if (existing) return existing
} catch {}
const name = `mimo-code-cli-key-${crypto.randomBytes(4).toString("hex")}`
fs.writeFileSync(filePath, name)
return name
}
function generateKeyPair() {
const keyPair = crypto.generateKeyPairSync("x25519", {
publicKeyEncoding: { type: "spki", format: "der" },
privateKeyEncoding: { type: "pkcs8", format: "der" },
})
const publicKeyBase64 = Buffer.from(keyPair.publicKey).toString("base64url")
return { publicKey: publicKeyBase64, privateKeyDer: keyPair.privateKey }
}
function decrypt(privateKeyDer: Buffer, encryptedBase64: string): { sk?: string; uid: string; url?: string } {
const encrypted = Buffer.from(encryptedBase64, "base64url")
// Format: ephemeralPublicKey(32 bytes) + nonce(12 bytes) + ciphertext + tag(16 bytes)
const ephemeralPub = encrypted.subarray(0, 32)
const nonce = encrypted.subarray(32, 44)
const ciphertextAndTag = encrypted.subarray(44)
const tag = ciphertextAndTag.subarray(ciphertextAndTag.length - 16)
const ciphertext = ciphertextAndTag.subarray(0, ciphertextAndTag.length - 16)
const privateKey = crypto.createPrivateKey({ key: privateKeyDer, format: "der", type: "pkcs8" })
const ephemeralPublicKey = crypto.createPublicKey({
key: Buffer.concat([Buffer.from("302a300506032b656e032100", "hex"), ephemeralPub]),
format: "der",
type: "spki",
})
const sharedSecret = crypto.diffieHellman({ privateKey, publicKey: ephemeralPublicKey })
const derivedKey = crypto.createHash("sha256").update(sharedSecret).digest()
const decipher = crypto.createDecipheriv("aes-256-gcm", derivedKey, nonce)
decipher.setAuthTag(tag)
const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()])
return JSON.parse(decrypted.toString("utf-8"))
}
function openBrowser(url: string) {
if (process.env.CI || process.env.NODE_ENV === "test") return
const command =
process.platform === "darwin"
? `open "${url}"`
: process.platform === "win32"
? `start "" "${url}"`
: `xdg-open "${url}"`
exec(command, (error) => {
if (error) {
log.warn("could not open browser automatically", { error })
}
})
}
function buildAuthorizeUrl(publicKey: string, redirectUri: string): string {
const params = new URLSearchParams({
pk: publicKey,
redirect_uri: redirectUri,
kn: "mimocode",
key_name: getKeyName(),
})
return `${PLATFORM_URL}/authorize?${params.toString()}`
}
export async function MimoAuthPlugin(_input: PluginInput): Promise<Hooks> {
return {
config: async (input) => {
input.provider ??= {}
input.provider.xiaomi ??= {}
const xiaomi = input.provider.xiaomi
xiaomi.name ??= "MiMo"
xiaomi.api ??= "https://api.xiaomimimo.com/v1"
// Both "opencode" and "opencode-go" stay enabled. The opencode custom
// loader strips the free/public tier (and hides paid models until the
// user authenticates). "opencode-go" has no free models and no custom
// loader, so it only loads once a subscription key/auth is present.
},
auth: {
provider: "xiaomi",
async loader(getAuth) {
const auth = (await getAuth()) as { type: string; metadata?: Record<string, string> }
if (auth?.type !== "api" || !auth.metadata?.base_url) return {}
return { baseURL: auth.metadata.base_url }
},
methods: [
{
label: "浏览器登录",
type: "oauth" as const,
authorize: async () => {
const { publicKey, privateKeyDer } = generateKeyPair()
const server = createServer()
await new Promise<void>((resolve, reject) => {
server.listen(0, () => resolve())
server.on("error", reject)
})
const addr = server.address()
const port = typeof addr === "object" && addr ? addr.port : 0
log.info("mimo oauth server started", { port })
const redirectUri = `http://localhost:${port}/`
const authUrl = buildAuthorizeUrl(publicKey, redirectUri)
const manualUrl = buildAuthorizeUrl(publicKey, `${PLATFORM_URL}/authorize/code/callback`)
openBrowser(authUrl)
const serverCallbackPromise = new Promise<{ sk?: string; uid: string; url?: string }>((resolve, reject) => {
const timeout = setTimeout(() => {
server.close()
reject(new Error("Authorization timeout"))
}, 5 * 60 * 1000)
server.on("request", (req, res) => {
const url = new URL(req.url || "/", `http://localhost`)
log.info("mimo oauth callback received", { path: url.pathname, query: url.search.substring(0, 100) })
const u = url.searchParams.get("u")
if (!u) {
log.warn("mimo oauth callback missing u param")
res.writeHead(302, { Location: `${PLATFORM_URL}/authorize/callback?status=error&message=missing_data` })
res.end()
reject(new Error("Missing encrypted data"))
return
}
try {
const result = decrypt(privateKeyDer, u)
log.info("mimo oauth decrypt success", { uid: result.uid, url: result.url })
res.writeHead(302, { Location: `${PLATFORM_URL}/authorize/callback?status=success` })
res.end()
clearTimeout(timeout)
resolve(result)
} catch (err) {
log.error("mimo oauth decrypt failed", { error: err })
res.writeHead(302, { Location: `${PLATFORM_URL}/authorize/callback?status=error&message=decrypt_failed` })
res.end()
reject(new Error("Decryption failed"))
}
})
})
serverCallbackPromise.catch(() => {})
return {
url: manualUrl,
method: "auto" as const,
instructions: "在浏览器中完成授权,或粘贴 Code 完成登录。",
callback: async (code?: string) => {
if (code) {
try {
const result = decrypt(privateKeyDer, code.trim())
server.close()
const metadata: Record<string, string> = { uid: result.uid }
if (result.url) metadata.base_url = result.url
return { type: "success" as const, key: result.sk ?? "", metadata }
} catch {
return { type: "failed" as const }
}
}
try {
const result = await serverCallbackPromise
server.close()
const metadata: Record<string, string> = { uid: result.uid }
if (result.url) metadata.base_url = result.url
return { type: "success" as const, key: result.sk ?? "", metadata }
} catch {
server.close()
return { type: "failed" as const }
}
},
}
},
},
],
},
"chat.headers": async (input, output) => {
if (input.model.providerID !== "xiaomi") return
output.headers["X-Mimo-Source"] = "mimocode-cli"
},
}
}
export async function AnthropicProxyPlugin(_input: PluginInput): Promise<Hooks> {
return {
auth: {
provider: "anthropic",
async loader(_getAuth, provider) {
if (!provider?.options?.baseURL) return {}
return {
async fetch(url: any, init: any) {
if (init?.headers && typeof init.headers === "object" && !Array.isArray(init.headers)) {
delete init.headers["anthropic-beta"]
}
const res = await fetch(url, init)
if (!res.body || !res.headers.get("content-type")?.includes("text/event-stream")) return res
const reader = res.body.getReader()
const decoder = new TextDecoder()
let done = false
let buffer = ""
const body = new ReadableStream<Uint8Array>({
async pull(ctrl) {
if (done) { ctrl.close(); return }
const chunk = await reader.read()
if (chunk.done) { ctrl.close(); return }
ctrl.enqueue(chunk.value)
buffer += decoder.decode(chunk.value, { stream: true })
if (buffer.includes("\nevent: message_stop\n") || buffer.includes("\ndata: {\"type\":\"message_stop\"}")) {
done = true
void reader.cancel()
ctrl.close()
}
if (buffer.length > 512) buffer = buffer.slice(-256)
},
cancel() { reader.cancel() },
})
return new Response(body, { headers: res.headers, status: res.status })
},
}
},
methods: [],
},
}
}