| 1 | // OAuth 2.1 (authorization code + PKCE / device flow) client for AiToEarn MCP. |
| 2 | // |
| 3 | // Tokens live in ~/.aitoearn/oauth.json (mode 0600), keyed by server origin. |
| 4 | // No token is ever printed to stdout. |
| 5 | import { createHash, randomBytes } from 'node:crypto' |
| 6 | import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync, statSync } from 'node:fs' |
| 7 | import { homedir } from 'node:os' |
| 8 | import { dirname, join } from 'node:path' |
| 9 | import { createServer } from 'node:http' |
| 10 | import { spawn } from 'node:child_process' |
| 11 | |
| 12 | export const SITES = { |
| 13 | cn: 'https://aitoearn.cn', |
| 14 | ai: 'https://aitoearn.ai', |
| 15 | } |
| 16 | |
| 17 | export const DEFAULT_MCP_PATH = '/api/ai/agent/mcp' |
| 18 | export const DEFAULT_CALLBACK_PORT = 0 |
| 19 | const DISCOVERY_TIMEOUT_MS = 15000 |
| 20 | const TOKEN_TIMEOUT_MS = 30000 |
| 21 | const REFRESH_SKEW_MS = 60_000 |
| 22 | const DEVICE_FLOW_DEFAULT_INTERVAL_S = 5 |
| 23 | const DEVICE_FLOW_DEFAULT_TIMEOUT_S = 600 |
| 24 | const AUTH_TIMEOUT_MS = 15 * 60_000 |
| 25 | |
| 26 | export class OAuthError extends Error { |
| 27 | constructor(message, { code = 'oauth_error', cause } = {}) { |
| 28 | super(message, cause === undefined ? undefined : { cause }) |
| 29 | this.name = 'OAuthError' |
| 30 | this.code = code |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | /* ------------------------------------------------------------------ store -- */ |
| 35 | |
| 36 | export function storePath() { |
| 37 | return process.env.AITOEARN_OAUTH_STORE || join(homedir(), '.aitoearn', 'oauth.json') |
| 38 | } |
| 39 | |
| 40 | export function siteKey(url) { |
| 41 | return new URL(url).origin |
| 42 | } |
| 43 | |
| 44 | export function readStore() { |
| 45 | const file = storePath() |
| 46 | if (!existsSync(file)) return { version: 1, sites: {} } |
| 47 | try { |
| 48 | const parsed = JSON.parse(readFileSync(file, 'utf8')) |
| 49 | if (!parsed || typeof parsed !== 'object') return { version: 1, sites: {} } |
| 50 | return { |
| 51 | version: 1, |
| 52 | selectedSite: parsed.selectedSite === 'cn' || parsed.selectedSite === 'ai' ? parsed.selectedSite : '', |
| 53 | sites: parsed.sites && typeof parsed.sites === 'object' ? parsed.sites : {}, |
| 54 | } |
| 55 | } catch { |
| 56 | return { version: 1, sites: {} } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | function writeStore(store) { |
| 61 | const file = storePath() |
| 62 | mkdirSync(dirname(file), { recursive: true }) |
| 63 | const tmp = `${file}.${process.pid}.tmp` |
| 64 | writeFileSync(tmp, JSON.stringify(store, null, 2) + '\n', { mode: 0o600 }) |
| 65 | renameSync(tmp, file) |
| 66 | try { chmodSync(file, 0o600) } catch { /* best effort */ } |
| 67 | } |
| 68 | |
| 69 | export function readSelectedSite() { |
| 70 | const site = readStore().selectedSite |
| 71 | return site === 'cn' || site === 'ai' ? site : '' |
| 72 | } |
| 73 | |
| 74 | export function saveSelectedSite(site) { |
| 75 | if (site !== 'cn' && site !== 'ai') { |
| 76 | throw new OAuthError('未知站点,可选 cn(https://aitoearn.cn)或 ai(https://aitoearn.ai)', { code: 'bad_site' }) |
| 77 | } |
| 78 | const store = readStore() |
| 79 | store.selectedSite = site |
| 80 | writeStore(store) |
| 81 | } |
| 82 | |
| 83 | export function readRecord(url) { |
| 84 | return readStore().sites[siteKey(url)] || null |
| 85 | } |
| 86 | |
| 87 | export function saveRecord(url, record) { |
| 88 | const store = readStore() |
| 89 | store.sites[siteKey(url)] = record |
| 90 | writeStore(store) |
| 91 | } |
| 92 | |
| 93 | export function removeRecord(url) { |
| 94 | const store = readStore() |
| 95 | delete store.sites[siteKey(url)] |
| 96 | writeStore(store) |
| 97 | } |
| 98 | |
| 99 | /** mtime is used by the plugin to notice a fresh CLI login without a restart. */ |
| 100 | export function storeMtimeMs() { |
| 101 | try { return statSync(storePath()).mtimeMs } catch { return 0 } |
| 102 | } |
| 103 | |
| 104 | /* -------------------------------------------------------------- helpers ---- */ |
| 105 | |
| 106 | async function fetchJson(url, init, timeoutMs = DISCOVERY_TIMEOUT_MS) { |
| 107 | const res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }) |
| 108 | const text = await res.text() |
| 109 | let json = null |
| 110 | try { json = text ? JSON.parse(text) : null } catch { /* not JSON */ } |
| 111 | return { res, text, json } |
| 112 | } |
| 113 | |
| 114 | function wellKnownCandidates(base, suffix) { |
| 115 | const origin = base.origin |
| 116 | const path = base.pathname.replace(/\/+$/, '') |
| 117 | const list = [] |
| 118 | if (suffix) list.push(`${origin}/.well-known/${suffix}${path}`) |
| 119 | list.push(`${origin}/.well-known/${suffix}`) |
| 120 | return list |
| 121 | } |
| 122 | |
| 123 | async function fetchFirstJson(urls) { |
| 124 | for (const url of urls) { |
| 125 | try { |
| 126 | const { res, json } = await fetchJson(url, { headers: { Accept: 'application/json' } }) |
| 127 | if (res.ok && json && typeof json === 'object') return json |
| 128 | } catch { /* try next */ } |
| 129 | } |
| 130 | return null |
| 131 | } |
| 132 | |
| 133 | /** RFC 9728 protected resource metadata; the resource is the MCP endpoint. */ |
| 134 | export async function discoverProtectedResource(mcpUrl) { |
| 135 | const resource = new URL(mcpUrl) |
| 136 | const meta = await fetchFirstJson(wellKnownCandidates(resource, 'oauth-protected-resource')) |
| 137 | if (!meta) return null |
| 138 | return { |
| 139 | resource: typeof meta.resource === 'string' ? meta.resource : mcpUrl, |
| 140 | authorizationServers: Array.isArray(meta.authorization_servers) ? meta.authorization_servers : [], |
| 141 | scopesSupported: Array.isArray(meta.scopes_supported) ? meta.scopes_supported : [], |
| 142 | raw: meta, |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | /** RFC 8414 authorization server metadata (with OIDC discovery fallback). */ |
| 147 | export async function discoverAuthorizationServer(issuerUrl) { |
| 148 | const issuer = new URL(issuerUrl) |
| 149 | const meta = await fetchFirstJson([ |
| 150 | ...wellKnownCandidates(issuer, 'oauth-authorization-server'), |
| 151 | ...wellKnownCandidates(issuer, 'openid-configuration'), |
| 152 | ]) |
| 153 | if (!meta) return null |
| 154 | return { |
| 155 | issuer: typeof meta.issuer === 'string' ? meta.issuer : issuerUrl, |
| 156 | authorizationEndpoint: meta.authorization_endpoint, |
| 157 | tokenEndpoint: meta.token_endpoint, |
| 158 | registrationEndpoint: meta.registration_endpoint, |
| 159 | deviceAuthorizationEndpoint: meta.device_authorization_endpoint, |
| 160 | scopesSupported: Array.isArray(meta.scopes_supported) ? meta.scopes_supported : [], |
| 161 | tokenEndpointAuthMethods: Array.isArray(meta.token_endpoint_auth_methods_supported) |
| 162 | ? meta.token_endpoint_auth_methods_supported |
| 163 | : [], |
| 164 | codeChallengeMethods: Array.isArray(meta.code_challenge_methods_supported) |
| 165 | ? meta.code_challenge_methods_supported |
| 166 | : [], |
| 167 | raw: meta, |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /** |
| 172 | * Resolve OAuth endpoints. Explicit environment variables win, so deployments |
| 173 | * without discovery metadata can still be used. |
| 174 | */ |
| 175 | export async function resolveEndpoints({ url, scope } = {}) { |
| 176 | const env = process.env |
| 177 | const mcpUrl = url || env.AITOEARN_MCP_URL || `${SITES.cn}${DEFAULT_MCP_PATH}` |
| 178 | const explicit = { |
| 179 | issuer: env.AITOEARN_OAUTH_ISSUER || '', |
| 180 | authorizationEndpoint: env.AITOEARN_OAUTH_AUTHORIZE_URL || '', |
| 181 | tokenEndpoint: env.AITOEARN_OAUTH_TOKEN_URL || '', |
| 182 | registrationEndpoint: env.AITOEARN_OAUTH_REGISTRATION_URL || '', |
| 183 | deviceAuthorizationEndpoint: env.AITOEARN_OAUTH_DEVICE_AUTHORIZATION_URL || '', |
| 184 | } |
| 185 | |
| 186 | const prm = await discoverProtectedResource(mcpUrl).catch(() => null) |
| 187 | const issuer = explicit.issuer |
| 188 | || prm?.authorizationServers?.[0] |
| 189 | || new URL(mcpUrl).origin |
| 190 | |
| 191 | const as = explicit.authorizationEndpoint && explicit.tokenEndpoint |
| 192 | ? null |
| 193 | : await discoverAuthorizationServer(issuer).catch(() => null) |
| 194 | |
| 195 | const resolved = { |
| 196 | mcpUrl, |
| 197 | issuer, |
| 198 | scope: scope || env.AITOEARN_OAUTH_SCOPE || (prm?.scopesSupported?.length ? prm.scopesSupported.join(' ') : ''), |
| 199 | authorizationEndpoint: explicit.authorizationEndpoint || as?.authorizationEndpoint || '', |
| 200 | tokenEndpoint: explicit.tokenEndpoint || as?.tokenEndpoint || '', |
| 201 | registrationEndpoint: explicit.registrationEndpoint || as?.registrationEndpoint || '', |
| 202 | deviceAuthorizationEndpoint: |
| 203 | explicit.deviceAuthorizationEndpoint || as?.deviceAuthorizationEndpoint || '', |
| 204 | tokenEndpointAuthMethods: as?.tokenEndpointAuthMethods || [], |
| 205 | codeChallengeMethods: as?.codeChallengeMethods || [], |
| 206 | discovered: Boolean(as || prm), |
| 207 | } |
| 208 | |
| 209 | if (!resolved.tokenEndpoint) { |
| 210 | throw new OAuthError( |
| 211 | `未发现 OAuth 授权服务器(${issuer})。` + |
| 212 | '请确认该站点已开启 MCP OAuth,或通过 AITOEARN_OAUTH_AUTHORIZE_URL / AITOEARN_OAUTH_TOKEN_URL 显式指定端点。', |
| 213 | { code: 'discovery_failed' }, |
| 214 | ) |
| 215 | } |
| 216 | return resolved |
| 217 | } |
| 218 | |
| 219 | /* ------------------------------------------------------- client metadata --- */ |
| 220 | |
| 221 | function basicAuth(clientId, clientSecret) { |
| 222 | return 'Basic ' + Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString('base64') |
| 223 | } |
| 224 | |
| 225 | function tokenRequestHeaders({ clientId, clientSecret }) { |
| 226 | if (!clientSecret) return {} |
| 227 | if (process.env.AITOEARN_OAUTH_TOKEN_AUTH === 'client_secret_basic') { |
| 228 | return { Authorization: basicAuth(clientId, clientSecret) } |
| 229 | } |
| 230 | return {} |
| 231 | } |
| 232 | |
| 233 | /** |
| 234 | * Register a public client with dynamic client registration (RFC 7591). |
| 235 | * Falls back to `AITOEARN_OAUTH_CLIENT_ID` when the server has no DCR. |
| 236 | */ |
| 237 | export async function registerClient(endpoints, { redirectUri, scope, clientName }) { |
| 238 | const envClientId = process.env.AITOEARN_OAUTH_CLIENT_ID |
| 239 | if (envClientId) { |
| 240 | return { clientId: envClientId, clientSecret: process.env.AITOEARN_OAUTH_CLIENT_SECRET || '' } |
| 241 | } |
| 242 | if (!endpoints.registrationEndpoint) { |
| 243 | throw new OAuthError( |
| 244 | '授权服务器未提供动态客户端注册,且未设置 AITOEARN_OAUTH_CLIENT_ID。请先在 AiToEarn 创建 OAuth 客户端并设置该环境变量。', |
| 245 | { code: 'client_registration_unavailable' }, |
| 246 | ) |
| 247 | } |
| 248 | // Only request the device-code grant when the server actually offers device |
| 249 | // flow; strict servers reject unknown grant types. |
| 250 | const grantTypes = ['authorization_code', 'refresh_token'] |
| 251 | if (endpoints.deviceAuthorizationEndpoint) { |
| 252 | grantTypes.push('urn:ietf:params:oauth:grant-type:device_code') |
| 253 | } |
| 254 | const body = { |
| 255 | client_name: clientName || 'DeepSeek Harness (AiToEarn)', |
| 256 | redirect_uris: [redirectUri], |
| 257 | grant_types: grantTypes, |
| 258 | response_types: ['code'], |
| 259 | token_endpoint_auth_method: 'none', |
| 260 | ...(scope ? { scope } : {}), |
| 261 | } |
| 262 | const { res, text, json } = await fetchJson(endpoints.registrationEndpoint, { |
| 263 | method: 'POST', |
| 264 | headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, |
| 265 | body: JSON.stringify(body), |
| 266 | }) |
| 267 | if (!res.ok || !json?.client_id) { |
| 268 | throw new OAuthError(`客户端注册失败(HTTP ${res.status}):${text.slice(0, 300)}`, { |
| 269 | code: 'client_registration_failed', |
| 270 | }) |
| 271 | } |
| 272 | return { |
| 273 | clientId: json.client_id, |
| 274 | clientSecret: json.client_secret || '', |
| 275 | tokenEndpointAuthMethod: json.token_endpoint_auth_method || 'none', |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | /* ----------------------------------------------------------------- tokens -- */ |
| 280 | |
| 281 | function expiresAtFrom(tokens) { |
| 282 | const expiresIn = Number(tokens?.expires_in) |
| 283 | return Number.isFinite(expiresIn) && expiresIn > 0 ? Date.now() + expiresIn * 1000 : 0 |
| 284 | } |
| 285 | |
| 286 | async function postToken(endpoints, record, params) { |
| 287 | const body = new URLSearchParams(params) |
| 288 | if (record.clientSecret && !body.has('client_secret')) body.set('client_secret', record.clientSecret) |
| 289 | const { res, text, json } = await fetchJson(endpoints.tokenEndpoint, { |
| 290 | method: 'POST', |
| 291 | headers: { |
| 292 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 293 | Accept: 'application/json', |
| 294 | ...tokenRequestHeaders(record), |
| 295 | }, |
| 296 | body: body.toString(), |
| 297 | }, TOKEN_TIMEOUT_MS) |
| 298 | if (!res.ok || !json?.access_token) { |
| 299 | const error = json?.error || `HTTP ${res.status}` |
| 300 | const description = json?.error_description ? `: ${json.error_description}` : '' |
| 301 | throw new OAuthError(`令牌请求失败(${error}${description})`, { code: 'token_request_failed' }) |
| 302 | } |
| 303 | return json |
| 304 | } |
| 305 | |
| 306 | export async function refreshRecord(url, record) { |
| 307 | if (!record?.refreshToken || !record.tokenEndpoint) return null |
| 308 | const tokens = await postToken( |
| 309 | { tokenEndpoint: record.tokenEndpoint }, |
| 310 | record, |
| 311 | { grant_type: 'refresh_token', refresh_token: record.refreshToken, ...(record.scope ? { scope: record.scope } : {}) }, |
| 312 | ) |
| 313 | const next = { |
| 314 | ...record, |
| 315 | accessToken: tokens.access_token, |
| 316 | refreshToken: tokens.refresh_token || record.refreshToken, |
| 317 | tokenType: tokens.token_type || 'Bearer', |
| 318 | scope: tokens.scope || record.scope || '', |
| 319 | expiresAt: expiresAtFrom(tokens), |
| 320 | refreshedAt: Date.now(), |
| 321 | } |
| 322 | saveRecord(url, next) |
| 323 | return next |
| 324 | } |
| 325 | |
| 326 | /** |
| 327 | * Return a usable bearer token for `url`, refreshing when it is close to |
| 328 | * expiry. Returns null when the user has not authorized yet. |
| 329 | */ |
| 330 | export async function getAccessToken(url, { forceRefresh = false } = {}) { |
| 331 | const record = readRecord(url) |
| 332 | if (!record?.accessToken && !record?.refreshToken) return null |
| 333 | |
| 334 | const expiring = forceRefresh |
| 335 | || !record.accessToken |
| 336 | || (record.expiresAt > 0 && record.expiresAt - REFRESH_SKEW_MS <= Date.now()) |
| 337 | if (!expiring) return record.accessToken |
| 338 | |
| 339 | try { |
| 340 | const refreshed = await refreshRecord(url, record) |
| 341 | if (refreshed) return refreshed.accessToken |
| 342 | } catch { |
| 343 | if (!forceRefresh) return record.accessToken |
| 344 | } |
| 345 | return forceRefresh ? null : record.accessToken |
| 346 | } |
| 347 | |
| 348 | /* -------------------------------------------------------------- device ----- */ |
| 349 | |
| 350 | function sleep(ms) { |
| 351 | return new Promise((resolve) => setTimeout(resolve, ms)) |
| 352 | } |
| 353 | |
| 354 | async function deviceFlow(endpoints, client, { scope, mcpUrl, onPrompt }) { |
| 355 | if (!endpoints.deviceAuthorizationEndpoint) { |
| 356 | throw new OAuthError('授权服务器未提供设备码端点', { code: 'device_flow_unavailable' }) |
| 357 | } |
| 358 | const body = new URLSearchParams({ |
| 359 | client_id: client.clientId, |
| 360 | ...(scope ? { scope } : {}), |
| 361 | ...(mcpUrl ? { resource: mcpUrl } : {}), |
| 362 | }) |
| 363 | const { res, text, json } = await fetchJson(endpoints.deviceAuthorizationEndpoint, { |
| 364 | method: 'POST', |
| 365 | headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, |
| 366 | body: body.toString(), |
| 367 | }) |
| 368 | if (!res.ok || !json?.device_code) { |
| 369 | throw new OAuthError(`设备码申请失败(HTTP ${res.status}):${text.slice(0, 200)}`, { |
| 370 | code: 'device_flow_failed', |
| 371 | }) |
| 372 | } |
| 373 | |
| 374 | onPrompt( |
| 375 | `请在浏览器打开 ${json.verification_uri || json.verification_url}` + |
| 376 | (json.verification_uri_complete ? `\n或直接打开:${json.verification_uri_complete}` : '') + |
| 377 | `\n并输入代码:${json.user_code}`, |
| 378 | ) |
| 379 | |
| 380 | const intervalMs = Math.max(1, Number(json.interval) || DEVICE_FLOW_DEFAULT_INTERVAL_S) * 1000 |
| 381 | const deadline = Date.now() + (Number(json.expires_in) || DEVICE_FLOW_DEFAULT_TIMEOUT_S) * 1000 |
| 382 | let wait = intervalMs |
| 383 | |
| 384 | while (Date.now() < deadline) { |
| 385 | await sleep(wait) |
| 386 | const { res: pollRes, json: poll } = await fetchJson(endpoints.tokenEndpoint, { |
| 387 | method: 'POST', |
| 388 | headers: { |
| 389 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 390 | Accept: 'application/json', |
| 391 | ...tokenRequestHeaders(client), |
| 392 | }, |
| 393 | body: new URLSearchParams({ |
| 394 | grant_type: 'urn:ietf:params:oauth:grant-type:device_code', |
| 395 | device_code: json.device_code, |
| 396 | client_id: client.clientId, |
| 397 | }).toString(), |
| 398 | }, TOKEN_TIMEOUT_MS) |
| 399 | |
| 400 | if (pollRes.ok && poll?.access_token) return poll |
| 401 | if (poll?.error === 'authorization_pending') continue |
| 402 | if (poll?.error === 'slow_down') { wait += 5000; continue } |
| 403 | if (poll?.error === 'access_denied') { |
| 404 | throw new OAuthError('用户拒绝了授权', { code: 'access_denied' }) |
| 405 | } |
| 406 | if (poll?.error === 'expired_token') { |
| 407 | throw new OAuthError('设备码已过期,请重新登录', { code: 'expired_token' }) |
| 408 | } |
| 409 | if (poll?.error) { |
| 410 | throw new OAuthError(`设备码轮询失败:${poll.error}`, { code: 'device_flow_failed' }) |
| 411 | } |
| 412 | } |
| 413 | throw new OAuthError('设备码授权超时,请重试', { code: 'device_flow_timeout' }) |
| 414 | } |
| 415 | |
| 416 | /* ------------------------------------------------------------- loopback ---- */ |
| 417 | |
| 418 | function pkcePair() { |
| 419 | const verifier = randomBytes(32).toString('base64url') |
| 420 | const challenge = createHash('sha256').update(verifier).digest('base64url') |
| 421 | return { verifier, challenge } |
| 422 | } |
| 423 | |
| 424 | function openBrowser(url) { |
| 425 | if (process.env.AITOEARN_OAUTH_OPEN_BROWSER === '0') return |
| 426 | const platform = process.platform |
| 427 | const [cmd, args] = platform === 'darwin' |
| 428 | ? ['open', [url]] |
| 429 | : platform === 'win32' |
| 430 | ? ['cmd', ['/c', 'start', '', url]] |
| 431 | : ['xdg-open', [url]] |
| 432 | try { |
| 433 | const child = spawn(cmd, args, { detached: true, stdio: 'ignore' }) |
| 434 | child.unref() |
| 435 | } catch { /* user can copy the URL manually */ } |
| 436 | } |
| 437 | |
| 438 | async function loopbackFlow(endpoints, { scope, mcpUrl, onPrompt }) { |
| 439 | if (!endpoints.authorizationEndpoint) { |
| 440 | throw new OAuthError('授权服务器未提供授权端点', { code: 'missing_authorization_endpoint' }) |
| 441 | } |
| 442 | const { verifier, challenge } = pkcePair() |
| 443 | const state = randomBytes(24).toString('base64url') |
| 444 | const callbackPort = Number(process.env.AITOEARN_OAUTH_CALLBACK_PORT ?? DEFAULT_CALLBACK_PORT) || 0 |
| 445 | |
| 446 | const server = createServer() |
| 447 | let authTimer = null |
| 448 | const codePromise = new Promise((resolve, reject) => { |
| 449 | authTimer = setTimeout(() => reject(new OAuthError('授权回调超时', { code: 'authorization_timeout' })), AUTH_TIMEOUT_MS) |
| 450 | server.on('request', (req, res) => { |
| 451 | const requestUrl = new URL(req.url || '/', 'http://127.0.0.1') |
| 452 | if (requestUrl.pathname !== '/oauth/callback') { |
| 453 | res.writeHead(404).end('Not found') |
| 454 | return |
| 455 | } |
| 456 | const error = requestUrl.searchParams.get('error') |
| 457 | const code = requestUrl.searchParams.get('code') |
| 458 | const receivedState = requestUrl.searchParams.get('state') |
| 459 | res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end( |
| 460 | error |
| 461 | ? '<!doctype html><meta charset="utf-8"><title>Authorization failed</title><p>Authorization failed. Return to DeepSeek Harness.</p>' |
| 462 | : '<!doctype html><meta charset="utf-8"><title>Authorized</title><p>Authorization complete. You may close this window.</p>', |
| 463 | ) |
| 464 | clearTimeout(authTimer) |
| 465 | if (error) reject(new OAuthError(`授权被拒绝:${error}`, { code: 'access_denied' })) |
| 466 | else if (receivedState !== state) reject(new OAuthError('OAuth state 校验失败', { code: 'state_mismatch' })) |
| 467 | else if (!code) reject(new OAuthError('授权回调缺少 code', { code: 'missing_code' })) |
| 468 | else resolve(code) |
| 469 | }) |
| 470 | }) |
| 471 | |
| 472 | await new Promise((resolve, reject) => { |
| 473 | server.once('error', reject) |
| 474 | server.listen(callbackPort, '127.0.0.1', resolve) |
| 475 | }) |
| 476 | const address = server.address() |
| 477 | const redirectUri = `http://127.0.0.1:${address.port}/oauth/callback` |
| 478 | |
| 479 | try { |
| 480 | // The loopback port is known only now, so this is where a public client is |
| 481 | // registered (or an explicitly configured client is used as-is). |
| 482 | let client |
| 483 | if (process.env.AITOEARN_OAUTH_CLIENT_ID) { |
| 484 | client = { |
| 485 | clientId: process.env.AITOEARN_OAUTH_CLIENT_ID, |
| 486 | clientSecret: process.env.AITOEARN_OAUTH_CLIENT_SECRET || '', |
| 487 | redirectUri, |
| 488 | } |
| 489 | } else { |
| 490 | const registered = await registerClient(endpoints, { |
| 491 | redirectUri, |
| 492 | scope, |
| 493 | clientName: 'DeepSeek Harness (AiToEarn)', |
| 494 | }) |
| 495 | client = { ...registered, redirectUri } |
| 496 | } |
| 497 | |
| 498 | const authUrl = new URL(endpoints.authorizationEndpoint) |
| 499 | authUrl.searchParams.set('response_type', 'code') |
| 500 | authUrl.searchParams.set('client_id', client.clientId) |
| 501 | authUrl.searchParams.set('redirect_uri', redirectUri) |
| 502 | authUrl.searchParams.set('state', state) |
| 503 | authUrl.searchParams.set('code_challenge', challenge) |
| 504 | authUrl.searchParams.set('code_challenge_method', 'S256') |
| 505 | if (scope) authUrl.searchParams.set('scope', scope) |
| 506 | if (mcpUrl) authUrl.searchParams.set('resource', mcpUrl) |
| 507 | |
| 508 | onPrompt(`请在浏览器完成授权:\n${authUrl.toString()}`) |
| 509 | openBrowser(authUrl.toString()) |
| 510 | |
| 511 | const code = await codePromise |
| 512 | const tokens = await postToken( |
| 513 | endpoints, |
| 514 | client, |
| 515 | { |
| 516 | grant_type: 'authorization_code', |
| 517 | code, |
| 518 | redirect_uri: redirectUri, |
| 519 | client_id: client.clientId, |
| 520 | code_verifier: verifier, |
| 521 | ...(mcpUrl ? { resource: mcpUrl } : {}), |
| 522 | }, |
| 523 | ) |
| 524 | return { tokens, client, redirectUri } |
| 525 | } finally { |
| 526 | if (authTimer) clearTimeout(authTimer) |
| 527 | await new Promise((resolve) => server.close(resolve)) |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | /* ----------------------------------------------------------------- login --- */ |
| 532 | |
| 533 | /** |
| 534 | * Run the interactive OAuth login and persist the token record. |
| 535 | * Prefers device flow when the authorization server advertises it. |
| 536 | */ |
| 537 | export async function login({ site, url, scope, onPrompt = () => {} } = {}) { |
| 538 | const base = site ? SITES[site] : null |
| 539 | if (site && !base) throw new OAuthError('未知站点,可选 cn(https://aitoearn.cn)或 ai(https://aitoearn.ai)', { code: 'bad_site' }) |
| 540 | if (!url && !base) throw new OAuthError('请指定站点 cn 或 ai', { code: 'site_required' }) |
| 541 | const mcpUrl = url || `${base}${DEFAULT_MCP_PATH}` |
| 542 | const endpoints = await resolveEndpoints({ url: mcpUrl, scope }) |
| 543 | const effectiveScope = scope || endpoints.scope || '' |
| 544 | |
| 545 | let flow = 'authorization_code' |
| 546 | let client |
| 547 | let tokens |
| 548 | |
| 549 | if (endpoints.deviceAuthorizationEndpoint) { |
| 550 | flow = 'device_code' |
| 551 | client = process.env.AITOEARN_OAUTH_CLIENT_ID |
| 552 | ? { |
| 553 | clientId: process.env.AITOEARN_OAUTH_CLIENT_ID, |
| 554 | clientSecret: process.env.AITOEARN_OAUTH_CLIENT_SECRET || '', |
| 555 | } |
| 556 | : await registerClient(endpoints, { |
| 557 | redirectUri: 'http://127.0.0.1/oauth/callback', |
| 558 | scope: effectiveScope, |
| 559 | clientName: 'DeepSeek Harness (AiToEarn)', |
| 560 | }) |
| 561 | tokens = await deviceFlow(endpoints, client, { scope: effectiveScope, mcpUrl, onPrompt }) |
| 562 | } else { |
| 563 | const result = await loopbackFlow(endpoints, { |
| 564 | scope: effectiveScope, |
| 565 | mcpUrl, |
| 566 | onPrompt, |
| 567 | }) |
| 568 | tokens = result.tokens |
| 569 | client = result.client |
| 570 | } |
| 571 | |
| 572 | const record = { |
| 573 | issuer: endpoints.issuer, |
| 574 | mcpUrl, |
| 575 | flow, |
| 576 | clientId: client.clientId, |
| 577 | clientSecret: client.clientSecret || '', |
| 578 | tokenEndpoint: endpoints.tokenEndpoint, |
| 579 | authorizationEndpoint: endpoints.authorizationEndpoint || '', |
| 580 | deviceAuthorizationEndpoint: endpoints.deviceAuthorizationEndpoint || '', |
| 581 | scope: tokens.scope || effectiveScope, |
| 582 | tokenType: tokens.token_type || 'Bearer', |
| 583 | accessToken: tokens.access_token, |
| 584 | refreshToken: tokens.refresh_token || '', |
| 585 | expiresAt: expiresAtFrom(tokens), |
| 586 | createdAt: Date.now(), |
| 587 | } |
| 588 | saveRecord(mcpUrl, record) |
| 589 | return record |
| 590 | } |
| 591 | |
| 592 | /** Delete the stored record for a site (or an explicit MCP URL). */ |
| 593 | export function logout({ site = 'cn', url } = {}) { |
| 594 | const base = SITES[site] |
| 595 | if (!url && !base) throw new OAuthError('未知站点,可选 cn(https://aitoearn.cn)或 ai(https://aitoearn.ai)', { code: 'bad_site' }) |
| 596 | removeRecord(url || `${base}${DEFAULT_MCP_PATH}`) |
| 597 | } |
| 598 | |
| 599 | /** Non-secret snapshot for `status`. */ |
| 600 | export function describeRecord({ site = 'cn', url } = {}) { |
| 601 | const base = SITES[site] |
| 602 | const mcpUrl = url || `${base}${DEFAULT_MCP_PATH}` |
| 603 | const record = readRecord(mcpUrl) |
| 604 | if (!record) return { mcpUrl, authorized: false } |
| 605 | return { |
| 606 | mcpUrl, |
| 607 | authorized: Boolean(record.accessToken || record.refreshToken), |
| 608 | hasAccessToken: Boolean(record.accessToken), |
| 609 | hasRefreshToken: Boolean(record.refreshToken), |
| 610 | expiresAt: record.expiresAt || 0, |
| 611 | expiresAtIso: record.expiresAt ? new Date(record.expiresAt).toISOString() : '', |
| 612 | scope: record.scope || '', |
| 613 | issuer: record.issuer || '', |
| 614 | mcpEndpoint: record.mcpUrl || mcpUrl, |
| 615 | flow: record.flow || '', |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | /** Live check used by the CLI after login. Never logs the token itself. */ |
| 620 | export async function verifyToken(mcpUrl, token) { |
| 621 | const res = await fetch(mcpUrl, { |
| 622 | method: 'POST', |
| 623 | headers: { |
| 624 | 'Content-Type': 'application/json', |
| 625 | Accept: 'application/json, text/event-stream', |
| 626 | ...(token ? { Authorization: `Bearer ${token}` } : {}), |
| 627 | }, |
| 628 | body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }), |
| 629 | signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS), |
| 630 | }) |
| 631 | const text = await res.text() |
| 632 | const events = parseSse(text) |
| 633 | const payload = events.length ? events[events.length - 1] : safeJson(text) |
| 634 | const tools = Array.isArray(payload?.result?.tools) ? payload.result.tools : [] |
| 635 | return { |
| 636 | ok: res.ok && tools.length > 0, |
| 637 | status: res.status, |
| 638 | toolCount: tools.length, |
| 639 | onlyConnectionHelp: tools.length === 1 && tools[0]?.name === 'aitoearn_connection_help', |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | function safeJson(text) { |
| 644 | try { return JSON.parse(text) } catch { return null } |
| 645 | } |
| 646 | |
| 647 | function parseSse(body) { |
| 648 | const out = [] |
| 649 | for (const block of body.split(/\r?\n\r?\n/)) { |
| 650 | for (const line of block.split(/\r?\n/)) { |
| 651 | if (!line.startsWith('data:')) continue |
| 652 | const data = line.slice(5).trim() |
| 653 | if (!data || data === '[DONE]') continue |
| 654 | const parsed = safeJson(data) |
| 655 | if (parsed && typeof parsed === 'object') out.push(parsed) |
| 656 | } |
| 657 | } |
| 658 | return out |
| 659 | } |
| 660 |