qoder 0.2.30: Qoder CN's check-in sends Qoder CN's own device identity, as its desktop and CLI do (yetone/magpie#2911, #304)

witt-bit (yetone/magpie#2911, 10-22): after Qoder CN's update moved its
daily 100 Credits into the desktop's 权益中心, magpie's Qoder CN check-in
stopped working; Andrew0767 (#304) sees the same with Qoder desktop
installed. The plugin sent Qoder CN's campaigns pages no device identity
at all ("Qoder CN does not need this local helper").

What Qoder CN's clients do, read from their own packages:
- Qoder CN desktop 0.4.9 (the .deb's out/main): its requests carry
  Cosy-ClientType 10 and, through createAuthorizedHeaders, the identity
  from <resources>/umid/runtime-info run with environment
  `regionCode === "global" ? 3 : 0`, i.e. 0 for Qoder CN, the uid on
  stdin (--account-stdin) on macOS and Windows. Campaigns are found
  through GET /sash/api/v1/me/notifications (hasClaimableCampaign,
  campaignPopupUrl). When the identity can't be read it sends the
  request without it (resolveMachineIdentity's catch returns null).
- qoderclicn (@qodercn-ai/qoderclicn 1.1.64, 1.1.70, 1.1.73):
  campaigns.list is GET /sash/api/v1/me/campaigns, needing the UMID from
  1.1.64 and requireMachineIdentity() from 1.1.70, UMID environment
  ONLINE = 0; its config dir is QODERCN_CONFIG_DIR, else QODERCN_CLI_HOME
  (or home) + QODERCN_CONFIG_DIR_NAME (or .qoder-cn), and it caches the
  helper in <config>/.bin/runtime-info-<platform>-<arch>-<hash>.
- Install places: Qoder CN.app/Contents/Resources/umid/runtime-info
  (seen inside Qoder-CN-Installer-mac-arm64.zip's payload, 0.4.9),
  /opt/Qoder-CN/resources/umid/runtime-info (the .deb), and on Windows
  umid/runtime-info.exe among Qoder-CN-win-x64-user.exe's owned files,
  with "Uninstall Qoder CN.exe" (electron-builder's
  %LOCALAPPDATA%\Programs\<productName>; the folder itself not seen).

The plugin now keeps a runtime per site (RUNTIMES): Qoder CN reads its own
helper (those paths, its CLI's folders, QODERCN_RUNTIME_INFO, never the
international Qoder's) with environment 0, and sends Cosy-MachineToken and
Cosy-MachineType on the list, the claim and the campaigns proxy. As the
desktop does, a Qoder CN request without a readable identity still goes
out, so an account that was claiming without Qoder CN installed (0.2.21's
live PAT claim) keeps doing so. When such a list offers no daily claim,
the check-in is ineligible for the day, saying to install Qoder CN desktop
or sign in to its CLI (no helper), or failed and asked again (a helper that
didn't answer), instead of "inactive". International Qoder is unchanged.

Run: in packages/qoder, TMPDIR=$H HOME=$H/home bun test: 195 pass, 0 fail.
On the old index.mjs the new tests are 9 red (checkin.test.mjs 5 lookup
tests and the env-0 proxy test, native-checkin.test.mjs the env-0 claim,
the ineligible and the failed cases). Repo root at this commit
(rebased on 26e3e5f): 2151 pass, 1 skip, 0 fail; bun scripts/check.mjs ok.

Not tried: a real Qoder CN account (none available) or a real Qoder CN
install, so whether Qoder CN now hides the daily claim from a request
without the identity is inferred from its clients, not seen on the wire;
the Windows install folder is electron-builder's default, not seen; the
desktop's own claim happens in a remote page (campaignPopupUrl) whose
calls weren't seen, so the list/claim pages stay those of 0.2.21;
Cosy-MachineCode, which both Qoder CN clients send, is not sent.
Version 0.2.29 is open PR #319's (QwenWork).
This commit is contained in:
yetone
2026-10-23 00:29:25 +08:00
parent 26e3e5f91a
commit 929a8b3adf
5 changed files with 223 additions and 32 deletions
+22 -2
View File
@@ -285,8 +285,28 @@ the account's credentials.
international account gets no daily claim until Qoder is installed.
- A helper that is there but can't be read, or gives an invalid identity,
is `failed` and asked again later, rather than a false "no activity"
result. Qoder CN keeps its existing requests and does not need this
local helper.
result.
Qoder CN (since 0.2.30) sends its own device identity the same way when
Qoder CN is installed: its desktop 0.4.9 and CLI (`qoderclicn`) both ask
Qoder CN's `runtime-info` for environment `0` (the international one is
`3`) and send it on the campaigns pages (yetone/magpie#2911, #304).
- The plugin finds Qoder CN desktop's `resources/umid` (`Qoder CN.app` on
macOS, `%LOCALAPPDATA%\Programs\Qoder CN` or `%ProgramFiles%\Qoder CN`
on Windows, `/opt/Qoder-CN` on Linux) or the runtime its CLI caches in
`~/.qoder-cn/.bin` (`QODERCN_CONFIG_DIR`, `QODERCN_CLI_HOME` and
`QODERCN_CONFIG_DIR_NAME` move it). `QODERCN_RUNTIME_INFO` names
another location; `QODER_RUNTIME_INFO` is only the international one's.
- Without it the requests go out as before, as Qoder CN's desktop does
when it can't read the identity, and a claim the list still offers is
made. When the list then offers no daily claim, the check-in is
`ineligible` for the day with a message to install Qoder CN desktop (or
sign in to its CLI); a helper that is there but can't be read makes it
`failed`, asked again later.
- Not tried with a real Qoder CN account: whether Qoder CN now hides the
daily claim from a request without the identity, as the international
site does, is inferred from its clients, not seen.
- **List:** `GET <openapi>/sash/api/v1/me/campaigns`: `campaigns[]` with
`campaignId`, `actionType`, `claimStatus` (`CLAIMABLE`, `CLAIMED`),
+77 -4
View File
@@ -11,6 +11,7 @@ import { QoderAuthPlugin, QoderCNAuthPlugin, _internal } from "./index.mjs"
const real = globalThis.fetch
const originalRuntime = process.env.QODER_RUNTIME_INFO
const originalCNRuntime = process.env.QODERCN_RUNTIME_INFO
const realStat = fsPromises.stat
let sandbox, native, reads, nativeError, nativeOutput
const MACHINE_TYPE = "cfe111111111111111"
@@ -19,6 +20,7 @@ beforeEach(() => {
const file = join(sandbox, process.platform === "win32" ? "runtime-info.exe" : "runtime-info")
writeFileSync(file, "fixture")
process.env.QODER_RUNTIME_INFO = file
process.env.QODERCN_RUNTIME_INFO = file
reads = []
nativeError = null
nativeOutput = (uid) => JSON.stringify({ machineToken: "sdk-token-" + uid, machineType: MACHINE_TYPE, machineCode: "fixture-code" })
@@ -39,6 +41,8 @@ afterEach(() => {
setSystemTime()
if (originalRuntime === undefined) delete process.env.QODER_RUNTIME_INFO
else process.env.QODER_RUNTIME_INFO = originalRuntime
if (originalCNRuntime === undefined) delete process.env.QODERCN_RUNTIME_INFO
else process.env.QODERCN_RUNTIME_INFO = originalCNRuntime
// 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")
@@ -204,6 +208,55 @@ test("Linux finds the Qoder desktop's /opt/Qoder runtime", async () => {
expect(await inSandbox(() => _internal.campaignRuntime({ home: sandbox, platform: "linux", arch: "x64", env: {}, opt: join(sandbox, "opt") }))).toBe(file)
})
// Qoder CN keeps its runtime under its own names (Qoder CN desktop 0.4.9's
// .deb, macOS installer and Windows user installer; qoderclicn 1.1.77), and
// never reads the international Qoder's.
const CN = _internal.RUNTIMES?.["qoder-cn"]
const cnRuntime = (opts) => inSandbox(() => _internal.campaignRuntime({ arch: "x64", env: {}, opt: join(sandbox, "opt"), runtime: CN, ...opts }))
const fixture = (...parts) => {
const file = join(sandbox, ...parts)
mkdirSync(dirname(file), { recursive: true })
writeFileSync(file, "fixture")
return file
}
test("Qoder CN: Linux finds /opt/Qoder-CN, never /opt/Qoder", async () => {
fixture("opt", "Qoder", "resources", "umid", "runtime-info")
await expect(cnRuntime({ home: sandbox, platform: "linux" })).rejects.toThrow("Qoder CN check-in: device identity runtime not found")
const file = fixture("opt", "Qoder-CN", "resources", "umid", "runtime-info")
expect(await cnRuntime({ home: sandbox, platform: "linux" })).toBe(file)
})
test("Qoder CN: macOS finds Qoder CN.app", async () => {
fixture("Applications", "Qoder.app", "Contents", "Resources", "umid", "runtime-info")
const file = fixture("Applications", "Qoder CN.app", "Contents", "Resources", "umid", "runtime-info")
expect(await cnRuntime({ home: sandbox, platform: "darwin", arch: "arm64" })).toBe(file)
})
test("Qoder CN: Windows finds the Qoder CN desktop's runtime", async () => {
fixture("Local", "Programs", "Qoder", "resources", "umid", "runtime-info.exe")
const file = fixture("Local", "Programs", "Qoder CN", "resources", "umid", "runtime-info.exe")
expect(await cnRuntime({ home: join(sandbox, "nobody"), platform: "win32", env: { LOCALAPPDATA: join(sandbox, "Local") } })).toBe(file)
})
test("Qoder CN: finds its CLI's cache in .qoder-cn and its QODERCN_ folders, never .qoder", async () => {
cliCache(join(sandbox, ".qoder"), "linux", "x64")
await expect(cnRuntime({ home: sandbox, platform: "linux" })).rejects.toThrow("QODERCN_RUNTIME_INFO")
await expect(cnRuntime({ home: sandbox, platform: "linux", env: { QODER_CONFIG_DIR: join(sandbox, ".qoder") } })).rejects.toThrow("not found")
const own = cliCache(join(sandbox, ".qoder-cn"), "linux", "x64")
expect(await cnRuntime({ home: sandbox, platform: "linux" })).toBe(own)
const dir = cliCache(join(sandbox, "custom"), "linux", "x64")
expect(await cnRuntime({ home: join(sandbox, "nobody"), platform: "linux", env: { QODERCN_CONFIG_DIR: join(sandbox, "custom") } })).toBe(dir)
const named = cliCache(join(sandbox, "clihome", ".qcn"), "linux", "x64")
expect(await cnRuntime({ home: join(sandbox, "nobody"), platform: "linux", env: { QODERCN_CLI_HOME: join(sandbox, "clihome"), QODERCN_CONFIG_DIR_NAME: ".qcn" } })).toBe(named)
})
test("Qoder CN: QODERCN_RUNTIME_INFO names its runtime; QODER_RUNTIME_INFO is the international one's", async () => {
const intl = fixture("intl", "runtime-info")
await expect(cnRuntime({ home: sandbox, platform: "linux", env: { QODER_RUNTIME_INFO: intl } })).rejects.toThrow("not found")
expect(await cnRuntime({ home: sandbox, platform: "linux", env: { QODERCN_RUNTIME_INFO: intl } })).toBe(intl)
})
test("no runtime anywhere says how to get one", async () => {
await expect(inSandbox(() => _internal.campaignRuntime({ home: sandbox, platform: "linux", arch: "x64", env: {}, opt: join(sandbox, "opt") }))).rejects.toThrow("device identity runtime not found")
})
@@ -232,16 +285,36 @@ for (const identity of [{}, { machineToken: "", machineType: MACHINE_TYPE }, { m
}
test("CN still queries and claims without a native identity runtime", async () => {
process.env.QODER_RUNTIME_INFO = join(sandbox, "not-installed")
delete process.env.QODERCN_RUNTIME_INFO
const nowhere = spyOn(fsPromises, "stat").mockImplementation(() => Promise.reject(Object.assign(new Error("ENOENT"), { code: "ENOENT" })))
try {
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)
} finally {
nowhere.mockRestore()
}
})
// #2911, plugins#304: Qoder CN's desktop (0.4.9) and CLI send Qoder CN's
// own runtime-info identity, environment 0, on its campaigns pages.
test("CN campaigns carry Qoder CN's own device identity, environment 0", async () => {
const p = await loader(QoderCNAuthPlugin, (u, init) => {
expect(init.headers["Cosy-MachineToken"]).toBeUndefined()
expect(init.headers["Cosy-MachineType"]).toBeUndefined()
expect(init.headers["Cosy-MachineToken"]).toBe("sdk-token-u1")
expect(init.headers["Cosy-MachineType"]).toBe(MACHINE_TYPE)
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)
expect(reads).toHaveLength(1)
expect(reads[0].args).toEqual(process.platform === "linux" ? ["0"] : ["0", "--account-stdin"])
})
test("a PAT account checks in on its job token, having no device token", async () => {
+63 -22
View File
@@ -1526,23 +1526,45 @@ const CAMPAIGN_MACHINE_TTL = 60 * 60 * 1000 // Qoder's desktop client renews its
// (or .qoder): a file runtime-info-<platform>-<arch>-<hash> on macOS and
// Linux, a folder umid-win32-<arch>-<hash> holding runtime-info.exe on
// Windows.
async function campaignRuntime({ home = homedir(), platform = process.platform, arch = process.arch, env = process.env, opt = "/opt" } = {}) {
if (env.QODER_RUNTIME_INFO) return resolve(env.QODER_RUNTIME_INFO)
//
// Qoder CN keeps its own (Qoder CN desktop 0.4.9's packages, qoderclicn
// 1.1.77): Qoder CN.app on macOS (its installer's expectedBundleName),
// /opt/Qoder-CN on Linux (the .deb), Qoder CN on Windows (the user
// installer's "Uninstall Qoder CN.exe", electron-builder's
// Programs\<productName>); its CLI's config is QODERCN_CONFIG_DIR, else
// QODERCN_CLI_HOME (or home) joined with QODERCN_CONFIG_DIR_NAME (or
// .qoder-cn). Both ask the helper for environment 0, the international
// ones for 3 (the desktop's `regionCode === "global" ? 3 : 0`, the CLI's
// UMID environment ONLINE = 0, US_ONLINE = 3).
//
// required: international Qoder lists the daily credits only on a request
// carrying the identity. Qoder CN's desktop sends it when it can read it
// and goes on without it when it can't, and a Qoder CN account was offered
// and claimed the credits without one (0.2.21), so there it is sent when
// Qoder CN is installed and left out when it isn't.
const RUNTIMES = {
qoder: { name: "Qoder", environment: "3", override: "QODER_RUNTIME_INFO", app: "Qoder", linux: "Qoder", cli: "QODER_", dir: ".qoder", required: true },
"qoder-cn": { name: "Qoder CN", environment: "0", override: "QODERCN_RUNTIME_INFO", app: "Qoder CN", linux: "Qoder-CN", cli: "QODERCN_", dir: ".qoder-cn", required: false },
}
async function campaignRuntime({ home = homedir(), platform = process.platform, arch = process.arch, env = process.env, opt = "/opt", runtime = RUNTIMES.qoder } = {}) {
if (env[runtime.override]) return resolve(env[runtime.override])
const name = platform === "win32" ? "runtime-info.exe" : "runtime-info"
const isFile = async (path) => (await stat(path).catch(() => null))?.isFile() ?? false
const paths = []
if (platform === "win32") {
const local = env.LOCALAPPDATA || join(home, "AppData", "Local")
paths.push(join(local, "Programs", "Qoder", "resources", "umid", name))
paths.push(join(local, "Programs", runtime.app, "resources", "umid", name))
// the machine-wide installer, as VS Code's system setup places it
for (const dir of [env.ProgramFiles || env.PROGRAMFILES, env.ProgramW6432]) if (dir) paths.push(join(dir, "Qoder", "resources", "umid", name))
for (const dir of [env.ProgramFiles || env.PROGRAMFILES, env.ProgramW6432]) if (dir) paths.push(join(dir, runtime.app, "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 dir of ["/Applications", join(home, "Applications")]) paths.push(join(dir, runtime.app + ".app", "Contents", "Resources", "umid", name))
} else if (platform === "linux") {
paths.push(join(opt, "Qoder", "resources", "umid", name))
paths.push(join(opt, runtime.linux, "resources", "umid", name))
}
for (const path of paths) if (await isFile(path)) return path
const config = env.QODER_CONFIG_DIR || join(env.QODER_CLI_HOME || env.GEMINI_CLI_HOME || home, env.QODER_CONFIG_DIR_NAME || ".qoder")
const cli = (key) => env[runtime.cli + key]
const config = cli("CONFIG_DIR") || join(cli("CLI_HOME") || env.GEMINI_CLI_HOME || home, cli("CONFIG_DIR_NAME") || runtime.dir)
const cache = join(config, ".bin")
const entries = await readdir(cache, { withFileTypes: true }).catch(() => [])
const found = []
@@ -1556,7 +1578,7 @@ async function campaignRuntime({ home = homedir(), platform = process.platform,
if (path && (await isFile(path))) found.push({ path, time: (await stat(path)).mtimeMs })
}
if (found.length) return found.sort((a, b) => b.time - a.time)[0].path
throw new RuntimeMissing()
throw new RuntimeMissing(runtime)
}
// RuntimeMissing: no Qoder desktop or CLI on this machine to read the
@@ -1566,19 +1588,21 @@ async function campaignRuntime({ home = homedir(), platform = process.platform,
// never makes up. Asking again won't change that until the user installs
// Qoder, so the check-in says what to do once instead of "tries again later".
class RuntimeMissing extends Error {
constructor() {
constructor(runtime = RUNTIMES.qoder) {
const { name, override } = runtime
super(
"Qoder check-in: device identity runtime not found. Qoder gives the daily credits only to a device its own app identifies, and this machine has neither Qoder desktop nor Qoder CLI to read that identity from. Install Qoder desktop (or install Qoder CLI and sign in to it once), or set QODER_RUNTIME_INFO to its runtime-info executable; magpie checks in again the next day",
`${name} check-in: device identity runtime not found. ${name} gives the daily credits only to a device its own app identifies, and this machine has neither ${name} desktop nor ${name} CLI to read that identity from. Install ${name} desktop (or install ${name} CLI and sign in to it once), or set ${override} to its runtime-info executable; magpie checks in again the next day`,
)
}
}
// 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) {
// Read the SDK identity as Qoder does: environment 3 is international, 0
// Qoder CN; on Windows and macOS the uid goes over stdin, never into the
// command line.
async function campaignMachine(uid, runtime = RUNTIMES.qoder) {
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 file = await campaignRuntime({ runtime })
const args = process.platform === "linux" ? [runtime.environment] : [runtime.environment, "--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)
@@ -1587,7 +1611,7 @@ async function campaignMachine(uid) {
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")
throw new Error(`${runtime.name} check-in: could not read device identity; restart or update ${runtime.name}, or check ${runtime.override}`)
})
try {
const identity = JSON.parse(text.trim().split(/\r?\n/, 1)[0])
@@ -1599,7 +1623,7 @@ async function campaignMachine(uid) {
}
return headers
} catch {
throw new Error("Qoder check-in: invalid device identity from Qoder; restart or update Qoder")
throw new Error(`${runtime.name} check-in: invalid device identity from ${runtime.name}; restart or update ${runtime.name}`)
}
}
@@ -1754,12 +1778,13 @@ 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 runtime = RUNTIMES[ID]
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) }
entry = { at: now, promise: campaignMachine(uid, runtime) }
campaignMachines.set(uid, entry)
}
try {
@@ -1769,6 +1794,16 @@ const makePlugin = (site) => async ({ client }) => {
throw e
}
}
// 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) => {
if (runtime.required) return { machine: await machineForCampaign(uid) }
try {
return { machine: await machineForCampaign(uid) }
} catch (e) {
return { machine: {}, unread: e }
}
}
// serializes checking, rotating and saving tokens: a refresh token is
// spent once, so two refreshes would spend it twice
let lock = Promise.resolve()
@@ -1927,7 +1962,7 @@ 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 {
const machine = site.id === "qoder" ? await machineForCampaign(cred.uid) : {}
const { machine } = await campaignIdentity(cred.uid)
// A PAT account has no device token: its job token signs the campaigns
// pages too, as it does the usage read. Nothing is rotated on that
// path — the refusal is the answer.
@@ -1956,7 +1991,7 @@ const makePlugin = (site) => async ({ client }) => {
const base = campaignTarget(site, siteOf(site, cred), site.openapi + CAMPAIGNS)
if (!base) return { outcome: "inactive", message: "no campaigns page for this account" }
try {
const machine = site.id === "qoder" ? await machineForCampaign(cred.uid) : {}
const { machine, unread } = await campaignIdentity(cred.uid)
// A PAT account has no device token: the campaigns pages take the job
// token the exchange gave, as the usage endpoint does. A live Qoder CN
// PAT account answered 200 to the list and CLAIMED to a claim, so the
@@ -1994,7 +2029,13 @@ const makePlugin = (site) => async ({ client }) => {
const amount = Number(done.benefit?.amount)
return { outcome: "done", ...(Number.isFinite(amount) && amount > 0 ? { credit: amount } : {}) }
}
return campaigns.length ? { outcome: "failed", message: "campaigns: today's credits aren't offered yet" } : { outcome: "inactive" }
if (campaigns.length) return { outcome: "failed", message: "campaigns: today's credits aren't offered yet" }
// Asked without Qoder CN's identity and offered nothing: what an
// international list says to a request without one, so say why
// (no Qoder CN on this machine) or ask again (it didn't answer).
if (unread instanceof RuntimeMissing) return { outcome: "ineligible", message: unread.message }
if (unread) return { outcome: "failed", message: unread.message }
return { outcome: "inactive" }
}
const claimRes = await call(base.replace(/\/$/, "") + "/" + encodeURIComponent(campaign.campaignId) + "/claim", "POST", "{}")
let claim = {}
@@ -2233,4 +2274,4 @@ export const QoderAuthPlugin = makePlugin(SITES.qoder)
export const QoderCNAuthPlugin = makePlugin(SITES["qoder-cn"])
// for tests
export const _internal = { campaignRuntime, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, SITES, decodeBody, events, QUEUE, queueState }
export const _internal = { campaignRuntime, RUNTIMES, campaignPage, campaignTarget, vpcInstance, vpcSite, parseUsage, gfmt, when, failure, modelInfo, qoderBody, qoderMessages, cacheMarked, sessionOf, SITES, decodeBody, events, QUEUE, queueState }
+60 -3
View File
@@ -10,12 +10,14 @@ import { QoderAuthPlugin, QoderCNAuthPlugin } from "./index.mjs"
const real = globalThis.fetch
const originalRuntime = process.env.QODER_RUNTIME_INFO
const originalCNRuntime = process.env.QODERCN_RUNTIME_INFO
const MACHINE_TYPE = "cfe111111111111111"
let sandbox, native, reads, nativeError, nativeOutput
beforeEach(() => {
sandbox = mkdtempSync(join(tmpdir(), "qoder-native-checkin-"))
process.env.QODER_RUNTIME_INFO = join(sandbox, process.platform === "win32" ? "runtime-info.exe" : "runtime-info")
writeFileSync(process.env.QODER_RUNTIME_INFO, "fixture")
process.env.QODERCN_RUNTIME_INFO = process.env.QODER_RUNTIME_INFO
reads = []
nativeError = null
nativeOutput = (uid) => JSON.stringify({ machineToken: "sdk-token-" + uid, machineType: MACHINE_TYPE })
@@ -35,6 +37,8 @@ afterEach(() => {
native.mockRestore()
if (originalRuntime === undefined) delete process.env.QODER_RUNTIME_INFO
else process.env.QODER_RUNTIME_INFO = originalRuntime
if (originalCNRuntime === undefined) delete process.env.QODERCN_RUNTIME_INFO
else process.env.QODERCN_RUNTIME_INFO = originalCNRuntime
const target = realpathSync(sandbox)
if (!target.startsWith(realpathSync(tmpdir()) + sep)) throw new Error("test directory escaped temp root")
rmSync(target, { recursive: true, force: true })
@@ -86,16 +90,69 @@ test("a claim answer with nested data is read", async () => {
expect(p.out).toEqual({ outcome: "claimed", credit: 100 })
})
// Qoder CN on no device: no runtime anywhere, as on a machine that never had
// Qoder CN desktop or its CLI.
async function noRuntime(run) {
delete process.env.QODER_RUNTIME_INFO
delete process.env.QODERCN_RUNTIME_INFO
const nowhere = spyOn(fsPromises, "stat").mockImplementation(() => Promise.reject(Object.assign(new Error("ENOENT"), { code: "ENOENT" })))
try {
return await run()
} finally {
nowhere.mockRestore()
}
}
test("CN claims without the native runtime", async () => {
process.env.QODER_RUNTIME_INFO = join(sandbox, "not-installed")
const p = await checkin(QoderCNAuthPlugin, (u, init) => {
const p = await noRuntime(() => checkin(QoderCNAuthPlugin, (u, init) => {
expect(init.headers["Cosy-MachineToken"]).toBeUndefined()
return u.pathname.endsWith("/claim") ? json({ status: "CLAIMED" }) : json(LIST)
}, "https://openapi.qoder.com.cn")
}, "https://openapi.qoder.com.cn"))
expect(p.out).toEqual({ outcome: "claimed", credit: 100 })
expect(reads).toHaveLength(0)
})
// #2911, plugins#304 (10-22): Qoder CN desktop 0.4.9 and its CLI ask
// Qoder CN's runtime-info for environment 0 and send what it says on every
// campaigns request; the plugin sent nothing for CN. With Qoder CN
// installed, the check-in carries the same identity.
test("CN claims with Qoder CN's own device identity, environment 0", async () => {
const p = await checkin(QoderCNAuthPlugin, (u, init) => {
const identified = init.headers["Cosy-MachineToken"] === "sdk-token-u1" && init.headers["Cosy-MachineType"] === MACHINE_TYPE
if (u.pathname.endsWith("/claim")) return json(identified ? { status: "CLAIMED" } : { status: "INELIGIBLE" })
return json(identified ? LIST : { campaigns: [] })
}, "https://openapi.qoder.com.cn")
expect(p.out).toEqual({ outcome: "claimed", credit: 100 })
expect(reads).toHaveLength(1)
expect(reads[0].args).toEqual(process.platform === "linux" ? ["0"] : ["0", "--account-stdin"])
if (process.platform !== "linux") expect(reads[0].input).toEqual({ account: "u1" })
})
// Offered nothing without the identity, the CN check-in says why and what to
// install, as the international one does, instead of "inactive".
test("CN offered nothing with no Qoder CN on this machine is ineligible, naming Qoder CN", async () => {
const p = await noRuntime(() => checkin(QoderCNAuthPlugin, () => json({ campaigns: [] }), "https://openapi.qoder.com.cn"))
expect(p.out.outcome).toBe("ineligible")
expect(p.out.message).toContain("Install Qoder CN desktop")
expect(p.out.message).toContain("QODERCN_RUNTIME_INFO")
expect(reads).toHaveLength(0)
})
// The helper is there but didn't answer: ask again later, not for the day.
test("CN offered nothing when Qoder CN's helper failed is a failure to retry", async () => {
nativeError = new Error("fixture helper unavailable")
const p = await checkin(QoderCNAuthPlugin, () => json({ campaigns: [] }), "https://openapi.qoder.com.cn")
expect(p.out.outcome).toBe("failed")
expect(p.out.message).toContain("Qoder CN check-in: could not read device identity")
})
// The helper failing never stops a check-in the server still serves.
test("CN still claims when Qoder CN's helper fails", async () => {
nativeError = new Error("fixture helper unavailable")
const p = await checkin(QoderCNAuthPlugin, (u) => (u.pathname.endsWith("/claim") ? json({ status: "CLAIMED" }) : json(LIST)), "https://openapi.qoder.com.cn")
expect(p.out).toEqual({ outcome: "claimed", credit: 100 })
})
// plugins#304: on a machine that never had Qoder there is no helper to read
// the identity from, and without it Qoder hides the daily credits. That is
// an answer for the day with what to do once, not "tries again later".
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-qoder-auth",
"version": "0.2.28",
"version": "0.2.30",
"description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)",
"type": "module",
"main": "./index.mjs",