Models: add Qwen Portal OAuth support
This commit is contained in:
committed by
Peter Steinberger
parent
f9e3b129ed
commit
8eb80ee40a
24
extensions/qwen-portal-auth/README.md
Normal file
24
extensions/qwen-portal-auth/README.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# Qwen Portal OAuth (Clawdbot plugin)
|
||||
|
||||
OAuth provider plugin for **Qwen Portal** (free-tier OAuth).
|
||||
|
||||
## Enable
|
||||
|
||||
Bundled plugins are disabled by default. Enable this one:
|
||||
|
||||
```bash
|
||||
clawdbot plugins enable qwen-portal-auth
|
||||
```
|
||||
|
||||
Restart the Gateway after enabling.
|
||||
|
||||
## Authenticate
|
||||
|
||||
```bash
|
||||
clawdbot models auth login --provider qwen-portal --set-default
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Qwen OAuth uses a device-code login flow.
|
||||
- Tokens expire periodically; re-run login if requests fail.
|
||||
124
extensions/qwen-portal-auth/index.ts
Normal file
124
extensions/qwen-portal-auth/index.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import { loginQwenPortalOAuth } from "./oauth.js";
|
||||
|
||||
const PROVIDER_ID = "qwen-portal";
|
||||
const PROVIDER_LABEL = "Qwen Portal OAuth";
|
||||
const DEFAULT_MODEL = "qwen-portal/coder-model";
|
||||
const DEFAULT_BASE_URL = "https://portal.qwen.ai/v1";
|
||||
const DEFAULT_CONTEXT_WINDOW = 128000;
|
||||
const DEFAULT_MAX_TOKENS = 8192;
|
||||
const OAUTH_PLACEHOLDER = "qwen-oauth";
|
||||
|
||||
function normalizeBaseUrl(value: string | undefined): string {
|
||||
const raw = value?.trim() || DEFAULT_BASE_URL;
|
||||
const withProtocol = raw.startsWith("http") ? raw : `https://${raw}`;
|
||||
return withProtocol.endsWith("/v1") ? withProtocol : `${withProtocol.replace(/\/+$/, "")}/v1`;
|
||||
}
|
||||
|
||||
function buildModelDefinition(params: { id: string; name: string; input: Array<"text" | "image"> }) {
|
||||
return {
|
||||
id: params.id,
|
||||
name: params.name,
|
||||
reasoning: false,
|
||||
input: params.input,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: DEFAULT_CONTEXT_WINDOW,
|
||||
maxTokens: DEFAULT_MAX_TOKENS,
|
||||
};
|
||||
}
|
||||
|
||||
const qwenPortalPlugin = {
|
||||
id: "qwen-portal-auth",
|
||||
name: "Qwen Portal OAuth",
|
||||
description: "OAuth flow for Qwen Portal (free-tier) models",
|
||||
register(api) {
|
||||
api.registerProvider({
|
||||
id: PROVIDER_ID,
|
||||
label: PROVIDER_LABEL,
|
||||
docsPath: "/providers/qwen",
|
||||
aliases: ["qwen"],
|
||||
auth: [
|
||||
{
|
||||
id: "device",
|
||||
label: "Qwen OAuth",
|
||||
hint: "Device code login",
|
||||
kind: "device_code",
|
||||
run: async (ctx) => {
|
||||
const progress = ctx.prompter.progress("Starting Qwen OAuth…");
|
||||
try {
|
||||
const result = await loginQwenPortalOAuth({
|
||||
openUrl: ctx.openUrl,
|
||||
note: ctx.prompter.note,
|
||||
progress,
|
||||
});
|
||||
|
||||
progress.stop("Qwen OAuth complete");
|
||||
|
||||
const profileId = `${PROVIDER_ID}:default`;
|
||||
const baseUrl = normalizeBaseUrl(result.resourceUrl);
|
||||
|
||||
return {
|
||||
profiles: [
|
||||
{
|
||||
profileId,
|
||||
credential: {
|
||||
type: "oauth",
|
||||
provider: PROVIDER_ID,
|
||||
access: result.access,
|
||||
refresh: result.refresh,
|
||||
expires: result.expires,
|
||||
},
|
||||
},
|
||||
],
|
||||
configPatch: {
|
||||
models: {
|
||||
providers: {
|
||||
[PROVIDER_ID]: {
|
||||
baseUrl,
|
||||
apiKey: OAUTH_PLACEHOLDER,
|
||||
api: "openai-completions",
|
||||
models: [
|
||||
buildModelDefinition({
|
||||
id: "coder-model",
|
||||
name: "Qwen Coder (Portal)",
|
||||
input: ["text"],
|
||||
}),
|
||||
buildModelDefinition({
|
||||
id: "vision-model",
|
||||
name: "Qwen Vision (Portal)",
|
||||
input: ["text", "image"],
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
agents: {
|
||||
defaults: {
|
||||
models: {
|
||||
"qwen-portal/coder-model": { alias: "qwen" },
|
||||
"qwen-portal/vision-model": {},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
defaultModel: DEFAULT_MODEL,
|
||||
notes: [
|
||||
"Qwen OAuth tokens auto-refresh. Re-run login if refresh fails or access is revoked.",
|
||||
`Base URL defaults to ${DEFAULT_BASE_URL}. Override models.providers.${PROVIDER_ID}.baseUrl if needed.`,
|
||||
],
|
||||
};
|
||||
} catch (err) {
|
||||
progress.stop("Qwen OAuth failed");
|
||||
await ctx.prompter.note(
|
||||
"If OAuth fails, verify your Qwen account has portal access and try again.",
|
||||
"Qwen OAuth",
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default qwenPortalPlugin;
|
||||
190
extensions/qwen-portal-auth/oauth.ts
Normal file
190
extensions/qwen-portal-auth/oauth.ts
Normal file
@@ -0,0 +1,190 @@
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
|
||||
const QWEN_OAUTH_BASE_URL = "https://chat.qwen.ai";
|
||||
const QWEN_OAUTH_DEVICE_CODE_ENDPOINT = `${QWEN_OAUTH_BASE_URL}/api/v1/oauth2/device/code`;
|
||||
const QWEN_OAUTH_TOKEN_ENDPOINT = `${QWEN_OAUTH_BASE_URL}/api/v1/oauth2/token`;
|
||||
const QWEN_OAUTH_CLIENT_ID = "f0304373b74a44d2b584a3fb70ca9e56";
|
||||
const QWEN_OAUTH_SCOPE = "openid profile email model.completion";
|
||||
const QWEN_OAUTH_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
||||
|
||||
export type QwenDeviceAuthorization = {
|
||||
device_code: string;
|
||||
user_code: string;
|
||||
verification_uri: string;
|
||||
verification_uri_complete?: string;
|
||||
expires_in: number;
|
||||
interval?: number;
|
||||
};
|
||||
|
||||
export type QwenOAuthToken = {
|
||||
access: string;
|
||||
refresh: string;
|
||||
expires: number;
|
||||
resourceUrl?: string;
|
||||
};
|
||||
|
||||
type TokenPending = { status: "pending"; slowDown?: boolean };
|
||||
|
||||
type DeviceTokenResult =
|
||||
| { status: "success"; token: QwenOAuthToken }
|
||||
| TokenPending
|
||||
| { status: "error"; message: string };
|
||||
|
||||
function toFormUrlEncoded(data: Record<string, string>): string {
|
||||
return Object.entries(data)
|
||||
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
|
||||
.join("&");
|
||||
}
|
||||
|
||||
function generatePkce(): { verifier: string; challenge: string } {
|
||||
const verifier = randomBytes(32).toString("base64url");
|
||||
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
||||
return { verifier, challenge };
|
||||
}
|
||||
|
||||
async function requestDeviceCode(params: { challenge: string }): Promise<QwenDeviceAuthorization> {
|
||||
const response = await fetch(QWEN_OAUTH_DEVICE_CODE_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Accept: "application/json",
|
||||
"x-request-id": randomUUID(),
|
||||
},
|
||||
body: toFormUrlEncoded({
|
||||
client_id: QWEN_OAUTH_CLIENT_ID,
|
||||
scope: QWEN_OAUTH_SCOPE,
|
||||
code_challenge: params.challenge,
|
||||
code_challenge_method: "S256",
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
throw new Error(`Qwen device authorization failed: ${text || response.statusText}`);
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as QwenDeviceAuthorization & { error?: string };
|
||||
if (!payload.device_code || !payload.user_code || !payload.verification_uri) {
|
||||
throw new Error(
|
||||
payload.error ??
|
||||
"Qwen device authorization returned an incomplete payload (missing user_code or verification_uri).",
|
||||
);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function pollDeviceToken(params: {
|
||||
deviceCode: string;
|
||||
verifier: string;
|
||||
}): Promise<DeviceTokenResult> {
|
||||
const response = await fetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: toFormUrlEncoded({
|
||||
grant_type: QWEN_OAUTH_GRANT_TYPE,
|
||||
client_id: QWEN_OAUTH_CLIENT_ID,
|
||||
device_code: params.deviceCode,
|
||||
code_verifier: params.verifier,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let payload: { error?: string; error_description?: string } | undefined;
|
||||
try {
|
||||
payload = (await response.json()) as { error?: string; error_description?: string };
|
||||
} catch {
|
||||
const text = await response.text();
|
||||
return { status: "error", message: text || response.statusText };
|
||||
}
|
||||
|
||||
if (response.status === 400 && payload?.error === "authorization_pending") {
|
||||
return { status: "pending" };
|
||||
}
|
||||
|
||||
if (response.status === 429 && payload?.error === "slow_down") {
|
||||
return { status: "pending", slowDown: true };
|
||||
}
|
||||
|
||||
return {
|
||||
status: "error",
|
||||
message: payload?.error_description || payload?.error || response.statusText,
|
||||
};
|
||||
}
|
||||
|
||||
const tokenPayload = (await response.json()) as {
|
||||
access_token?: string | null;
|
||||
refresh_token?: string | null;
|
||||
expires_in?: number | null;
|
||||
token_type?: string;
|
||||
resource_url?: string;
|
||||
};
|
||||
|
||||
if (!tokenPayload.access_token || !tokenPayload.refresh_token || !tokenPayload.expires_in) {
|
||||
return { status: "error", message: "Qwen OAuth returned incomplete token payload." };
|
||||
}
|
||||
|
||||
return {
|
||||
status: "success",
|
||||
token: {
|
||||
access: tokenPayload.access_token,
|
||||
refresh: tokenPayload.refresh_token,
|
||||
expires: Date.now() + tokenPayload.expires_in * 1000,
|
||||
resourceUrl: tokenPayload.resource_url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function loginQwenPortalOAuth(params: {
|
||||
openUrl: (url: string) => Promise<void>;
|
||||
note: (message: string, title?: string) => Promise<void>;
|
||||
progress: { update: (message: string) => void; stop: (message?: string) => void };
|
||||
}): Promise<QwenOAuthToken> {
|
||||
const { verifier, challenge } = generatePkce();
|
||||
const device = await requestDeviceCode({ challenge });
|
||||
const verificationUrl = device.verification_uri_complete || device.verification_uri;
|
||||
|
||||
await params.note(
|
||||
[
|
||||
`Open ${verificationUrl} to approve access.`,
|
||||
`If prompted, enter the code ${device.user_code}.`,
|
||||
].join("\n"),
|
||||
"Qwen OAuth",
|
||||
);
|
||||
|
||||
try {
|
||||
await params.openUrl(verificationUrl);
|
||||
} catch {
|
||||
// Fall back to manual copy/paste if browser open fails.
|
||||
}
|
||||
|
||||
const start = Date.now();
|
||||
let pollIntervalMs = device.interval ? device.interval * 1000 : 2000;
|
||||
const timeoutMs = device.expires_in * 1000;
|
||||
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
params.progress.update("Waiting for Qwen OAuth approval…");
|
||||
const result = await pollDeviceToken({
|
||||
deviceCode: device.device_code,
|
||||
verifier,
|
||||
});
|
||||
|
||||
if (result.status === "success") {
|
||||
return result.token;
|
||||
}
|
||||
|
||||
if (result.status === "error") {
|
||||
throw new Error(`Qwen OAuth failed: ${result.message}`);
|
||||
}
|
||||
|
||||
if (result.status === "pending" && result.slowDown) {
|
||||
pollIntervalMs = Math.min(pollIntervalMs * 1.5, 10000);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
||||
}
|
||||
|
||||
throw new Error("Qwen OAuth timed out waiting for authorization.");
|
||||
}
|
||||
Reference in New Issue
Block a user