diff --git a/packages/qoder/README.md b/packages/qoder/README.md index c9a95c5..ee24c19 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -201,7 +201,10 @@ 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 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), +(Settings), through `auth.checkin`: an already claimed campaign is `done`, +a campaign not available is `inactive`, and a claimable one is `claimed` +with its benefit amount. It asks these pages through this plugin's own +campaigns path (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. diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 25af4ec..026e46b 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -1618,6 +1618,73 @@ const makePlugin = (site) => async ({ client }) => { } } + // checkin claims the daily credits through the same campaigns page as + // Qoder's client. A campaign already claimed is done; one not available + // is inactive, never an error that magpie would retry all day. + const checkin = async (getAuth) => { + let cred + try { + cred = await fresh(getAuth) + } catch (e) { + return { outcome: "failed", message: e?.message ?? String(e), ...(e?.expired ? { signIn: "expired" } : {}) } + } + 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 call = async (url, method, body) => { + let res = await campaignCall(url, method, body, cred.deviceToken, machine) + if (res.status === 401 || res.status === 403) { + const token = await deviceToken(getAuth, cred.deviceToken) + const current = latest(await getAuth()) + cred = { ...current, deviceToken: token } + res = await campaignCall(url, method, body, token, machine) + } + return res + } + const listRes = await call(base, "GET") + let list = {} + let listRaw = "" + try { + listRaw = await listRes.text() + list = JSON.parse(listRaw) ?? {} + } catch { + return { outcome: "failed", message: `campaigns: unreadable reply ${listRaw.trim().slice(0, 120) || "(empty)"}` } + } + if (listRes.status !== 200) return { outcome: "failed", message: `campaigns: HTTP ${listRes.status}` } + const now = Date.now() + const active = (c) => (!c.startAt || c.startAt * 1000 <= now) && (!c.endAt || c.endAt * 1000 > now) + const campaigns = (Array.isArray(list.campaigns) ? list.campaigns : []).filter((x) => x?.actionType === "CLAIM_BENEFIT") + const campaign = campaigns.find((x) => x.claimStatus === "CLAIMABLE") + if (!campaign) { + const done = campaigns.find((x) => x.claimStatus === "CLAIMED" && active(x)) + if (done) { + 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" } + } + const claimRes = await call(base.replace(/\/$/, "") + "/" + encodeURIComponent(campaign.campaignId) + "/claim", "POST", "{}") + let claim = {} + let claimRaw = "" + try { + claimRaw = await claimRes.text() + claim = JSON.parse(claimRaw) ?? {} + } catch { + return { outcome: "failed", message: `claim: unreadable reply ${claimRaw.trim().slice(0, 120) || "(empty)"}` } + } + const said = claim?.status ?? claim?.data?.status + if (claimRes.status !== 200) return { outcome: "failed", message: `claim: HTTP ${claimRes.status}` } + if (said === "CLAIMED") { + const amount = Number(claim?.benefit?.amount ?? claim?.data?.benefit?.amount ?? campaign.benefit?.amount) + return { outcome: "claimed", ...(Number.isFinite(amount) && amount > 0 ? { credit: amount } : {}) } + } + return { outcome: "failed", message: `claim: ${said || "unknown answer"}` } + } catch (e) { + return { outcome: "failed", message: e?.message ?? String(e), ...(e?.expired ? { signIn: "expired" } : {}) } + } + } + const signedInError = (e) => errorResponse({ status: e instanceof SignInGone ? 401 : 502, @@ -1774,6 +1841,7 @@ const makePlugin = (site) => async ({ client }) => { : []), ], usage, + checkin, }, async config(config) { config.provider ??= {} diff --git a/packages/qoder/native-checkin.test.mjs b/packages/qoder/native-checkin.test.mjs new file mode 100644 index 0000000..3fcde5f --- /dev/null +++ b/packages/qoder/native-checkin.test.mjs @@ -0,0 +1,130 @@ +// Native auth.checkin: the campaigns answer in magpie's outcome words, not +// Qoder's raw page. +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test" +import * as childProcess from "node:child_process" +import * as fsPromises from "node:fs/promises" +import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join, sep } from "node:path" +import { QoderAuthPlugin, QoderCNAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +const originalRuntime = process.env.QODER_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") + reads = [] + nativeError = null + nativeOutput = (uid) => JSON.stringify({ machineToken: "sdk-token-" + uid, machineType: MACHINE_TYPE }) + native = spyOn(childProcess, "execFile").mockImplementation((file, args, options, done) => ({ + stdin: { + on() {}, + end(text) { + const input = text ? JSON.parse(text) : {} + reads.push({ args, input }) + queueMicrotask(() => done(nativeError, nativeOutput(input.account ?? "u1"))) + }, + }, + })) +}) +afterEach(() => { + globalThis.fetch = real + native.mockRestore() + if (originalRuntime === undefined) delete process.env.QODER_RUNTIME_INFO + else process.env.QODER_RUNTIME_INFO = originalRuntime + 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", refresh: "rt", expires: Date.now() + 3_600_000, + accountId: "one@x", uid: "u1", deviceToken: "dt", deviceRefresh: "drt", +}) +const json = (v, status = 200) => new Response(JSON.stringify(v), { status }) +const LIST = { campaigns: [{ campaignId: "c1", actionType: "CLAIM_BENEFIT", claimStatus: "CLAIMABLE", benefit: { amount: 100 } }] } + +async function checkin(make, serve, origin = "https://openapi.qoder.sh") { + let auth = account() + const seen = [] + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + seen.push({ path: u.pathname, method: init.method ?? "GET", auth: init.headers.Authorization, body: init.body }) + return serve(u, init) + } + const hooks = await make({ client: { auth: { set: async ({ body }) => (auth = body) } } }) + return { out: await hooks.auth.checkin(async () => auth), seen, auth: () => auth } +} + +test("a claimable campaign is claimed with the native identity", async () => { + const p = await checkin(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(identified ? { status: "CLAIMED" } : { status: "INELIGIBLE" }) + return json(identified ? LIST : { campaigns: [] }) + }) + expect(p.out).toEqual({ outcome: "claimed", credit: 100 }) + expect(p.seen.map((x) => x.path)).toEqual(["/sash/api/v1/me/campaigns", "/sash/api/v1/me/campaigns/c1/claim"]) + expect(reads).toHaveLength(1) +}) + +test("an already-claimed campaign is done without another claim", async () => { + const p = await checkin(QoderAuthPlugin, () => json({ campaigns: [{ campaignId: "c1", actionType: "CLAIM_BENEFIT", claimStatus: "CLAIMED", benefit: { amount: 100 } }] })) + expect(p.out).toEqual({ outcome: "done", credit: 100 }) + expect(p.seen.map((x) => x.path)).toEqual(["/sash/api/v1/me/campaigns"]) +}) + +test("no benefit campaign is inactive", async () => { + const p = await checkin(QoderAuthPlugin, () => json({ campaigns: [{ campaignId: "x", actionType: "VIEW_DETAILS", claimStatus: "CLAIMABLE" }] })) + expect(p.out).toEqual({ outcome: "inactive" }) +}) + +test("a claim answer with nested data is read", async () => { + const p = await checkin(QoderAuthPlugin, (u) => u.pathname.endsWith("/claim") ? json({ data: { status: "CLAIMED", benefit: { amount: 100 } } }) : json(LIST)) + expect(p.out).toEqual({ outcome: "claimed", credit: 100 }) +}) + +test("CN claims without the native runtime", async () => { + process.env.QODER_RUNTIME_INFO = join(sandbox, "not-installed") + const p = await 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") + expect(p.out).toEqual({ outcome: "claimed", credit: 100 }) + expect(reads).toHaveLength(0) +}) + +test("an unreadable list reply is failed", async () => { + const p = await checkin(QoderAuthPlugin, () => new Response("")) + expect(p.out).toMatchObject({ outcome: "failed" }) + expect(p.out.message).toContain("unreadable") +}) + +test("yesterday's claimed entry does not hide today's claimable campaign", async () => { + const list = { campaigns: [ + { campaignId: "old", actionType: "CLAIM_BENEFIT", claimStatus: "CLAIMED", startAt: Math.floor(Date.now()/1000)-86400, endAt: Math.floor(Date.now()/1000)+86400, benefit: { amount: 50 } }, + { campaignId: "new", actionType: "CLAIM_BENEFIT", claimStatus: "CLAIMABLE", startAt: Math.floor(Date.now()/1000)-100, endAt: Math.floor(Date.now()/1000)+86000, benefit: { amount: 100 } }, + ] } + const p = await checkin(QoderAuthPlugin, (u) => u.pathname.endsWith("/claim") ? json({ status: "CLAIMED", benefit: { amount: 125 } }) : json(list)) + expect(p.out).toEqual({ outcome: "claimed", credit: 125 }) +}) + +test("an active claimed campaign is done, and an unavailable one retries", async () => { + const active = { campaignId: "c", actionType: "CLAIM_BENEFIT", claimStatus: "CLAIMED", startAt: Math.floor(Date.now()/1000)-100, endAt: Math.floor(Date.now()/1000)+1000, benefit: { amount: 100 } } + let p = await checkin(QoderAuthPlugin, () => json({ campaigns: [active] })) + expect(p.out).toEqual({ outcome: "done", credit: 100 }) + p = await checkin(QoderAuthPlugin, () => json({ campaigns: [{ ...active, claimStatus: "DISABLED" }] })) + expect(p.out).toEqual({ outcome: "failed", message: "campaigns: today's credits aren't offered yet" }) +}) + +test("a refused device token is rotated and the claim asked again", async () => { + const p = await checkin(QoderAuthPlugin, (u, init) => { + if (u.pathname === "/api/v1/deviceToken/refresh") return json({ device_token: "dt-new", refresh_token: "drt-new" }) + const authed = init.headers.Authorization === "Bearer dt-new" && init.headers["Cosy-MachineToken"] === "sdk-token-u1" + return authed ? (u.pathname.endsWith("/claim") ? json({ status: "CLAIMED" }) : json(LIST)) : new Response("", { status: 401 }) + }) + expect(p.out).toEqual({ outcome: "claimed", credit: 100 }) + expect(p.auth().deviceToken).toBe("dt-new") +}) diff --git a/packages/qoder/package.json b/packages/qoder/package.json index e55e5d1..d4a114a 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.16", + "version": "0.2.17", "description": "Qoder subscriptions in OpenCode and magpie: Qoder (qoder.com) and Qoder CN (qoder.cn)", "type": "module", "main": "./index.mjs",