|
| 1 | +/** |
| 2 | + * Qoder CN OAuth flow (device authorization grant with PKCE). |
| 3 | + */ |
| 4 | +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; |
| 5 | +import { homedir } from "node:os"; |
| 6 | +import { join } from "node:path"; |
| 7 | +import { randomUUID } from "node:crypto"; |
| 8 | +import { getConfigDir } from "../config"; |
| 9 | +import { recordOwnedConfigPath } from "../lib/config-ownership"; |
| 10 | +import { generatePKCE } from "./pkce"; |
| 11 | +import type { OAuthController, OAuthCredentials } from "./types"; |
| 12 | + |
| 13 | +const CLIENT_ID = "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb"; |
| 14 | +const DEFAULT_OPENAPI_HOST = "https://openapi.qoder.com.cn"; |
| 15 | +const DEFAULT_AUTH_HOST = "https://qoder.cn"; |
| 16 | +const MACHINE_ID_FILENAME = "qodercn-machine-id"; |
| 17 | +const POLL_INTERVAL_MS = 1500; |
| 18 | +const POLL_TIMEOUT_MS = 5 * 60 * 1000; |
| 19 | +const OAUTH_EXPIRY_SKEW_MS = 5 * 60 * 1000; |
| 20 | + |
| 21 | +interface QoderDevicePollResponse { |
| 22 | + token?: string; |
| 23 | + device_token?: string; |
| 24 | + refresh_token?: string; |
| 25 | + expires_at?: string; |
| 26 | + expires_in?: number; |
| 27 | + refresh_token_expires_at?: string; |
| 28 | + refresh_token_expires_in?: number; |
| 29 | + user_id?: string; |
| 30 | + user_name?: string; |
| 31 | + email?: string; |
| 32 | +} |
| 33 | + |
| 34 | +interface QoderTokenRefreshResponse { |
| 35 | + device_token?: string; |
| 36 | + token?: string; |
| 37 | + refresh_token?: string; |
| 38 | + expires_at?: string; |
| 39 | + expires_in?: number; |
| 40 | +} |
| 41 | + |
| 42 | +function getMachineId(): string { |
| 43 | + const cliPath = join(homedir(), ".qoder-cn", ".auth", "machine_id"); |
| 44 | + try { |
| 45 | + if (existsSync(cliPath)) { |
| 46 | + const id = readFileSync(cliPath, "utf-8").trim(); |
| 47 | + if (id) return id; |
| 48 | + } |
| 49 | + } catch (_err) { |
| 50 | + // Fall back to generating a machine id if unreadable. |
| 51 | + } |
| 52 | + const p = join(getConfigDir(), MACHINE_ID_FILENAME); |
| 53 | + try { |
| 54 | + if (existsSync(p)) { |
| 55 | + const id = readFileSync(p, "utf-8").trim(); |
| 56 | + if (id) return id; |
| 57 | + } |
| 58 | + } catch (e) { |
| 59 | + if ((e as { code?: string })?.code !== "ENOENT") throw e; |
| 60 | + } |
| 61 | + const id = randomUUID(); |
| 62 | + recordOwnedConfigPath(getConfigDir(), p); |
| 63 | + if (!existsSync(getConfigDir())) mkdirSync(getConfigDir(), { recursive: true }); |
| 64 | + writeFileSync(p, id + " |
| 65 | +", { mode: 0o600 }); |
| 66 | + return id; |
| 67 | +} |
| 68 | + |
| 69 | +function sleep(ms: number, signal?: AbortSignal): Promise<void> { |
| 70 | + return new Promise((resolve, reject) => { |
| 71 | + if (signal?.aborted) return reject(new Error("Login cancelled")); |
| 72 | + const t = setTimeout(resolve, ms); |
| 73 | + signal?.addEventListener("abort", () => { |
| 74 | + clearTimeout(t); |
| 75 | + reject(new Error("Login cancelled")); |
| 76 | + }, { once: true }); |
| 77 | + }); |
| 78 | +} |
| 79 | + |
| 80 | +async function pollForToken(nonce: string, verifier: string, signal?: AbortSignal): Promise<OAuthCredentials> { |
| 81 | + const deadline = Date.now() + POLL_TIMEOUT_MS; |
| 82 | + const search = new URLSearchParams({ |
| 83 | + nonce, |
| 84 | + verifier, |
| 85 | + challenge_method: "S256", |
| 86 | + }); |
| 87 | + const url = `${DEFAULT_OPENAPI_HOST}/api/v1/deviceToken/poll?${search}`; |
| 88 | + |
| 89 | + while (Date.now() < deadline) { |
| 90 | + if (signal?.aborted) throw new Error("Login cancelled"); |
| 91 | + const res = await fetch(url, { |
| 92 | + method: "GET", |
| 93 | + headers: { Accept: "application/json" }, |
| 94 | + signal, |
| 95 | + }); |
| 96 | + if (res.status === 404) { |
| 97 | + await sleep(POLL_INTERVAL_MS, signal); |
| 98 | + continue; |
| 99 | + } |
| 100 | + if (!res.ok) { |
| 101 | + throw new Error(`Qoder device token poll failed: HTTP ${res.status}`); |
| 102 | + } |
| 103 | + const data = (await res.json()) as QoderDevicePollResponse; |
| 104 | + const token = data.token || data.device_token; |
| 105 | + if (!token) throw new Error("Qoder poll response missing token"); |
| 106 | + |
| 107 | + let expires = Date.now() + 24 * 3600 * 1000; |
| 108 | + if (typeof data.expires_at === "string") { |
| 109 | + const parsed = new Date(data.expires_at).getTime(); |
| 110 | + if (Number.isFinite(parsed) && parsed > 0) expires = parsed - OAUTH_EXPIRY_SKEW_MS; |
| 111 | + } else if (typeof data.expires_in === "number" && Number.isFinite(data.expires_in)) { |
| 112 | + expires = Date.now() + data.expires_in * 1000 - OAUTH_EXPIRY_SKEW_MS; |
| 113 | + } |
| 114 | + |
| 115 | + const accountId = data.user_id; |
| 116 | + const email = data.user_name || data.email; |
| 117 | + |
| 118 | + return { |
| 119 | + access: token, |
| 120 | + refresh: data.refresh_token || token, |
| 121 | + expires, |
| 122 | + ...(accountId ? { accountId } : {}), |
| 123 | + ...(email ? { email } : {}), |
| 124 | + source: "oauth", |
| 125 | + }; |
| 126 | + } |
| 127 | + throw new Error("Qoder CN device authorization timed out"); |
| 128 | +} |
| 129 | + |
| 130 | +export async function loginQoderCn(ctrl: OAuthController): Promise<OAuthCredentials> { |
| 131 | + const { verifier, challenge } = generatePKCE(); |
| 132 | + const nonce = randomUUID(); |
| 133 | + const machineId = getMachineId(); |
| 134 | + const authUrl = `${DEFAULT_AUTH_HOST}/device/selectAccounts?challenge=${challenge}&challenge_method=S256&nonce=${nonce}&machine_id=${machineId}&client_id=${CLIENT_ID}`; |
| 135 | + |
| 136 | + ctrl.onAuth?.({ |
| 137 | + url: authUrl, |
| 138 | + instructions: "Please complete the login in your browser", |
| 139 | + }); |
| 140 | + |
| 141 | + return pollForToken(nonce, verifier, ctrl.signal); |
| 142 | +} |
| 143 | + |
| 144 | +export async function refreshQoderCnToken(refreshToken: string, signal?: AbortSignal): Promise<OAuthCredentials> { |
| 145 | + const res = await fetch(`${DEFAULT_OPENAPI_HOST}/api/v1/deviceToken/refresh`, { |
| 146 | + method: "POST", |
| 147 | + headers: { |
| 148 | + "Content-Type": "application/json", |
| 149 | + Accept: "application/json", |
| 150 | + }, |
| 151 | + body: JSON.stringify({ refresh_token: refreshToken }), |
| 152 | + signal, |
| 153 | + }); |
| 154 | + if (!res.ok) { |
| 155 | + throw new Error(`Qoder token refresh failed: HTTP ${res.status}`); |
| 156 | + } |
| 157 | + const data = (await res.json()) as QoderTokenRefreshResponse; |
| 158 | + const token = data.device_token || data.token; |
| 159 | + if (!token) throw new Error("Qoder refresh response missing token"); |
| 160 | + let expires = Date.now() + 24 * 3600 * 1000; |
| 161 | + if (typeof data.expires_at === "string") { |
| 162 | + const parsed = new Date(data.expires_at).getTime(); |
| 163 | + if (Number.isFinite(parsed) && parsed > 0) expires = parsed - OAUTH_EXPIRY_SKEW_MS; |
| 164 | + } else if (typeof data.expires_in === "number" && Number.isFinite(data.expires_in)) { |
| 165 | + expires = Date.now() + data.expires_in * 1000 - OAUTH_EXPIRY_SKEW_MS; |
| 166 | + } |
| 167 | + return { access: token, refresh: data.refresh_token || refreshToken, expires, source: "oauth" }; |
| 168 | +} |
0 commit comments