Feat/upgrade openclaw (#729)
This commit is contained in:
committed by
GitHub
Unverified
parent
bf5b089158
commit
d34a88e629
@@ -1,11 +1,10 @@
|
||||
/**
|
||||
* Device OAuth Manager
|
||||
*
|
||||
* Manages Device Code OAuth flows for MiniMax and Qwen providers.
|
||||
* Manages Device Code OAuth flows for MiniMax providers.
|
||||
*
|
||||
* The OAuth protocol implementations are fully self-contained in:
|
||||
* - ./minimax-oauth.ts (MiniMax Device Code + PKCE)
|
||||
* - ./qwen-oauth.ts (Qwen Device Code + PKCE)
|
||||
*
|
||||
* This approach:
|
||||
* - Hardcodes client_id and endpoints (same as openai-codex-oauth.ts)
|
||||
@@ -24,12 +23,11 @@ import { getProviderDefaultModel } from './provider-registry';
|
||||
import { proxyAwareFetch } from './proxy-fetch';
|
||||
import { saveOAuthTokenToOpenClaw, setOpenClawDefaultModelWithOverride } from './openclaw-auth';
|
||||
import { loginMiniMaxPortalOAuth, type MiniMaxOAuthToken, type MiniMaxRegion } from './minimax-oauth';
|
||||
import { loginQwenPortalOAuth, type QwenOAuthToken } from './qwen-oauth';
|
||||
|
||||
export type OAuthProviderType = 'minimax-portal' | 'minimax-portal-cn' | 'qwen-portal';
|
||||
export type OAuthProviderType = 'minimax-portal' | 'minimax-portal-cn';
|
||||
|
||||
// Re-export types for consumers
|
||||
export type { MiniMaxRegion, MiniMaxOAuthToken, QwenOAuthToken };
|
||||
export type { MiniMaxRegion, MiniMaxOAuthToken };
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// DeviceOAuthManager
|
||||
@@ -76,8 +74,6 @@ class DeviceOAuthManager extends EventEmitter {
|
||||
if (provider === 'minimax-portal' || provider === 'minimax-portal-cn') {
|
||||
const actualRegion = provider === 'minimax-portal-cn' ? 'cn' : (region || 'global');
|
||||
await this.runMiniMaxFlow(actualRegion, provider);
|
||||
} else if (provider === 'qwen-portal') {
|
||||
await this.runQwenFlow();
|
||||
} else {
|
||||
throw new Error(`Unsupported OAuth provider type: ${provider}`);
|
||||
}
|
||||
@@ -152,47 +148,7 @@ class DeviceOAuthManager extends EventEmitter {
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────
|
||||
// Qwen flow
|
||||
// ─────────────────────────────────────────────────────────
|
||||
|
||||
private async runQwenFlow(): Promise<void> {
|
||||
const provider = this.activeProvider!;
|
||||
|
||||
const token: QwenOAuthToken = await this.runWithProxyAwareFetch(() => loginQwenPortalOAuth({
|
||||
openUrl: async (url: string) => {
|
||||
logger.info(`[DeviceOAuth] Qwen opening browser: ${url}`);
|
||||
shell.openExternal(url).catch((err: unknown) =>
|
||||
logger.warn(`[DeviceOAuth] Failed to open browser:`, err)
|
||||
);
|
||||
},
|
||||
note: async (message: string, _title?: string) => {
|
||||
if (!this.active) return;
|
||||
const { verificationUri, userCode } = this.parseNote(message);
|
||||
if (verificationUri && userCode) {
|
||||
this.emitCode({ provider, verificationUri, userCode, expiresIn: 300 });
|
||||
} else {
|
||||
logger.info(`[DeviceOAuth] Qwen note: ${message}`);
|
||||
}
|
||||
},
|
||||
progress: {
|
||||
update: (msg: string) => logger.info(`[DeviceOAuth] Qwen progress: ${msg}`),
|
||||
stop: (msg?: string) => logger.info(`[DeviceOAuth] Qwen progress done: ${msg ?? ''}`),
|
||||
},
|
||||
}));
|
||||
|
||||
if (!this.active) return;
|
||||
|
||||
await this.onSuccess('qwen-portal', {
|
||||
access: token.access,
|
||||
refresh: token.refresh,
|
||||
expires: token.expires,
|
||||
// Qwen returns a per-account resourceUrl as the API base URL
|
||||
resourceUrl: token.resourceUrl,
|
||||
// Qwen uses OpenAI Completions API format
|
||||
api: 'openai-completions',
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────
|
||||
// Success handler
|
||||
@@ -235,7 +191,7 @@ class DeviceOAuthManager extends EventEmitter {
|
||||
// or falls back to the provider's default public endpoint.
|
||||
const defaultBaseUrl = providerType === 'minimax-portal'
|
||||
? 'https://api.minimax.io/anthropic'
|
||||
: (providerType === 'minimax-portal-cn' ? 'https://api.minimaxi.com/anthropic' : 'https://portal.qwen.ai/v1');
|
||||
: 'https://api.minimaxi.com/anthropic';
|
||||
|
||||
let baseUrl = token.resourceUrl || defaultBaseUrl;
|
||||
|
||||
@@ -247,11 +203,6 @@ class DeviceOAuthManager extends EventEmitter {
|
||||
// Ensure the base URL ends with /anthropic
|
||||
if (providerType.startsWith('minimax-portal') && baseUrl) {
|
||||
baseUrl = baseUrl.replace(/\/v1$/, '').replace(/\/anthropic$/, '').replace(/\/$/, '') + '/anthropic';
|
||||
} else if (providerType === 'qwen-portal' && baseUrl) {
|
||||
// Ensure Qwen API gets /v1 at the end
|
||||
if (!baseUrl.endsWith('/v1')) {
|
||||
baseUrl = baseUrl.replace(/\/$/, '') + '/v1';
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -263,7 +214,7 @@ class DeviceOAuthManager extends EventEmitter {
|
||||
authHeader: providerType.startsWith('minimax-portal') ? true : undefined,
|
||||
// OAuth placeholder — tells Gateway to resolve credentials
|
||||
// from auth-profiles.json (type: 'oauth') instead of a static API key.
|
||||
apiKeyEnv: tokenProviderId === 'minimax-portal' ? 'minimax-oauth' : 'qwen-oauth',
|
||||
apiKeyEnv: 'minimax-oauth',
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn(`[DeviceOAuth] Failed to configure openclaw models:`, err);
|
||||
@@ -274,7 +225,6 @@ class DeviceOAuthManager extends EventEmitter {
|
||||
const nameMap: Record<OAuthProviderType, string> = {
|
||||
'minimax-portal': 'MiniMax (Global)',
|
||||
'minimax-portal-cn': 'MiniMax (CN)',
|
||||
'qwen-portal': 'Qwen',
|
||||
};
|
||||
const providerConfig: ProviderConfig = {
|
||||
id: accountId,
|
||||
|
||||
@@ -473,7 +473,7 @@ export async function removeProviderFromOpenClaw(provider: string): Promise<void
|
||||
const config = await readOpenClawJson();
|
||||
let modified = false;
|
||||
|
||||
// Disable plugin (for OAuth like qwen-portal-auth)
|
||||
// Disable plugin (for OAuth like minimax-portal-auth)
|
||||
const plugins = config.plugins as Record<string, unknown> | undefined;
|
||||
const entries = (plugins?.entries ?? {}) as Record<string, Record<string, unknown>>;
|
||||
const pluginName = `${provider}-auth`;
|
||||
@@ -872,6 +872,10 @@ export async function setOpenClawDefaultModelWithOverride(
|
||||
* Get a set of all active provider IDs configured in openclaw.json.
|
||||
* Reads the file ONCE and extracts both models.providers and plugins.entries.
|
||||
*/
|
||||
// Provider IDs that have been deprecated and should never appear as active.
|
||||
// These may still linger in openclaw.json from older versions.
|
||||
const DEPRECATED_PROVIDER_IDS = new Set(['qwen-portal']);
|
||||
|
||||
export async function getActiveOpenClawProviders(): Promise<Set<string>> {
|
||||
const activeProviders = new Set<string>();
|
||||
|
||||
@@ -897,7 +901,7 @@ export async function getActiveOpenClawProviders(): Promise<Set<string>> {
|
||||
}
|
||||
|
||||
// 3. agents.defaults.model.primary — the default model reference encodes
|
||||
// the provider prefix (e.g. "qwen-portal/coder-model" → "qwen-portal").
|
||||
// the provider prefix (e.g. "modelstudio/qwen3.5-plus" → "modelstudio").
|
||||
// This covers providers that are active via OAuth or env-key but don't
|
||||
// have an explicit models.providers entry.
|
||||
const agents = config.agents as Record<string, unknown> | undefined;
|
||||
@@ -921,6 +925,11 @@ export async function getActiveOpenClawProviders(): Promise<Set<string>> {
|
||||
console.warn('Failed to read openclaw.json for active providers:', err);
|
||||
}
|
||||
|
||||
// Remove deprecated providers that may still linger in config/auth files.
|
||||
for (const deprecated of DEPRECATED_PROVIDER_IDS) {
|
||||
activeProviders.delete(deprecated);
|
||||
}
|
||||
|
||||
return activeProviders;
|
||||
}
|
||||
|
||||
@@ -1350,10 +1359,24 @@ export async function sanitizeOpenClawConfig(): Promise<void> {
|
||||
toolsModified = true;
|
||||
}
|
||||
|
||||
// ── tools.exec approvals (OpenClaw 3.28+) ──────────────────────
|
||||
// ClawX is a local desktop app where the user is the trusted operator.
|
||||
// Exec approval prompts add unnecessary friction in this context, so we
|
||||
// set security="full" (allow all commands) and ask="off" (never prompt).
|
||||
// If a user has manually configured a stricter ~/.openclaw/exec-approvals.json,
|
||||
// OpenClaw's minSecurity/maxAsk merge will still respect their intent.
|
||||
const execConfig = (toolsConfig.exec as Record<string, unknown> | undefined) || {};
|
||||
if (execConfig.security !== 'full' || execConfig.ask !== 'off') {
|
||||
execConfig.security = 'full';
|
||||
execConfig.ask = 'off';
|
||||
toolsConfig.exec = execConfig;
|
||||
toolsModified = true;
|
||||
console.log('[sanitize] Set tools.exec.security="full" and tools.exec.ask="off" to disable exec approvals for ClawX desktop');
|
||||
}
|
||||
|
||||
if (toolsModified) {
|
||||
config.tools = toolsConfig;
|
||||
modified = true;
|
||||
console.log('[sanitize] Enforced tools.profile="full" and tools.sessions.visibility="all" for OpenClaw 3.8+');
|
||||
}
|
||||
|
||||
// ── plugins.entries.feishu cleanup ──────────────────────────────
|
||||
@@ -1465,6 +1488,44 @@ export async function sanitizeOpenClawConfig(): Promise<void> {
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// ── qwen-portal → modelstudio migration ────────────────────
|
||||
// OpenClaw 2026.3.28 deprecated qwen-portal OAuth (portal.qwen.ai)
|
||||
// in favor of Model Studio (DashScope API key). Clean up legacy
|
||||
// qwen-portal-auth plugin entries and qwen-portal provider config.
|
||||
const LEGACY_QWEN_PLUGIN_ID = 'qwen-portal-auth';
|
||||
if (Array.isArray(pluginsObj.allow)) {
|
||||
const allowArr = pluginsObj.allow as string[];
|
||||
const legacyIdx = allowArr.indexOf(LEGACY_QWEN_PLUGIN_ID);
|
||||
if (legacyIdx !== -1) {
|
||||
allowArr.splice(legacyIdx, 1);
|
||||
console.log(`[sanitize] Removed deprecated plugin from plugins.allow: ${LEGACY_QWEN_PLUGIN_ID}`);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
if (pEntries?.[LEGACY_QWEN_PLUGIN_ID]) {
|
||||
delete pEntries[LEGACY_QWEN_PLUGIN_ID];
|
||||
console.log(`[sanitize] Removed deprecated plugin from plugins.entries: ${LEGACY_QWEN_PLUGIN_ID}`);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// Remove deprecated models.providers.qwen-portal
|
||||
const LEGACY_QWEN_PROVIDER = 'qwen-portal';
|
||||
if (providers[LEGACY_QWEN_PROVIDER]) {
|
||||
delete providers[LEGACY_QWEN_PROVIDER];
|
||||
console.log(`[sanitize] Removed deprecated provider: ${LEGACY_QWEN_PROVIDER}`);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// Clean up qwen-portal OAuth auth profile (no longer functional)
|
||||
const authConfig = config.auth as Record<string, unknown> | undefined;
|
||||
const authProfiles = authConfig?.profiles as Record<string, unknown> | undefined;
|
||||
if (authProfiles?.[LEGACY_QWEN_PROVIDER]) {
|
||||
delete authProfiles[LEGACY_QWEN_PROVIDER];
|
||||
console.log(`[sanitize] Removed deprecated auth profile: ${LEGACY_QWEN_PROVIDER}`);
|
||||
modified = true;
|
||||
}
|
||||
|
||||
|
||||
// ── Remove bare 'feishu' when canonical feishu plugin is present ──
|
||||
// The Gateway binary automatically adds bare 'feishu' to plugins.allow
|
||||
// because the official plugin registers the 'feishu' channel.
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
const MULTI_INSTANCE_PROVIDER_TYPES = new Set(['custom', 'ollama']);
|
||||
|
||||
export const OPENCLAW_PROVIDER_KEY_MINIMAX = 'minimax-portal';
|
||||
export const OPENCLAW_PROVIDER_KEY_QWEN = 'qwen-portal';
|
||||
export const OPENCLAW_PROVIDER_KEY_MOONSHOT = 'moonshot';
|
||||
export const OAUTH_PROVIDER_TYPES = ['qwen-portal', 'minimax-portal', 'minimax-portal-cn'] as const;
|
||||
export const OAUTH_PROVIDER_TYPES = ['minimax-portal', 'minimax-portal-cn'] as const;
|
||||
export const OPENCLAW_OAUTH_PLUGIN_PROVIDER_KEYS = [
|
||||
OPENCLAW_PROVIDER_KEY_MINIMAX,
|
||||
OPENCLAW_PROVIDER_KEY_QWEN,
|
||||
] as const;
|
||||
|
||||
const OAUTH_PROVIDER_TYPE_SET = new Set<string>(OAUTH_PROVIDER_TYPES);
|
||||
@@ -54,27 +52,24 @@ export function isMiniMaxProviderType(type: string): boolean {
|
||||
|
||||
export function getOAuthProviderTargetKey(type: string): string | undefined {
|
||||
if (!isOAuthProviderType(type)) return undefined;
|
||||
return isMiniMaxProviderType(type) ? OPENCLAW_PROVIDER_KEY_MINIMAX : OPENCLAW_PROVIDER_KEY_QWEN;
|
||||
return OPENCLAW_PROVIDER_KEY_MINIMAX;
|
||||
}
|
||||
|
||||
export function getOAuthProviderApi(type: string): 'anthropic-messages' | 'openai-completions' | undefined {
|
||||
export function getOAuthProviderApi(type: string): 'anthropic-messages' | undefined {
|
||||
if (!isOAuthProviderType(type)) return undefined;
|
||||
return isMiniMaxProviderType(type) ? 'anthropic-messages' : 'openai-completions';
|
||||
return 'anthropic-messages';
|
||||
}
|
||||
|
||||
export function getOAuthProviderDefaultBaseUrl(type: string): string | undefined {
|
||||
if (!isOAuthProviderType(type)) return undefined;
|
||||
if (type === OPENCLAW_PROVIDER_KEY_MINIMAX) return 'https://api.minimax.io/anthropic';
|
||||
if (type === 'minimax-portal-cn') return 'https://api.minimaxi.com/anthropic';
|
||||
return 'https://portal.qwen.ai/v1';
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function normalizeOAuthBaseUrl(type: string, baseUrl?: string): string | undefined {
|
||||
export function normalizeOAuthBaseUrl(_type: string, baseUrl?: string): string | undefined {
|
||||
if (!baseUrl) return undefined;
|
||||
if (isMiniMaxProviderType(type)) {
|
||||
return baseUrl.replace(/\/v1$/, '').replace(/\/anthropic$/, '').replace(/\/$/, '') + '/anthropic';
|
||||
}
|
||||
return baseUrl;
|
||||
return baseUrl.replace(/\/v1$/, '').replace(/\/anthropic$/, '').replace(/\/$/, '') + '/anthropic';
|
||||
}
|
||||
|
||||
export function usesOAuthAuthHeader(providerKey: string): boolean {
|
||||
@@ -83,7 +78,6 @@ export function usesOAuthAuthHeader(providerKey: string): boolean {
|
||||
|
||||
export function getOAuthApiKeyEnv(providerKey: string): string | undefined {
|
||||
if (providerKey === OPENCLAW_PROVIDER_KEY_MINIMAX) return 'minimax-oauth';
|
||||
if (providerKey === OPENCLAW_PROVIDER_KEY_QWEN) return 'qwen-oauth';
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
/**
|
||||
* Self-contained Qwen Device Code OAuth flow.
|
||||
*
|
||||
* Implements RFC 8628 (Device Authorization Grant) with PKCE for Qwen API.
|
||||
* Zero dependency on openclaw extension modules — survives openclaw upgrades.
|
||||
*
|
||||
* Protocol:
|
||||
* 1. POST /api/v1/oauth2/device/code → get device_code, user_code, verification_uri
|
||||
* 2. Open verification_uri in browser
|
||||
* 3. Poll POST /api/v1/oauth2/token with device_code until approved
|
||||
* 4. Return { access, refresh, expires, resourceUrl }
|
||||
*/
|
||||
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
||||
import { proxyAwareFetch } from './proxy-fetch';
|
||||
|
||||
// ── Constants ────────────────────────────────────────────────
|
||||
|
||||
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';
|
||||
|
||||
// ── Types ────────────────────────────────────────────────────
|
||||
|
||||
export interface QwenOAuthToken {
|
||||
access: string;
|
||||
refresh: string;
|
||||
expires: number;
|
||||
resourceUrl?: string;
|
||||
}
|
||||
|
||||
interface QwenDeviceAuthorization {
|
||||
device_code: string;
|
||||
user_code: string;
|
||||
verification_uri: string;
|
||||
verification_uri_complete?: string;
|
||||
expires_in: number;
|
||||
interval?: number;
|
||||
}
|
||||
|
||||
type DeviceTokenResult =
|
||||
| { status: 'success'; token: QwenOAuthToken }
|
||||
| { status: 'pending'; slowDown?: boolean }
|
||||
| { status: 'error'; message: string };
|
||||
|
||||
export interface QwenOAuthOptions {
|
||||
openUrl: (url: string) => Promise<void>;
|
||||
note: (message: string, title?: string) => Promise<void>;
|
||||
progress: { update: (message: string) => void; stop: (message?: string) => void };
|
||||
}
|
||||
|
||||
// ── PKCE helpers (self-contained, no openclaw dependency) ────
|
||||
|
||||
function generatePkce(): { verifier: string; challenge: string } {
|
||||
const verifier = randomBytes(32).toString('base64url');
|
||||
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
||||
return { verifier, challenge };
|
||||
}
|
||||
|
||||
function toFormUrlEncoded(params: Record<string, string>): string {
|
||||
return new URLSearchParams(params).toString();
|
||||
}
|
||||
|
||||
// ── OAuth flow steps ─────────────────────────────────────────
|
||||
|
||||
async function requestDeviceCode(params: { challenge: string }): Promise<QwenDeviceAuthorization> {
|
||||
const response = await proxyAwareFetch(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 proxyAwareFetch(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 (payload?.error === 'authorization_pending') {
|
||||
return { status: 'pending' };
|
||||
}
|
||||
|
||||
if (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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ── Public API ───────────────────────────────────────────────
|
||||
|
||||
export async function loginQwenPortalOAuth(params: QwenOAuthOptions): 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