@magpie-community/opencode-qoder-auth 0.2.40 → 0.2.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.mjs +72 -15
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -38,8 +38,9 @@ import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, con
38
38
  import { execFile } from "node:child_process"
39
39
  import { readdir, stat } from "node:fs/promises"
40
40
  import { STATUS_CODES } from "node:http"
41
- import { homedir } from "node:os"
41
+ import { homedir, hostname } from "node:os"
42
42
  import { join, resolve } from "node:path"
43
+ import { domainToASCII } from "node:url"
43
44
 
44
45
  const CHAT_PATH = "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1"
45
46
  const MODELS_PATH = "/algo/api/v2/model/list?Encode=1"
@@ -73,10 +74,33 @@ const hexID = () => randomUUID().replaceAll("-", "")
73
74
 
74
75
  // ---- the COSY envelope --------------------------------------------------------
75
76
 
76
- // machineOS names the machine as Qoder's desktop clients do.
77
- function machineOS() {
78
- const arch = { x64: "x86_64", ia32: "x86", arm64: "aarch64" }[process.arch] ?? process.arch
79
- return arch + "_" + process.platform
77
+ // machineOS names the machine as Qoder's desktop client does: Node's
78
+ // process.platform, so x86_64_win32 on Windows, aarch64_darwin on a Mac
79
+ // (its worker runtime's COSY_MACHINE_OS, Qoder 0.4.3). Only x64 and arm64
80
+ // are renamed; any other arch goes as Node names it.
81
+ function machineOS(arch = process.arch, platform = process.platform) {
82
+ return ({ x64: "x86_64", arm64: "aarch64" }[arch] ?? arch) + "_" + platform
83
+ }
84
+
85
+ // machineHostname is the Cosy-MachineHostname Qoder's client puts on a chat
86
+ // request: os.hostname(), sent as it is when it is printable ASCII, else
87
+ // its punycode, else made safe and marked with a hash of the original, at
88
+ // most 96 characters (its zei). "" (none is sent) for an empty name.
89
+ const HOST_SAFE = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/u
90
+ function machineHostname(name = hostname()) {
91
+ const hash = (v) => createHash("sha256").update(v, "utf8").digest("hex").slice(0, 8)
92
+ const cap = (v) => {
93
+ if (v.length <= 96) return v
94
+ const head = v.slice(0, 96 - 8 - 1).replace(/[-\s]+$/u, "")
95
+ return head ? `${head}-${hash(v)}` : `unknown-${hash(v)}`
96
+ }
97
+ const v = String(name ?? "").trim()
98
+ if (!v) return ""
99
+ if (HOST_SAFE.test(v)) return cap(v)
100
+ const ascii = domainToASCII(v)
101
+ if (ascii && HOST_SAFE.test(ascii)) return cap(ascii)
102
+ const safe = v.replace(/[^\x21-\x7e]+/gu, "-").replace(/-{2,}/gu, "-").replace(/^-+|-+$/gu, "")
103
+ return cap(safe ? `${safe}-${hash(v)}` : `unknown-${hash(v)}`)
80
104
  }
81
105
 
82
106
  // 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)) {
98
122
  const cosyVersion = site?.cosyVersion ?? COSY_VERSION
99
123
  const blob = userBlob(u, site?.rsaKey)
100
124
  const payload = Buffer.from(
101
- JSON.stringify({ version: "v1", requestId: hexID(), info: blob.info, cosyVersion, ideVersion: "" }),
125
+ // the request id is a dashed UUID, as Qoder's signer makes it; its
126
+ // ideVersion is "" too
127
+ JSON.stringify({ version: "v1", requestId: randomUUID(), info: blob.info, cosyVersion, ideVersion: "" }),
102
128
  ).toString("base64")
103
129
  let path = new URL(url).pathname
104
130
  if (path.startsWith("/algo")) path = path.slice(5)
@@ -127,6 +153,25 @@ function cosyHeaders(url, u, body, site, ts = Math.floor(Date.now() / 1000)) {
127
153
  }
128
154
  }
129
155
 
156
+ // chatHeaders are the headers of a chat (agent_chat_generation) call, as
157
+ // Qoder's client builds them (its prepareInferRequest, then Vai): no
158
+ // Cosy-ClientIp; Cosy-MachineToken and Cosy-MachineType are its device
159
+ // identity's (the runtime-info the check-in reads), or left off when it has
160
+ // none, rather than the machine id cosyHeaders puts there; and the
161
+ // machine's hostname. Every other call keeps cosyHeaders' set, which is
162
+ // its prepareRequest's: there ClientIp, MachineId and MachineToken are all
163
+ // the machine id (#443).
164
+ function chatHeaders(url, u, body, site, model, identity = {}) {
165
+ const h = cosyHeaders(url, u, body, site)
166
+ delete h["Cosy-ClientIp"]
167
+ delete h["Cosy-MachineToken"]
168
+ delete h["Cosy-MachineType"]
169
+ for (const key of ["Cosy-MachineToken", "Cosy-MachineType"]) if (identity[key]) h[key] = identity[key]
170
+ const host = machineHostname()
171
+ if (host) h["Cosy-MachineHostname"] = host
172
+ return { ...h, Accept: "text/event-stream", "Cache-Control": "no-cache", "X-Model-Key": model.key, "X-Model-Source": model.source }
173
+ }
174
+
130
175
  // ---- the body codec -----------------------------------------------------------
131
176
 
132
177
  // Base64 through the client's shuffled alphabet ('$' pads), then the first
@@ -2235,12 +2280,30 @@ const makePlugin = (site) => async ({ client }) => {
2235
2280
  campaignMachines.set(uid, entry)
2236
2281
  }
2237
2282
  try {
2238
- return await entry.promise
2283
+ const got = await entry.promise
2284
+ if (campaignMachines.get(uid) === entry) readIdentities.set(uid, { at: entry.at, headers: got })
2285
+ return got
2239
2286
  } catch (e) {
2240
2287
  if (campaignMachines.get(uid) === entry) campaignMachines.delete(uid)
2241
2288
  throw e
2242
2289
  }
2243
2290
  }
2291
+ // chatIdentity: the device identity a chat carries, as Qoder's client puts
2292
+ // its native identity on when it has one. Only one this process has
2293
+ // already read (a check-in) is used, so a chat never waits on, or is the
2294
+ // first to run, Qoder's helper; one an hour old is read again behind the
2295
+ // chat, as the desktop client renews its own hourly. {}: none yet.
2296
+ const readIdentities = new Map()
2297
+ const chatIdentity = (uid) => {
2298
+ const known = uid ? readIdentities.get(uid) : undefined
2299
+ if (!known) return {}
2300
+ const now = Date.now()
2301
+ if (now - (known.tried ?? known.at) >= CAMPAIGN_MACHINE_TTL) {
2302
+ known.tried = now
2303
+ machineForCampaign(uid).catch(() => {})
2304
+ }
2305
+ return known.headers
2306
+ }
2244
2307
  // campaignIdentity: the headers a campaigns request carries, and why
2245
2308
  // there are none where the site goes on without them (Qoder CN).
2246
2309
  const campaignIdentity = async (uid) => {
@@ -2581,13 +2644,7 @@ const makePlugin = (site) => async ({ client }) => {
2581
2644
  ask.requestId = body.request_id
2582
2645
  }
2583
2646
  const wire = encodeBody(JSON.stringify(body))
2584
- const headers = {
2585
- ...cosyHeaders(CHAT_URL, cred, wire, siteOf(site, cred)),
2586
- Accept: "text/event-stream",
2587
- "Cache-Control": "no-cache",
2588
- "X-Model-Key": m.key,
2589
- "X-Model-Source": m.source,
2590
- }
2647
+ const headers = chatHeaders(CHAT_URL, cred, wire, siteOf(site, cred), m, chatIdentity(cred.uid))
2591
2648
  // a refused call's stream is closed: Qoder keeps a 10605 stream open
2592
2649
  // after its one event, and a connection held open while the call is
2593
2650
  // waited out and sent again is one more the account holds
@@ -2856,4 +2913,4 @@ export async function QwenWorkEnterpriseAuthPlugin({ client }) {
2856
2913
  export const protocol = { makePlugin, deviceSignIn, openapi, siteOf }
2857
2914
 
2858
2915
  // for tests
2859
- 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 }
2916
+ 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 }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-qoder-auth",
3
- "version": "0.2.40",
3
+ "version": "0.2.41",
4
4
  "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",