qoder: include native device identity in international campaigns (#49)
This commit is contained in:
@@ -186,12 +186,30 @@ The hosts and reply shapes come from a real VPC account's report
|
||||
|
||||
Qoder gives credits for a daily claim (the Qoder client's campaign
|
||||
`CLAIM_BENEFIT`, 100 Credits a day as reported), on both sites. magpie can
|
||||
press it once a day for each account when its Qoder check-in switch is on
|
||||
claim it for each account when its Qoder check-in switch is on
|
||||
(Settings). It asks these pages through this plugin's fetch (since 0.2.7),
|
||||
which sends them as the account, on the device token (`Bearer`,
|
||||
`Cosy-ClientType: 10`) as usage is read; a refused device token is
|
||||
rotated once and the page asked again.
|
||||
|
||||
International campaigns also need Qoder's native device identity:
|
||||
`Cosy-MachineToken` and `Cosy-MachineType`. Without them, the server can
|
||||
return HTTP 200 but omit the daily claim. The plugin reads them from
|
||||
Qoder's own `runtime-info` helper for the signed-in uid, sharing an
|
||||
in-flight read and caching it in memory for an hour. The same identity
|
||||
goes on the list, the claim and a device-token retry; it is not saved in
|
||||
the account's credentials.
|
||||
|
||||
- Install Qoder desktop or run Qoder CLI to make its native runtime
|
||||
available. The plugin finds the desktop's standard Windows/macOS
|
||||
location or the CLI's matching `~/.qoder/.bin/umid-*` cache.
|
||||
- For another installation location, set `QODER_RUNTIME_INFO` to the
|
||||
absolute path of Qoder's installed `runtime-info` executable
|
||||
(`runtime-info.exe` on Windows), with its accompanying SDK files.
|
||||
- A missing helper or invalid identity is an error, rather than a false
|
||||
"no activity" result. Qoder CN keeps its existing requests and does
|
||||
not need this local helper.
|
||||
|
||||
- **List:** `GET <openapi>/sash/api/v1/me/campaigns`: `campaigns[]` with
|
||||
`campaignId`, `actionType`, `claimStatus` (`CLAIMABLE`, `CLAIMED`),
|
||||
`startAt`, `endAt`, `benefit.amount`.
|
||||
@@ -201,7 +219,11 @@ rotated once and the page asked again.
|
||||
(Qoder CN). Other pages on those hosts are still refused.
|
||||
|
||||
Taken from [wallechfox/qoder-checkin](https://github.com/wallechfox/qoder-checkin),
|
||||
which a user reports works. Not yet tried here with a real Qoder account.
|
||||
which a user reports works, and Qoder desktop 0.4.3's campaign requests.
|
||||
International campaign discovery was checked with a real account on
|
||||
2026-10-08: the native identity exposed the claimable 100 credits, and
|
||||
omitting either header hid them. This verification only queried the
|
||||
activity; a live claim was not performed.
|
||||
|
||||
## Not here
|
||||
|
||||
|
||||
@@ -1,17 +1,55 @@
|
||||
// The account's fetch sends Qoder's campaigns pages (the daily check-in) as
|
||||
// the account, on the device token, for both sites; anything else on those
|
||||
// hosts is still refused as not a chat.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { afterEach, beforeEach, expect, setSystemTime, spyOn, test } from "bun:test"
|
||||
import * as childProcess from "node:child_process"
|
||||
import * as fsPromises from "node:fs/promises"
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, utimesSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { dirname, join, sep } from "node:path"
|
||||
import { QoderAuthPlugin, QoderCNAuthPlugin, _internal } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
const originalRuntime = process.env.QODER_RUNTIME_INFO
|
||||
const realStat = fsPromises.stat
|
||||
let sandbox, native, reads, nativeError, nativeOutput
|
||||
const MACHINE_TYPE = "cfe111111111111111"
|
||||
beforeEach(() => {
|
||||
sandbox = mkdtempSync(join(tmpdir(), "qoder-checkin-"))
|
||||
const file = join(sandbox, process.platform === "win32" ? "runtime-info.exe" : "runtime-info")
|
||||
writeFileSync(file, "fixture")
|
||||
process.env.QODER_RUNTIME_INFO = file
|
||||
reads = []
|
||||
nativeError = null
|
||||
nativeOutput = (uid) => JSON.stringify({ machineToken: "sdk-token-" + uid, machineType: MACHINE_TYPE, machineCode: "fixture-code" })
|
||||
native = spyOn(childProcess, "execFile").mockImplementation((file, args, options, done) => ({
|
||||
stdin: {
|
||||
on() {},
|
||||
end(text) {
|
||||
const input = text ? JSON.parse(text) : {}
|
||||
reads.push({ file, args, options, input })
|
||||
queueMicrotask(() => done(nativeError, nativeOutput(input.account ?? "u1")))
|
||||
},
|
||||
},
|
||||
}))
|
||||
})
|
||||
afterEach(() => {
|
||||
globalThis.fetch = real
|
||||
native.mockRestore()
|
||||
setSystemTime()
|
||||
if (originalRuntime === undefined) delete process.env.QODER_RUNTIME_INFO
|
||||
else process.env.QODER_RUNTIME_INFO = originalRuntime
|
||||
// Only remove the directory this test made under the system's temp root.
|
||||
const target = realpathSync(sandbox)
|
||||
if (!target.startsWith(realpathSync(tmpdir()) + sep)) throw new Error("test directory escaped temp root")
|
||||
rmSync(target, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const account = () => ({
|
||||
type: "oauth",
|
||||
access: "jt-one",
|
||||
refresh: "rt-one",
|
||||
expires: Date.now() + 3_600_000,
|
||||
expires: Date.now() + 86_400_000,
|
||||
accountId: "one@x",
|
||||
uid: "u1",
|
||||
deviceToken: "dt-old",
|
||||
@@ -35,6 +73,123 @@ async function loader(make, serve) {
|
||||
}
|
||||
|
||||
const LIST = { campaigns: [{ campaignId: "c1", actionType: "CLAIM_BENEFIT", claimStatus: "CLAIMABLE", benefit: { amount: 100 } }] }
|
||||
const CAMPAIGN_URL = "https://openapi.qoder.sh/sash/api/v1/me/campaigns"
|
||||
|
||||
test("international campaigns expose the daily 100 credits using the native device identity", async () => {
|
||||
const p = await loader(QoderAuthPlugin, (u, init) => {
|
||||
const identified = init.headers["Cosy-MachineToken"] === "sdk-token-u1" && init.headers["Cosy-MachineType"] === MACHINE_TYPE
|
||||
if (u.pathname.endsWith("/claim")) return json({ status: identified ? "CLAIMED" : "INELIGIBLE" })
|
||||
return json(identified ? LIST : { campaigns: [{ campaignId: "details", actionType: "VIEW_DETAILS", claimStatus: "CLAIMED" }] })
|
||||
})
|
||||
const list = await p.fetch(CAMPAIGN_URL, { method: "GET" })
|
||||
expect(await list.json()).toEqual(LIST)
|
||||
const claim = await p.fetch(CAMPAIGN_URL + "/c1/claim", { method: "POST", body: "{}" })
|
||||
expect((await claim.json()).status).toBe("CLAIMED")
|
||||
expect(reads).toHaveLength(1)
|
||||
expect(reads[0].args).toEqual(process.platform === "linux" ? ["3"] : ["3", "--account-stdin"])
|
||||
if (process.platform !== "linux") expect(reads[0].input).toEqual({ account: "u1" })
|
||||
})
|
||||
|
||||
test("parallel requests share the native identity and refresh it after an hour", async () => {
|
||||
setSystemTime(new Date("2026-10-08T06:00:00Z"))
|
||||
const p = await loader(QoderAuthPlugin, () => json(LIST))
|
||||
await Promise.all([p.fetch(CAMPAIGN_URL), p.fetch(CAMPAIGN_URL)])
|
||||
expect(reads).toHaveLength(1)
|
||||
setSystemTime(new Date("2026-10-08T07:00:00Z"))
|
||||
await p.fetch(CAMPAIGN_URL)
|
||||
expect(reads).toHaveLength(2)
|
||||
})
|
||||
|
||||
test("two accounts get separate native identities", async () => {
|
||||
const p = await loader(QoderAuthPlugin, () => json(LIST))
|
||||
await p.fetch(CAMPAIGN_URL)
|
||||
p.auth().uid = "u2"
|
||||
await p.fetch(CAMPAIGN_URL)
|
||||
expect(reads).toHaveLength(2)
|
||||
if (process.platform !== "linux") expect(reads.map((r) => r.input.account)).toEqual(["u1", "u2"])
|
||||
})
|
||||
|
||||
test("a missing native runtime fails before querying campaigns", async () => {
|
||||
process.env.QODER_RUNTIME_INFO = join(sandbox, "not-installed")
|
||||
native.mockImplementation((file, args, options, done) => {
|
||||
queueMicrotask(() => done(new Error("ENOENT")))
|
||||
return { stdin: { on() {}, end() {} } }
|
||||
})
|
||||
const p = await loader(QoderAuthPlugin, () => json(LIST))
|
||||
const response = await p.fetch(CAMPAIGN_URL)
|
||||
expect(response.status).toBe(502)
|
||||
expect(await response.text()).toContain("device identity")
|
||||
expect(p.seen).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("Windows finds the Qoder desktop's installed runtime", async () => {
|
||||
const file = join(sandbox, "Programs", "Qoder", "resources", "umid", "runtime-info.exe")
|
||||
mkdirSync(dirname(file), { recursive: true })
|
||||
writeFileSync(file, "fixture")
|
||||
expect(await _internal.campaignRuntime({ home: sandbox, platform: "win32", arch: "x64", env: { LOCALAPPDATA: sandbox } })).toBe(file)
|
||||
})
|
||||
|
||||
for (const [platform, arch] of [["win32", "x64"], ["darwin", "arm64"], ["linux", "x64"]]) {
|
||||
test(`${platform}/${arch}: finds the newest matching CLI runtime`, async () => {
|
||||
const cache = join(sandbox, ".qoder", ".bin")
|
||||
const name = platform === "win32" ? "runtime-info.exe" : "runtime-info"
|
||||
const old = join(cache, `umid-${platform}-${arch}-ffff`)
|
||||
const newest = join(cache, `umid-${platform}-${arch}-aaaa`)
|
||||
const other = join(cache, `umid-${platform}-other-ffff`)
|
||||
for (const dir of [old, newest, other]) {
|
||||
mkdirSync(dir, { recursive: true })
|
||||
writeFileSync(join(dir, name), "fixture")
|
||||
}
|
||||
utimesSync(old, new Date(1000), new Date(1000))
|
||||
utimesSync(newest, new Date(2000), new Date(2000))
|
||||
// Keep desktop discovery inside this fixture, even on a Mac with Qoder installed.
|
||||
const inspect = spyOn(fsPromises, "stat").mockImplementation((path, ...args) => {
|
||||
if (!String(path).startsWith(sandbox + sep)) return Promise.reject(new Error("outside fixture"))
|
||||
return realStat(path, ...args)
|
||||
})
|
||||
try {
|
||||
expect(await _internal.campaignRuntime({ home: sandbox, platform, arch, env: {} })).toBe(join(newest, name))
|
||||
} finally {
|
||||
inspect.mockRestore()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
test("unavailable native identity fails the request and can be retried", async () => {
|
||||
nativeError = new Error("fixture helper unavailable")
|
||||
const p = await loader(QoderAuthPlugin, () => json(LIST))
|
||||
const failed = await p.fetch(CAMPAIGN_URL)
|
||||
expect(failed.status).toBe(502)
|
||||
expect(await failed.text()).toContain("device identity")
|
||||
expect(p.seen).toHaveLength(0)
|
||||
nativeError = null
|
||||
expect((await p.fetch(CAMPAIGN_URL)).status).toBe(200)
|
||||
expect(reads).toHaveLength(2)
|
||||
})
|
||||
|
||||
for (const identity of [{}, { machineToken: "", machineType: MACHINE_TYPE }, { machineToken: "token", machineType: "" }, { machineToken: "token\ninvalid", machineType: MACHINE_TYPE }, null]) {
|
||||
test(`invalid native identity is an error before querying campaigns: ${JSON.stringify(identity)}`, async () => {
|
||||
nativeOutput = () => JSON.stringify(identity)
|
||||
const p = await loader(QoderAuthPlugin, () => json(LIST))
|
||||
const response = await p.fetch(CAMPAIGN_URL)
|
||||
expect(response.status).toBe(502)
|
||||
expect(await response.text()).toContain("device identity")
|
||||
expect(p.seen).toHaveLength(0)
|
||||
})
|
||||
}
|
||||
|
||||
test("CN still queries and claims without a native identity runtime", async () => {
|
||||
process.env.QODER_RUNTIME_INFO = join(sandbox, "not-installed")
|
||||
const p = await loader(QoderCNAuthPlugin, (u, init) => {
|
||||
expect(init.headers["Cosy-MachineToken"]).toBeUndefined()
|
||||
expect(init.headers["Cosy-MachineType"]).toBeUndefined()
|
||||
return json(u.pathname.endsWith("/claim") ? { status: "CLAIMED" } : LIST)
|
||||
})
|
||||
const url = "https://openapi.qoder.com.cn/sash/api/v1/me/campaigns"
|
||||
expect(await (await p.fetch(url)).json()).toEqual(LIST)
|
||||
expect((await (await p.fetch(url + "/c1/claim", { method: "POST", body: "{}" })).json()).status).toBe("CLAIMED")
|
||||
expect(reads).toHaveLength(0)
|
||||
})
|
||||
|
||||
for (const [make, origin] of [
|
||||
[QoderAuthPlugin, "https://openapi.qoder.sh"],
|
||||
@@ -63,7 +218,8 @@ test("a refused device token is rotated, saved, and the claim asked again", asyn
|
||||
const p = await loader(QoderAuthPlugin, (u, init) => {
|
||||
if (u.pathname === "/api/v1/deviceToken/refresh") return json({ device_token: "dt-new", refresh_token: "drt-new" })
|
||||
if (u.pathname === "/sash/api/v1/me/campaigns/c1/claim")
|
||||
return init.headers.Authorization === "Bearer dt-new" ? json({ status: "CLAIMED" }) : new Response("", { status: 401 })
|
||||
return init.headers.Authorization === "Bearer dt-new" && init.headers["Cosy-MachineToken"] === "sdk-token-u1" && init.headers["Cosy-MachineType"] === MACHINE_TYPE
|
||||
? json({ status: "CLAIMED" }) : new Response("", { status: 401 })
|
||||
return new Response("", { status: 404 })
|
||||
})
|
||||
const res = await p.fetch("https://openapi.qoder.sh/sash/api/v1/me/campaigns/c1/claim", { method: "POST", body: "{}" })
|
||||
|
||||
@@ -35,7 +35,11 @@
|
||||
// <instance>-gateway.vpc.qoder.com.cn. The instance is kept on the account,
|
||||
// and an account with none is served as before.
|
||||
import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID, constants } from "node:crypto"
|
||||
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 { join, resolve } from "node:path"
|
||||
|
||||
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"
|
||||
@@ -1028,6 +1032,59 @@ async function fetchUsage(site, deviceToken) {
|
||||
// credits among them (actionType CLAIM_BENEFIT) — and claims one
|
||||
// (POST …/{id}/claim), as Qoder's client does, on the device token.
|
||||
const CAMPAIGNS = "/sash/api/v1/me/campaigns"
|
||||
const CAMPAIGN_MACHINE_TTL = 60 * 60 * 1000 // Qoder's desktop client renews its native identity hourly
|
||||
|
||||
// campaignRuntime uses Qoder's own native device identity helper, installed
|
||||
// by its desktop client or cached by its CLI. A made-up token (including the
|
||||
// chat envelope's machine id and type 5) doesn't reveal international claims.
|
||||
async function campaignRuntime({ home = homedir(), platform = process.platform, arch = process.arch, env = process.env } = {}) {
|
||||
if (env.QODER_RUNTIME_INFO) return resolve(env.QODER_RUNTIME_INFO)
|
||||
const name = platform === "win32" ? "runtime-info.exe" : "runtime-info"
|
||||
const paths = []
|
||||
if (platform === "win32") {
|
||||
const local = env.LOCALAPPDATA || join(home, "AppData", "Local")
|
||||
paths.push(join(local, "Programs", "Qoder", "resources", "umid", name))
|
||||
} else if (platform === "darwin") {
|
||||
for (const dir of ["/Applications", join(home, "Applications")]) paths.push(join(dir, "Qoder.app", "Contents", "Resources", "umid", name))
|
||||
}
|
||||
for (const path of paths) if ((await stat(path).catch(() => null))?.isFile()) return path
|
||||
const cache = join(home, ".qoder", ".bin")
|
||||
const dirs = (await readdir(cache, { withFileTypes: true }).catch(() => []))
|
||||
.filter((d) => d.isDirectory() && d.name.startsWith(`umid-${platform}-${arch}-`))
|
||||
const cached = await Promise.all(dirs.map(async (d) => ({ path: join(cache, d.name, name), time: (await stat(join(cache, d.name))).mtimeMs })))
|
||||
for (const { path } of cached.sort((a, b) => b.time - a.time)) if ((await stat(path).catch(() => null))?.isFile()) return path
|
||||
throw new Error("Qoder check-in: device identity runtime not found; install Qoder desktop or run Qoder CLI, or set QODER_RUNTIME_INFO to its runtime-info executable")
|
||||
}
|
||||
|
||||
// Read the SDK identity as Qoder does: environment 3 is international; on
|
||||
// Windows and macOS the uid goes over stdin, never into the command line.
|
||||
async function campaignMachine(uid) {
|
||||
if (!uid) throw new Error("Qoder check-in: device identity needs the account uid; sign in again")
|
||||
const file = await campaignRuntime()
|
||||
const args = process.platform === "linux" ? ["3"] : ["3", "--account-stdin"]
|
||||
const text = await new Promise((resolve, reject) => {
|
||||
const child = execFile(file, args, { timeout: 20_000, windowsHide: true, maxBuffer: 1 << 20 }, (err, out) => {
|
||||
if (err) reject(err)
|
||||
else resolve(out)
|
||||
})
|
||||
child.stdin?.on("error", () => {})
|
||||
child.stdin?.end(process.platform === "linux" ? undefined : JSON.stringify({ account: uid }) + "\n")
|
||||
}).catch(() => {
|
||||
throw new Error("Qoder check-in: could not read device identity; restart or update Qoder, or check QODER_RUNTIME_INFO")
|
||||
})
|
||||
try {
|
||||
const identity = JSON.parse(text.trim().split(/\r?\n/, 1)[0])
|
||||
const headers = {}
|
||||
for (const [key, field] of [["Cosy-MachineToken", "machineToken"], ["Cosy-MachineType", "machineType"]]) {
|
||||
const value = identity?.[field]?.trim()
|
||||
if (!value || value.length > 4096 || !/^[\x20-\x7e]+$/.test(value)) throw new Error("invalid identity")
|
||||
headers[key] = value
|
||||
}
|
||||
return headers
|
||||
} catch {
|
||||
throw new Error("Qoder check-in: invalid device identity from Qoder; restart or update Qoder")
|
||||
}
|
||||
}
|
||||
|
||||
// campaignPage: url is the site's campaigns page or a claim under it, which
|
||||
// the account's fetch sends as the account rather than as a chat.
|
||||
@@ -1057,10 +1114,10 @@ function campaignTarget(base, s, url) {
|
||||
|
||||
// campaignCall is url asked with the device token; Qoder's answer comes back
|
||||
// as it is.
|
||||
async function campaignCall(url, method, body, deviceToken, signal) {
|
||||
async function campaignCall(url, method, body, deviceToken, machine, signal) {
|
||||
return fetch(url, {
|
||||
method,
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${deviceToken}`, "Cosy-ClientType": "10", "User-Agent": "Qoder" },
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${deviceToken}`, "Cosy-ClientType": "10", "User-Agent": "Qoder", ...machine },
|
||||
body: method === "GET" ? undefined : body || "{}",
|
||||
signal: signal ?? AbortSignal.timeout(20_000),
|
||||
})
|
||||
@@ -1175,6 +1232,23 @@ const SITES = {
|
||||
|
||||
const makePlugin = (site) => async ({ client }) => {
|
||||
const ID = site.id
|
||||
// The SDK identity is account-specific. Share an in-flight read, refresh
|
||||
// after an hour, and leave a failed read available for the next attempt.
|
||||
const campaignMachines = new Map()
|
||||
const machineForCampaign = async (uid) => {
|
||||
const now = Date.now()
|
||||
let entry = campaignMachines.get(uid)
|
||||
if (!entry || now - entry.at >= CAMPAIGN_MACHINE_TTL) {
|
||||
entry = { at: now, promise: campaignMachine(uid) }
|
||||
campaignMachines.set(uid, entry)
|
||||
}
|
||||
try {
|
||||
return await entry.promise
|
||||
} catch (e) {
|
||||
if (campaignMachines.get(uid) === entry) campaignMachines.delete(uid)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
// serializes checking, rotating and saving tokens: a refresh token is
|
||||
// spent once, so two refreshes would spend it twice
|
||||
let lock = Promise.resolve()
|
||||
@@ -1305,8 +1379,9 @@ const makePlugin = (site) => async ({ client }) => {
|
||||
if (!url) return errorResponse({ status: 404, message: "only chat completions are served" })
|
||||
const method = String(init.method ?? input?.method ?? "GET").toUpperCase()
|
||||
try {
|
||||
let res = await campaignCall(url, method, body, cred.deviceToken, init.signal)
|
||||
if (res.status === 401 || res.status === 403) res = await campaignCall(url, method, body, await deviceToken(getAuth, cred.deviceToken), init.signal)
|
||||
const machine = site.id === "qoder" ? await machineForCampaign(cred.uid) : {}
|
||||
let res = await campaignCall(url, method, body, cred.deviceToken, machine, init.signal)
|
||||
if (res.status === 401 || res.status === 403) res = await campaignCall(url, method, body, await deviceToken(getAuth, cred.deviceToken), machine, init.signal)
|
||||
return signed(res, renewed(cred))
|
||||
} catch (e) {
|
||||
if (e?.expired) return signedInError(e)
|
||||
@@ -1482,4 +1557,4 @@ export const QoderAuthPlugin = makePlugin(SITES.qoder)
|
||||
export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"])
|
||||
|
||||
// for tests
|
||||
export const _internal = { campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, SITES, decodeBody, events }
|
||||
export const _internal = { campaignRuntime, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, SITES, decodeBody, events }
|
||||
|
||||
Reference in New Issue
Block a user