qoder 0.2.41: a chat carries the headers Qoder's client puts on a chat, not the machine id three times (#443)
unifilitence (plugins#443, Windows 11 x64, qoder.com) captured a chat
going out with the account's machine UUID as Cosy-ClientIp,
Cosy-MachineId and Cosy-MachineToken alike, Cosy-MachineType 5 and
Cosy-MachineOS x86_64_win32, and asked for each to be what Qoder's own
client sends.
Checked against Qoder.app 0.4.3: its worker runtime
(qoder-agent-sdk/dist/_worker) and the auth wasm it embeds, run here
with its own inputs:
- Cosy-MachineOS is `${x64->x86_64, arm64->aarch64, else arch}_${platform}`,
so x86_64_win32 is Qoder's own value. Only ia32 differed: the plugin
sent x86_win32, Qoder sends ia32_win32. Fixed.
- Its non-chat calls (prepareRequest) do send ClientIp, MachineId and
MachineToken all as the machine id, MachineType 5. The listing, usage
and queue status keep that set.
- A chat (prepareInferRequest, then its header pass) differs: no
Cosy-ClientIp; MachineToken and MachineType are the native device
identity's (umid runtime-info) or absent when there is none; and a
Cosy-MachineHostname, os.hostname() made safe as its zei does
(punycode, else "-" runs plus a sha256 mark, 96 chars at most). A chat
now goes so. The identity is one the check-in already read in this
process (renewed behind the chat after an hour); a chat never runs the
helper itself, so with no check-in yet it goes without, as Qoder does
when it has no identity.
- The signed payload's requestId is a dashed UUID in Qoder's signer; the
plugin sent it undashed. ideVersion "" is Qoder's own.
Left as it was: Accept-Encoding identity on a chat (Qoder sets none;
its fetch's default differs from Bun's anyway).
Run: packages/qoder `bun test` (276 pass, new headers.test.mjs and one
check-in test); `bun scripts/check.mjs` all green. Real qoder.com
account from bun in a sandbox HOME (token not renewed, no auth.set):
qfmodel answered "pong" with the new chat headers, dfmodel queued
(10605, as before), the model list 200.
Broken by hand: index.mjs at HEAD with the new tests: 6 of 7 in
headers.test.mjs and the check-in chat test red.
Not tried: Windows (the hostname and OS values are unit-tested for
it); a chat carrying a real device identity against the live service.
This commit is contained in:
@@ -412,3 +412,36 @@ test("another page on the openapi host is still refused", async () => {
|
||||
expect(res.status).toBe(404)
|
||||
expect(p.seen).toEqual([])
|
||||
})
|
||||
|
||||
// plugins#443: Qoder's client puts its native identity's machine token and
|
||||
// type on a chat too. A chat uses one the check-in already read, and never
|
||||
// runs the identity helper itself.
|
||||
test("a chat carries the device identity a check-in read, and runs no helper of its own", async () => {
|
||||
const line = (body) => `data:${JSON.stringify({ headers: {}, body: JSON.stringify(body), statusCodeValue: 200 })}\n\n`
|
||||
const chats = []
|
||||
const p = await loader(QoderAuthPlugin, (u, init) => {
|
||||
if (u.pathname.endsWith("/model/list")) return json({ chat: [{ key: "dfmodel", display_name: "DeepSeek Flash", enable: true }] })
|
||||
if (u.pathname.includes("/agent_chat_generation")) {
|
||||
chats.push(init.headers)
|
||||
return new Response(line({ choices: [{ delta: { content: "ok" } }] }) + line({ choices: [{ delta: {}, finish_reason: "stop" }] }), { headers: { "Content-Type": "text/event-stream" } })
|
||||
}
|
||||
return json(LIST)
|
||||
}, { machineId: "m1" })
|
||||
const chat = async () => {
|
||||
const res = await p.fetch("https://api3.qoder.sh/v1/chat/completions", { method: "POST", body: JSON.stringify({ model: "dfmodel", messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect(res.status).toBe(200)
|
||||
await res.text()
|
||||
}
|
||||
await chat()
|
||||
expect(reads).toHaveLength(0)
|
||||
expect(chats[0]["Cosy-MachineToken"]).toBeUndefined()
|
||||
expect(chats[0]["Cosy-ClientIp"]).toBeUndefined()
|
||||
expect((await p.fetch(CAMPAIGN_URL)).status).toBe(200)
|
||||
expect(reads).toHaveLength(1)
|
||||
await chat()
|
||||
expect(reads).toHaveLength(1)
|
||||
expect(chats[1]["Cosy-MachineToken"]).toBe("sdk-token-u1")
|
||||
expect(chats[1]["Cosy-MachineType"]).toBe(MACHINE_TYPE)
|
||||
expect(chats[1]["Cosy-MachineId"]).toBe("m1")
|
||||
expect(chats[1]["Cosy-ClientIp"]).toBeUndefined()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// The machine headers a Qoder call carries, against what Qoder's own client
|
||||
// sends (Qoder.app 0.4.3: its worker runtime and the signer it embeds).
|
||||
// unifilitence's capture (plugins#443) is the fixture: a Windows x64 chat
|
||||
// went out with the account's machine UUID as Cosy-ClientIp, -MachineId
|
||||
// and -MachineToken alike, Cosy-MachineType 5 and Cosy-MachineOS
|
||||
// x86_64_win32. Qoder's client sends that set on its other calls (its
|
||||
// prepareRequest), but a chat (prepareInferRequest) carries no ClientIp,
|
||||
// its device identity's MachineToken and MachineType or none, and the
|
||||
// machine's hostname. x86_64_win32 is Qoder's own name for the machine.
|
||||
import { test, expect } from "bun:test"
|
||||
import { createHash } from "node:crypto"
|
||||
import { hostname } from "node:os"
|
||||
import { QoderAuthPlugin, _internal } from "./index.mjs"
|
||||
|
||||
const { chatHeaders, cosyHeaders, machineOS, machineHostname } = _internal
|
||||
const MACHINE = "01a1450c-5eb1-7555-ae94-000000000000" // the capture's, redacted part made up
|
||||
const cred = { type: "oauth", uid: "u1", machineId: MACHINE, access: "a" }
|
||||
const URL_CHAT = "https://api3.qoder.sh/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1"
|
||||
const model = { key: "auto", source: "system" }
|
||||
const payloadOf = (h) => JSON.parse(Buffer.from(h.Authorization.split(".")[1], "base64").toString())
|
||||
|
||||
test("Cosy-MachineOS is Qoder's own: x86_64_win32 on Windows x64, aarch64_darwin on a Mac", () => {
|
||||
expect(machineOS("x64", "win32")).toBe("x86_64_win32")
|
||||
expect(machineOS("arm64", "darwin")).toBe("aarch64_darwin")
|
||||
expect(machineOS("x64", "linux")).toBe("x86_64_linux")
|
||||
// Qoder renames only x64 and arm64
|
||||
expect(machineOS("ia32", "win32")).toBe("ia32_win32")
|
||||
})
|
||||
|
||||
test("a chat carries no Cosy-ClientIp, and no machine token or type without a device identity", () => {
|
||||
const h = chatHeaders(URL_CHAT, cred, "body", undefined, model)
|
||||
expect(h["Cosy-ClientIp"]).toBeUndefined()
|
||||
expect(h["Cosy-MachineToken"]).toBeUndefined()
|
||||
expect(h["Cosy-MachineType"]).toBeUndefined()
|
||||
expect(h["Cosy-MachineId"]).toBe(MACHINE)
|
||||
expect(h["Cosy-MachineOS"]).toBe(machineOS())
|
||||
expect(h.Accept).toBe("text/event-stream")
|
||||
expect(h["Cache-Control"]).toBe("no-cache")
|
||||
expect(h["X-Model-Key"]).toBe("auto")
|
||||
expect(h["X-Model-Source"]).toBe("system")
|
||||
expect(h["Cosy-MachineHostname"]).toBe(machineHostname(hostname()))
|
||||
})
|
||||
|
||||
test("a chat carries the device identity's machine token and type when one is known", () => {
|
||||
const h = chatHeaders(URL_CHAT, cred, "body", undefined, model, { "Cosy-MachineToken": "sdk-token-u1", "Cosy-MachineType": "7" })
|
||||
expect(h["Cosy-MachineToken"]).toBe("sdk-token-u1")
|
||||
expect(h["Cosy-MachineType"]).toBe("7")
|
||||
expect(h["Cosy-ClientIp"]).toBeUndefined()
|
||||
})
|
||||
|
||||
test("every other call keeps Qoder's prepareRequest set: ClientIp, MachineId and MachineToken the machine id", () => {
|
||||
const h = cosyHeaders("https://api3.qoder.sh/algo/api/v2/model/list?Encode=1", cred, "", undefined)
|
||||
expect(h["Cosy-ClientIp"]).toBe(MACHINE)
|
||||
expect(h["Cosy-MachineId"]).toBe(MACHINE)
|
||||
expect(h["Cosy-MachineToken"]).toBe(MACHINE)
|
||||
expect(h["Cosy-MachineType"]).toBe("5")
|
||||
expect(h["Accept-Encoding"]).toBe("identity")
|
||||
})
|
||||
|
||||
test("the signed payload's request id is a dashed UUID and its ideVersion empty, as Qoder's signer writes them", () => {
|
||||
const p = payloadOf(cosyHeaders(URL_CHAT, cred, "body", undefined))
|
||||
expect(p.requestId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
|
||||
expect(p.ideVersion).toBe("")
|
||||
expect(p.version).toBe("v1")
|
||||
})
|
||||
|
||||
test("Cosy-MachineHostname is the hostname as Qoder's client makes it safe", () => {
|
||||
const h8 = (v) => createHash("sha256").update(v, "utf8").digest("hex").slice(0, 8)
|
||||
expect(machineHostname("DESKTOP-ABC123")).toBe("DESKTOP-ABC123")
|
||||
expect(machineHostname(" my-mac.local ")).toBe("my-mac.local")
|
||||
expect(machineHostname("")).toBe("")
|
||||
// a non-ASCII name goes as its punycode
|
||||
expect(machineHostname("büro")).toBe("xn--bro-hoa")
|
||||
expect(machineHostname("张三的电脑")).toBe("xn--ehq892buuqjgb581a")
|
||||
// one that has none is made safe and marked with its hash
|
||||
expect(machineHostname("PC 张三")).toBe(`PC-${h8("PC 张三")}`)
|
||||
// at most 96 characters
|
||||
const long = "a".repeat(120)
|
||||
expect(machineHostname(long)).toBe(`${"a".repeat(87)}-${h8(long)}`)
|
||||
})
|
||||
|
||||
test("a chat on the wire carries the chat set, not the machine UUID three times (#443)", async () => {
|
||||
const line = (body) => `data:${JSON.stringify({ headers: {}, body: JSON.stringify(body), statusCodeValue: 200 })}\n\n`
|
||||
const seen = []
|
||||
const saved = globalThis.fetch
|
||||
globalThis.fetch = async (input, init = {}) => {
|
||||
const url = String(input?.url ?? input)
|
||||
seen.push({ url, headers: Object.fromEntries(new Headers(init.headers)) })
|
||||
if (new URL(url).pathname.endsWith("/model/list")) return Response.json({ chat: [{ key: "dfmodel", display_name: "DeepSeek Flash", enable: true }] })
|
||||
return new Response(line({ choices: [{ delta: { content: "ok" } }] }) + line({ choices: [{ delta: {}, finish_reason: "stop" }] }), { headers: { "Content-Type": "text/event-stream" } })
|
||||
}
|
||||
try {
|
||||
const auth = { type: "oauth", access: "jt", refresh: "rt", expires: Date.now() + 3_600_000, accountId: "one@x", uid: "u1", machineId: MACHINE }
|
||||
const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const l = await hooks.auth.loader(async () => auth)
|
||||
const res = await l.fetch("https://api3.qoder.sh/v1/chat/completions", { method: "POST", body: JSON.stringify({ model: "dfmodel", messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect(res.status).toBe(200)
|
||||
await res.text()
|
||||
const chat = seen.find((r) => r.url.includes("/agent_chat_generation"))
|
||||
expect(chat).toBeDefined()
|
||||
expect(chat.headers["cosy-clientip"]).toBeUndefined()
|
||||
expect(chat.headers["cosy-machinetoken"]).toBeUndefined()
|
||||
expect(chat.headers["cosy-machinetype"]).toBeUndefined()
|
||||
expect(chat.headers["cosy-machineid"]).toBe(MACHINE)
|
||||
expect(chat.headers.accept).toBe("text/event-stream")
|
||||
// the listing is not a chat: it keeps the prepareRequest set
|
||||
const list = seen.find((r) => r.url.includes("/model/list"))
|
||||
expect(list.headers["cosy-clientip"]).toBe(MACHINE)
|
||||
expect(list.headers["cosy-machinetoken"]).toBe(MACHINE)
|
||||
} finally {
|
||||
globalThis.fetch = saved
|
||||
}
|
||||
})
|
||||
+72
-15
@@ -38,8 +38,9 @@ import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, con
|
||||
import { execFile } from "node:child_process"
|
||||
import { readdir, stat } from "node:fs/promises"
|
||||
import { STATUS_CODES } from "node:http"
|
||||
import { homedir } from "node:os"
|
||||
import { homedir, hostname } from "node:os"
|
||||
import { join, resolve } from "node:path"
|
||||
import { domainToASCII } from "node:url"
|
||||
|
||||
const CHAT_PATH = "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1"
|
||||
const MODELS_PATH = "/algo/api/v2/model/list?Encode=1"
|
||||
@@ -73,10 +74,33 @@ const hexID = () => randomUUID().replaceAll("-", "")
|
||||
|
||||
// ---- the COSY envelope --------------------------------------------------------
|
||||
|
||||
// machineOS names the machine as Qoder's desktop clients do.
|
||||
function machineOS() {
|
||||
const arch = { x64: "x86_64", ia32: "x86", arm64: "aarch64" }[process.arch] ?? process.arch
|
||||
return arch + "_" + process.platform
|
||||
// machineOS names the machine as Qoder's desktop client does: Node's
|
||||
// process.platform, so x86_64_win32 on Windows, aarch64_darwin on a Mac
|
||||
// (its worker runtime's COSY_MACHINE_OS, Qoder 0.4.3). Only x64 and arm64
|
||||
// are renamed; any other arch goes as Node names it.
|
||||
function machineOS(arch = process.arch, platform = process.platform) {
|
||||
return ({ x64: "x86_64", arm64: "aarch64" }[arch] ?? arch) + "_" + platform
|
||||
}
|
||||
|
||||
// machineHostname is the Cosy-MachineHostname Qoder's client puts on a chat
|
||||
// request: os.hostname(), sent as it is when it is printable ASCII, else
|
||||
// its punycode, else made safe and marked with a hash of the original, at
|
||||
// most 96 characters (its zei). "" (none is sent) for an empty name.
|
||||
const HOST_SAFE = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/u
|
||||
function machineHostname(name = hostname()) {
|
||||
const hash = (v) => createHash("sha256").update(v, "utf8").digest("hex").slice(0, 8)
|
||||
const cap = (v) => {
|
||||
if (v.length <= 96) return v
|
||||
const head = v.slice(0, 96 - 8 - 1).replace(/[-\s]+$/u, "")
|
||||
return head ? `${head}-${hash(v)}` : `unknown-${hash(v)}`
|
||||
}
|
||||
const v = String(name ?? "").trim()
|
||||
if (!v) return ""
|
||||
if (HOST_SAFE.test(v)) return cap(v)
|
||||
const ascii = domainToASCII(v)
|
||||
if (ascii && HOST_SAFE.test(ascii)) return cap(ascii)
|
||||
const safe = v.replace(/[^\x21-\x7e]+/gu, "-").replace(/-{2,}/gu, "-").replace(/^-+|-+$/gu, "")
|
||||
return cap(safe ? `${safe}-${hash(v)}` : `unknown-${hash(v)}`)
|
||||
}
|
||||
|
||||
// userBlob is the account as the envelope carries it: AES-128-CBC under a
|
||||
@@ -98,7 +122,9 @@ function cosyHeaders(url, u, body, site, ts = Math.floor(Date.now() / 1000)) {
|
||||
const cosyVersion = site?.cosyVersion ?? COSY_VERSION
|
||||
const blob = userBlob(u, site?.rsaKey)
|
||||
const payload = Buffer.from(
|
||||
JSON.stringify({ version: "v1", requestId: hexID(), info: blob.info, cosyVersion, ideVersion: "" }),
|
||||
// the request id is a dashed UUID, as Qoder's signer makes it; its
|
||||
// ideVersion is "" too
|
||||
JSON.stringify({ version: "v1", requestId: randomUUID(), info: blob.info, cosyVersion, ideVersion: "" }),
|
||||
).toString("base64")
|
||||
let path = new URL(url).pathname
|
||||
if (path.startsWith("/algo")) path = path.slice(5)
|
||||
@@ -127,6 +153,25 @@ function cosyHeaders(url, u, body, site, ts = Math.floor(Date.now() / 1000)) {
|
||||
}
|
||||
}
|
||||
|
||||
// chatHeaders are the headers of a chat (agent_chat_generation) call, as
|
||||
// Qoder's client builds them (its prepareInferRequest, then Vai): no
|
||||
// Cosy-ClientIp; Cosy-MachineToken and Cosy-MachineType are its device
|
||||
// identity's (the runtime-info the check-in reads), or left off when it has
|
||||
// none, rather than the machine id cosyHeaders puts there; and the
|
||||
// machine's hostname. Every other call keeps cosyHeaders' set, which is
|
||||
// its prepareRequest's: there ClientIp, MachineId and MachineToken are all
|
||||
// the machine id (#443).
|
||||
function chatHeaders(url, u, body, site, model, identity = {}) {
|
||||
const h = cosyHeaders(url, u, body, site)
|
||||
delete h["Cosy-ClientIp"]
|
||||
delete h["Cosy-MachineToken"]
|
||||
delete h["Cosy-MachineType"]
|
||||
for (const key of ["Cosy-MachineToken", "Cosy-MachineType"]) if (identity[key]) h[key] = identity[key]
|
||||
const host = machineHostname()
|
||||
if (host) h["Cosy-MachineHostname"] = host
|
||||
return { ...h, Accept: "text/event-stream", "Cache-Control": "no-cache", "X-Model-Key": model.key, "X-Model-Source": model.source }
|
||||
}
|
||||
|
||||
// ---- the body codec -----------------------------------------------------------
|
||||
|
||||
// Base64 through the client's shuffled alphabet ('$' pads), then the first
|
||||
@@ -2235,12 +2280,30 @@ const makePlugin = (site) => async ({ client }) => {
|
||||
campaignMachines.set(uid, entry)
|
||||
}
|
||||
try {
|
||||
return await entry.promise
|
||||
const got = await entry.promise
|
||||
if (campaignMachines.get(uid) === entry) readIdentities.set(uid, { at: entry.at, headers: got })
|
||||
return got
|
||||
} catch (e) {
|
||||
if (campaignMachines.get(uid) === entry) campaignMachines.delete(uid)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
// chatIdentity: the device identity a chat carries, as Qoder's client puts
|
||||
// its native identity on when it has one. Only one this process has
|
||||
// already read (a check-in) is used, so a chat never waits on, or is the
|
||||
// first to run, Qoder's helper; one an hour old is read again behind the
|
||||
// chat, as the desktop client renews its own hourly. {}: none yet.
|
||||
const readIdentities = new Map()
|
||||
const chatIdentity = (uid) => {
|
||||
const known = uid ? readIdentities.get(uid) : undefined
|
||||
if (!known) return {}
|
||||
const now = Date.now()
|
||||
if (now - (known.tried ?? known.at) >= CAMPAIGN_MACHINE_TTL) {
|
||||
known.tried = now
|
||||
machineForCampaign(uid).catch(() => {})
|
||||
}
|
||||
return known.headers
|
||||
}
|
||||
// campaignIdentity: the headers a campaigns request carries, and why
|
||||
// there are none where the site goes on without them (Qoder CN).
|
||||
const campaignIdentity = async (uid) => {
|
||||
@@ -2581,13 +2644,7 @@ const makePlugin = (site) => async ({ client }) => {
|
||||
ask.requestId = body.request_id
|
||||
}
|
||||
const wire = encodeBody(JSON.stringify(body))
|
||||
const headers = {
|
||||
...cosyHeaders(CHAT_URL, cred, wire, siteOf(site, cred)),
|
||||
Accept: "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Model-Key": m.key,
|
||||
"X-Model-Source": m.source,
|
||||
}
|
||||
const headers = chatHeaders(CHAT_URL, cred, wire, siteOf(site, cred), m, chatIdentity(cred.uid))
|
||||
// a refused call's stream is closed: Qoder keeps a 10605 stream open
|
||||
// after its one event, and a connection held open while the call is
|
||||
// waited out and sent again is one more the account holds
|
||||
@@ -2856,4 +2913,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
|
||||
export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
|
||||
|
||||
// for tests
|
||||
export const _internal = { typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
|
||||
export const _internal = { chatHeaders, machineOS, machineHostname, cosyHeaders, typedUnions, Splitter, campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, namedSession, taskOf, TASKS, TASK_MAX, TASK_IDLE, SESSION, SITES, decodeBody, events, QUEUE, queueState }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-qoder-auth",
|
||||
"version": "0.2.40",
|
||||
"version": "0.2.41",
|
||||
"description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user