feat: init pi-provider-qoder plugin with oauth, signature and WAF bypass
This commit is contained in:
+184
@@ -0,0 +1,184 @@
|
||||
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";
|
||||
|
||||
type PromptFn = (p: { message: string; placeholder?: string; allowEmpty?: boolean }) => Promise<string>;
|
||||
|
||||
function getPrompt(callbacks: OAuthLoginCallbacks): PromptFn {
|
||||
return (callbacks as unknown as { onPrompt: PromptFn }).onPrompt;
|
||||
}
|
||||
|
||||
function getProgress(callbacks: OAuthLoginCallbacks): ((msg: string) => void) | undefined {
|
||||
return (callbacks as unknown as { onProgress?: (msg: string) => void }).onProgress;
|
||||
}
|
||||
|
||||
function getSignal(callbacks: OAuthLoginCallbacks): AbortSignal | undefined {
|
||||
return (callbacks as unknown as { signal?: AbortSignal }).signal;
|
||||
}
|
||||
|
||||
export function generatePKCE() {
|
||||
const codeVerifier = crypto.randomBytes(32).toString("base64url");
|
||||
const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
|
||||
return { codeVerifier, codeChallenge };
|
||||
}
|
||||
|
||||
function parseExpiresAt(s?: string, expiresInSeconds?: number): number {
|
||||
if (s) {
|
||||
const t = Date.parse(s);
|
||||
if (!Number.isNaN(t)) return t;
|
||||
const ms = Number.parseInt(s, 10);
|
||||
if (!Number.isNaN(ms) && ms > 0) return ms;
|
||||
}
|
||||
if (expiresInSeconds && expiresInSeconds > 0) {
|
||||
return Date.now() + expiresInSeconds * 1000;
|
||||
}
|
||||
return Date.now() + 30 * 24 * 60 * 60 * 1000; // default 30 days
|
||||
}
|
||||
|
||||
export async function interactiveLogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
|
||||
if (hasExtensionContext()) {
|
||||
const choice = await showLoginUI();
|
||||
if (!choice) {
|
||||
throw new Error("Login cancelled");
|
||||
}
|
||||
|
||||
const runAuth = async (mergedCallbacks: OAuthLoginCallbacks) => {
|
||||
return runDeviceFlow(mergedCallbacks);
|
||||
};
|
||||
|
||||
const creds = await showWaitingUI(callbacks, runAuth);
|
||||
if (!creds) {
|
||||
throw new Error("Login cancelled");
|
||||
}
|
||||
return creds;
|
||||
}
|
||||
|
||||
// Fallback for terminal prompt
|
||||
const prompt = getPrompt(callbacks);
|
||||
const proceed = 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);
|
||||
}
|
||||
|
||||
function abortableDelay(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
if (signal?.aborted) return Promise.reject(signal.reason || new Error("Login cancelled"));
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(signal?.reason || new Error("Login cancelled"));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function runDeviceFlow(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
|
||||
const { codeVerifier, codeChallenge } = generatePKCE();
|
||||
const nonce = crypto.randomUUID();
|
||||
const machineID = getMachineId();
|
||||
|
||||
const verificationURI = `https://qoder.com/device/selectAccounts?challenge=${codeChallenge}&challenge_method=S256&machine_id=${machineID}&nonce=${nonce}`;
|
||||
|
||||
getProgress(callbacks)?.("Please complete login in your browser...");
|
||||
|
||||
(callbacks as unknown as { onAuth: (info: { url: string; instructions: string }) => void }).onAuth({
|
||||
url: verificationURI,
|
||||
instructions: "Click to sign in with your Qoder account in the browser.",
|
||||
});
|
||||
|
||||
const pollURL = `https://openapi.qoder.sh/api/v1/deviceToken/poll?nonce=${encodeURIComponent(nonce)}&verifier=${encodeURIComponent(codeVerifier)}&challenge_method=S256`;
|
||||
const pollInterval = 2000;
|
||||
const maxAttempts = 90; // 3 minutes
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled");
|
||||
await abortableDelay(pollInterval, getSignal(callbacks));
|
||||
|
||||
try {
|
||||
const response = await fetch(pollURL, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "pi-provider-qoder",
|
||||
},
|
||||
signal: getSignal(callbacks),
|
||||
});
|
||||
|
||||
if (response.status === 202 || response.status === 404) {
|
||||
// Pending
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const errText = await response.text();
|
||||
throw new Error(`Device token poll failed: ${response.status} ${response.statusText}. Response: ${errText}`);
|
||||
}
|
||||
|
||||
const tokenData = (await response.json()) as {
|
||||
token: string;
|
||||
user_id: string;
|
||||
refresh_token: string;
|
||||
expires_at?: string;
|
||||
expires_in?: number;
|
||||
};
|
||||
|
||||
if (!tokenData.token) {
|
||||
throw new Error("Device token poll returned empty access token");
|
||||
}
|
||||
|
||||
const expireMs = parseExpiresAt(tokenData.expires_at, tokenData.expires_in);
|
||||
|
||||
// Fetch user info (best effort)
|
||||
getProgress(callbacks)?.("Fetching user profile...");
|
||||
let email = "";
|
||||
let name = "";
|
||||
try {
|
||||
const userinfoRes = await fetch("https://openapi.qoder.sh/api/v1/userinfo", {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokenData.token}`,
|
||||
Accept: "application/json",
|
||||
"User-Agent": "pi-provider-qoder",
|
||||
},
|
||||
});
|
||||
if (userinfoRes.ok) {
|
||||
const userinfo = (await userinfoRes.json()) as {
|
||||
email?: string;
|
||||
name?: string;
|
||||
username?: string;
|
||||
};
|
||||
email = userinfo.email || "";
|
||||
name = userinfo.name || userinfo.username || "";
|
||||
}
|
||||
} catch {}
|
||||
|
||||
getProgress(callbacks)?.("Login successful!");
|
||||
|
||||
return {
|
||||
refresh: `${tokenData.refresh_token}|${tokenData.user_id}|${machineID}`,
|
||||
access: tokenData.token,
|
||||
expires: expireMs - 5 * 60 * 1000, // 5 min buffer
|
||||
userID: tokenData.user_id,
|
||||
email,
|
||||
name,
|
||||
machineID,
|
||||
} as any;
|
||||
} catch (e: any) {
|
||||
if (e.name === "AbortError" || getSignal(callbacks)?.aborted) {
|
||||
throw new Error("Login cancelled");
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Authorization timed out");
|
||||
}
|
||||
Reference in New Issue
Block a user