diff --git a/README.md b/README.md index ed7451a..0fbfb46 100644 --- a/README.md +++ b/README.md @@ -30,11 +30,25 @@ Then log in from pi: /login qoder ``` -The login flow will prompt you to complete authorization in your browser. +The login menu offers two methods: -### Personal Access Token (PAT) Fallback +- **Browser Login** — OAuth device-code flow; complete authorization in your browser. +- **Use API Key (PAT)** — paste a Qoder Personal Access Token (`pt-...`). -For non-interactive environments, you can set the `QODER_PERSONAL_ACCESS_TOKEN` (or `QODER_PAT`) environment variable before starting pi. The provider will automatically pick up the PAT and authenticate. +### Personal Access Token (PAT) + +A Qoder PAT (`pt-...`) cannot authenticate API calls directly — the provider +exchanges it for a short-lived job token (mirroring the official `qodercli` +flow) and resolves your account identity automatically. You can supply a PAT in +two ways: + +- Run `/login qoder` and choose **Use API Key (PAT)**, then paste the token. +- Set the `QODER_PERSONAL_ACCESS_TOKEN` (or `QODER_PAT`) environment variable, + then run `/login qoder` — the PAT is picked up automatically and exchanged + without further prompts. This is the recommended path for headless/CI setups. + +> The exchanged job token is short-lived; the provider transparently re-exchanges +> the stored PAT when it expires. ## Models @@ -70,8 +84,9 @@ Or let Qoder select automatically: src/ ├── index.ts # Extension registration ├── cosy.ts # COSY Signature and Machine ID resolver -├── login.ts # OAuth Device Flow login sequence +├── login.ts # OAuth Device Flow + PAT login sequence ├── login-ui.ts # Custom TUI components for login +├── pat.ts # PAT → job-token exchange + identity resolution ├── models.ts # Model definitions and Dynamic Config Cache ├── oauth.ts # PAT / OAuth callback orchestrator ├── stream.ts # Main streaming response handler diff --git a/src/login-ui.ts b/src/login-ui.ts index bb54acc..dd2e4a4 100644 --- a/src/login-ui.ts +++ b/src/login-ui.ts @@ -2,7 +2,7 @@ import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-a import { DynamicBorder, type ExtensionContext } from "@earendil-works/pi-coding-agent"; import { Container, type SelectItem, SelectList, Text } from "@earendil-works/pi-tui"; -export type LoginChoice = { method: "web" } | null; // cancelled +export type LoginChoice = { method: "web" } | { method: "pat" } | null; // null = cancelled let _ctx: ExtensionContext | undefined; @@ -25,6 +25,7 @@ export async function showLoginUI(): Promise { return ctx.ui.custom((tui, theme, _kb, done) => { const mainItems: SelectItem[] = [ { value: "web", label: "Browser Login", description: "Sign in via browser (OAuth device flow)" }, + { value: "pat", label: "Use API Key (PAT)", description: "Paste a Qoder Personal Access Token (pt-...)" }, ]; const container = new Container(); @@ -42,7 +43,7 @@ export async function showLoginUI(): Promise { }); selectList.onSelect = (item) => { - done({ method: item.value as "web" }); + done({ method: item.value as "web" | "pat" }); }; selectList.onCancel = () => done(null); diff --git a/src/login.ts b/src/login.ts index 0731afd..7266c36 100644 --- a/src/login.ts +++ b/src/login.ts @@ -2,6 +2,7 @@ import crypto from "node:crypto"; import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai"; import { getMachineId } from "./cosy.js"; import { hasExtensionContext, showLoginUI, showWaitingUI } from "./login-ui.js"; +import { credentialsFromPat } from "./pat.js"; type PromptFn = (p: { message: string; placeholder?: string; allowEmpty?: boolean }) => Promise; @@ -43,6 +44,10 @@ export async function interactiveLogin(callbacks: OAuthLoginCallbacks): Promise< throw new Error("Login cancelled"); } + if (choice.method === "pat") { + return patLogin(callbacks); + } + const runAuth = async (mergedCallbacks: OAuthLoginCallbacks) => { return runDeviceFlow(mergedCallbacks); }; @@ -54,18 +59,50 @@ export async function interactiveLogin(callbacks: OAuthLoginCallbacks): Promise< return creds; } - // Fallback for terminal prompt + // Fallback for terminal prompt (no extension TUI context). + // Offer PAT entry first since it works in non-interactive-ish setups. const prompt = getPrompt(callbacks); - const proceed = await prompt({ + const pat = await prompt({ + message: "Paste a Qoder Personal Access Token (pt-...), or leave empty for browser login", + placeholder: "pt-...", + allowEmpty: true, + }); + if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled"); + if (pat?.trim()) { + return patLogin(callbacks, pat.trim()); + } + + await prompt({ message: "Press Enter to start browser login for Qoder", placeholder: "press enter", allowEmpty: true, }); - if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled"); return runDeviceFlow(callbacks); } +/** Prompt for a PAT (if not provided) and exchange it for full credentials. */ +async function patLogin(callbacks: OAuthLoginCallbacks, providedPat?: string): Promise { + let pat = providedPat; + if (!pat) { + const prompt = getPrompt(callbacks); + const entered = await prompt({ + message: "Paste your Qoder Personal Access Token (pt-...)", + placeholder: "pt-...", + allowEmpty: false, + }); + if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled"); + pat = entered?.trim(); + } + if (!pat) { + throw new Error("No Personal Access Token provided"); + } + getProgress(callbacks)?.("Exchanging access token..."); + const creds = await credentialsFromPat(pat); + getProgress(callbacks)?.("Login successful!"); + return creds; +} + function abortableDelay(ms: number, signal?: AbortSignal): Promise { if (signal?.aborted) return Promise.reject(signal.reason || new Error("Login cancelled")); return new Promise((resolve, reject) => { diff --git a/src/oauth.ts b/src/oauth.ts index bfecc1e..3627b0e 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -1,10 +1,11 @@ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; -import { dirname, join } from "node:path"; +import { join } from "node:path"; import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai"; import { getMachineId } from "./cosy.js"; import { interactiveLogin } from "./login.js"; import { updateQoderModelsCache } from "./models.js"; +import { credentialsFromPat, decodePatRefresh, isPatRefresh } from "./pat.js"; export interface QoderCredentials extends OAuthCredentials { userID: string; @@ -37,46 +38,21 @@ export function getCachedCredentials(_accessToken: string): QoderCredentials | n } export async function loginQoder(callbacks: OAuthLoginCallbacks): Promise { - // 1. Try environment variables first (PAT) + // 1. Try environment variables first (PAT). A PAT (pt-...) must be exchanged + // for a short-lived job token before it can be used — credentialsFromPat + // handles the exchange + identity resolution. const pat = process.env.QODER_PERSONAL_ACCESS_TOKEN || process.env.QODER_PAT; if (pat) { try { - const userinfoRes = await fetch("https://openapi.qoder.sh/api/v1/userinfo", { - headers: { - Authorization: `Bearer ${pat}`, - Accept: "application/json", - "User-Agent": "pi-provider-qoder", - }, - }); - if (userinfoRes.ok) { - const userinfo = (await userinfoRes.json()) as { - id?: string; - email?: string; - name?: string; - username?: string; - }; - const email = userinfo.email || ""; - const name = userinfo.name || userinfo.username || ""; - const userID = userinfo.id || "pat"; - const machineID = getMachineId(); - - const creds = { - refresh: `pat|${userID}|${machineID}`, - access: pat, - expires: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30 days - userID, - email, - name, - machineID, - }; - - // pi persists these credentials in auth.json itself; no separate cache needed. - // Cache models in background - updateQoderModelsCache(pat, userID, name, email).catch(() => {}); - - return creds; - } - } catch {} + const creds = await credentialsFromPat(pat); + const qCreds = creds as QoderCredentials; + // pi persists these credentials in auth.json itself; no separate cache needed. + // Cache models in background + updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email).catch(() => {}); + return creds; + } catch { + // Fall through to interactive login if PAT exchange fails. + } } // 2. Interactive login @@ -92,19 +68,30 @@ export async function loginQoder(callbacks: OAuthLoginCallbacks): Promise { + // PAT-based credentials: re-exchange the stored PAT for a fresh job token. + if (isPatRefresh(credentials.refresh)) { + const { pat } = decodePatRefresh(credentials.refresh); + if (pat) { + try { + const refreshed = await credentialsFromPat(pat); + const qCreds = refreshed as QoderCredentials; + updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email).catch(() => {}); + return refreshed; + } catch { + // Fall through to validity extension below. + } + } + return { + ...credentials, + expires: Date.now() + 60 * 60 * 1000, // extend 1 hour to retry later + }; + } + const parts = credentials.refresh.split("|"); const refreshToken = parts[0] || ""; const userID = parts[1] || ""; const machineID = parts[2] || getMachineId(); - if (refreshToken === "pat") { - // PAT tokens don't need refreshing, just extend validity - return { - ...credentials, - expires: Date.now() + 30 * 24 * 60 * 60 * 1000, - }; - } - const refreshURL = "https://center.qoder.sh/algo/api/v3/user/refresh_token"; try { const response = await fetch(refreshURL, { diff --git a/src/pat.ts b/src/pat.ts new file mode 100644 index 0000000..49555e2 --- /dev/null +++ b/src/pat.ts @@ -0,0 +1,148 @@ +import type { OAuthCredentials } from "@earendil-works/pi-ai"; +import { getMachineId } from "./cosy.js"; + +const UA = "pi-provider-qoder"; +const EXCHANGE_URL = "https://openapi.qoder.sh/api/v1/jobToken/exchange"; +const USERINFO_URL = "https://openapi.qoder.sh/api/v1/userinfo"; + +/** + * Marker prefix used in the credential `refresh` field to identify PAT-based + * credentials. Layout: `pat||||` + */ +export const PAT_REFRESH_PREFIX = "pat"; + +export interface PatExchangeResult { + /** Short-lived job token (jt-...) used for auth + COSY signatures. */ + jobToken: string; + /** Job refresh token (jrt-...), if returned. */ + jobRefreshToken: string; + expiresAt: number; +} + +export function isPatRefresh(refresh: string): boolean { + return refresh.startsWith(`${PAT_REFRESH_PREFIX}|`); +} + +/** Encode a PAT credential's refresh field. */ +export function encodePatRefresh(pat: string, jobRefreshToken: string, userID: string, machineID: string): string { + return [PAT_REFRESH_PREFIX, pat, jobRefreshToken, userID, machineID].join("|"); +} + +/** Decode a PAT credential's refresh field. */ +export function decodePatRefresh(refresh: string): { + pat: string; + jobRefreshToken: string; + userID: string; + machineID: string; +} { + const parts = refresh.split("|"); + return { + pat: parts[1] || "", + jobRefreshToken: parts[2] || "", + userID: parts[3] || "", + machineID: parts[4] || "", + }; +} + +/** + * Exchange a Qoder Personal Access Token (pt-...) for a short-lived Job Token + * (jt-...). PATs cannot authenticate API calls directly; they must first be + * exchanged. This mirrors the official qodercli flow: + * POST /api/v1/jobToken/exchange { personal_token } -> { token, refresh_token, expires_at } + * The exchange endpoint does not require a COSY signature. + */ +export async function exchangeJobToken(pat: string): Promise { + const res = await fetch(EXCHANGE_URL, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "User-Agent": UA, + "Cosy-Version": "1.0.1", + "Cosy-ClientType": "5", + }, + body: JSON.stringify({ personal_token: pat }), + }); + + if (!res.ok) { + const text = await res.text().catch(() => ""); + throw new Error(`Qoder PAT exchange failed: ${res.status} ${res.statusText}. ${text.slice(0, 200)}`); + } + + const data = (await res.json()) as { + token?: string; + refresh_token?: string; + expires_at?: string; + expires_in?: number; + }; + + if (!data.token) { + throw new Error("Qoder PAT exchange returned no job token"); + } + + let expiresAt = Date.now() + 24 * 60 * 60 * 1000; + if (data.expires_at) { + const parsed = Date.parse(data.expires_at); + if (!Number.isNaN(parsed)) expiresAt = parsed; + } else if (data.expires_in) { + // expires_in is in milliseconds per the observed API response. + expiresAt = Date.now() + data.expires_in; + } + + return { + jobToken: data.token, + jobRefreshToken: data.refresh_token || "", + expiresAt, + }; +} + +/** Fetch user profile using a job token (jt-...). Best-effort. */ +async function fetchUserInfo(jobToken: string): Promise<{ userID: string; email: string; name: string }> { + let userID = ""; + let email = ""; + let name = ""; + try { + const res = await fetch(USERINFO_URL, { + headers: { + Authorization: `Bearer ${jobToken}`, + Accept: "application/json", + "User-Agent": UA, + "Cosy-Version": "1.0.1", + "Cosy-ClientType": "5", + }, + }); + if (res.ok) { + const info = (await res.json()) as { + id?: string; + email?: string; + name?: string; + username?: string; + }; + userID = info.id || ""; + email = info.email || ""; + name = info.name || info.username || ""; + } + } catch {} + return { userID, email, name }; +} + +/** + * Build full Qoder credentials from a Personal Access Token. + * Exchanges the PAT for a job token, resolves identity, and encodes the PAT + * into the refresh field so the token can be re-exchanged on expiry. + */ +export async function credentialsFromPat(pat: string): Promise { + const { jobToken, jobRefreshToken, expiresAt } = await exchangeJobToken(pat); + const { userID, email, name } = await fetchUserInfo(jobToken); + const machineID = getMachineId(); + + return { + refresh: encodePatRefresh(pat, jobRefreshToken, userID, machineID), + access: jobToken, + expires: expiresAt - 5 * 60 * 1000, // 5 min buffer + userID, + email, + name, + machineID, + } as OAuthCredentials; +}