File size: 17,041 Bytes
f0634fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | import { homedir } from 'node:os';
import { join } from 'node:path';
import { KIMI_CODE_FLOW_CONFIG } from './constants';
import { OAuthUnauthorizedError } from './errors';
import {
assertKimiHostIdentity,
createKimiDefaultHeaders,
type KimiHostIdentity,
} from './identity';
import {
fetchSubmitFeedback,
kimiCodeFeedbackUrl,
type FetchSubmitFeedbackResult,
type SubmitFeedbackBody,
} from './managed-feedback';
import {
fetchCompleteFeedbackUpload,
fetchCreateFeedbackUploadUrl,
type CompleteFeedbackUploadBody,
type CreateFeedbackUploadUrlBody,
type FetchCompleteFeedbackUploadResult,
type FetchCreateFeedbackUploadUrlResult,
} from './managed-feedback-upload';
import {
KIMI_CODE_OAUTH_KEY,
KIMI_CODE_PROVIDER_NAME,
provisionManagedKimiCodeConfig,
resolveKimiCodeOAuthKey,
type ManagedKimiCodeProvisionResult,
type ManagedKimiConfigAdapter,
} from './managed-kimi-code';
import {
fetchManagedUserInfo,
kimiCodeUserInfoUrl,
type ManagedUserInfoResult,
} from './managed-userinfo';
import {
fetchManagedUsage,
kimiCodeUsageUrl,
type FetchManagedUsageError,
type ManagedQuota,
} from './managed-usage';
import { OAuthManager, type LoginOptions, type OAuthManagerOptions } from './oauth-manager';
import { FileTokenStorage, type TokenStorage } from './storage';
import type { OAuthFlowConfig } from './types';
export interface BearerTokenProvider {
getAccessToken(options?: { readonly force?: boolean | undefined }): Promise<string>;
}
export interface AuthProviderStatus {
readonly providerName: string;
readonly hasToken: boolean;
}
export interface AuthStatus {
readonly providers: readonly AuthProviderStatus[];
}
export interface KimiOAuthToolkitOptions<TConfig = unknown> {
readonly identity?: KimiHostIdentity | undefined;
readonly homeDir?: string | undefined;
readonly credentialsDir?: string | undefined;
readonly storage?: TokenStorage | undefined;
readonly flowConfig?: OAuthFlowConfig | undefined;
readonly configAdapter?: ManagedKimiConfigAdapter<TConfig> | undefined;
readonly fetchImpl?: typeof fetch | undefined;
readonly now?: OAuthManagerOptions['now'];
readonly sleep?: OAuthManagerOptions['sleep'];
readonly deviceCodeTimeoutMs?: number | undefined;
readonly refreshThreshold?: OAuthManagerOptions['refreshThreshold'];
readonly onRefresh?: OAuthManagerOptions['onRefresh'];
}
export interface KimiOAuthLoginOptions extends LoginOptions {
readonly provisionConfig?: boolean | undefined;
readonly baseUrl?: string | undefined;
readonly oauthRef?: KimiOAuthTokenRef | undefined;
readonly oauthHost?: string | undefined;
}
export interface KimiOAuthTokenRef {
readonly key?: string | undefined;
readonly oauthHost?: string | undefined;
}
export interface KimiOAuthLoginResult {
readonly providerName: string;
readonly ok: true;
readonly provision?: ManagedKimiCodeProvisionResult | undefined;
}
export interface KimiOAuthLogoutResult {
readonly providerName: string;
readonly ok: true;
}
export type AuthManagedUsageResult =
| {
readonly kind: 'ok';
readonly quota: ManagedQuota;
}
| FetchManagedUsageError;
export type AuthManagedUserInfoResult = ManagedUserInfoResult;
export class KimiOAuthToolkit<TConfig = unknown> {
private readonly homeDir: string;
private readonly identity: KimiHostIdentity | undefined;
private readonly storage: TokenStorage;
private readonly flowConfig: OAuthFlowConfig;
private readonly configAdapter: ManagedKimiConfigAdapter<TConfig> | undefined;
private readonly fetchImpl: typeof fetch | undefined;
private readonly managerOptions: Pick<
OAuthManagerOptions,
'now' | 'sleep' | 'deviceCodeTimeoutMs' | 'refreshThreshold' | 'onRefresh'
>;
private readonly managers = new Map<string, OAuthManager>();
private _identityHeaders: Record<string, string> | undefined;
constructor(options: KimiOAuthToolkitOptions<TConfig>) {
this.identity =
options.identity === undefined ? undefined : assertKimiHostIdentity(options.identity);
this.homeDir = options.homeDir ?? defaultKimiHome();
const credentialsDir = options.credentialsDir ?? join(this.homeDir, 'credentials');
this.storage = options.storage ?? new FileTokenStorage(credentialsDir);
this.flowConfig = options.flowConfig ?? KIMI_CODE_FLOW_CONFIG;
this.configAdapter = options.configAdapter;
this.fetchImpl = options.fetchImpl;
this.managerOptions = {
now: options.now,
sleep: options.sleep,
deviceCodeTimeoutMs: options.deviceCodeTimeoutMs,
refreshThreshold: options.refreshThreshold,
onRefresh: options.onRefresh,
};
}
async status(
providerName?: string | undefined,
oauthRef?: KimiOAuthTokenRef | undefined,
): Promise<AuthStatus> {
const name = providerName ?? KIMI_CODE_PROVIDER_NAME;
const oauthHost = this.oauthHostFor(oauthRef);
const oauthKey = oauthRef?.key ?? this.defaultOAuthKey(undefined, oauthHost);
return {
providers: [
{
providerName: name,
hasToken: await this.managerFor(name, oauthKey, oauthHost).hasToken(),
},
],
};
}
async login(
providerName?: string | undefined,
options: KimiOAuthLoginOptions = {},
): Promise<KimiOAuthLoginResult> {
const name = providerName ?? KIMI_CODE_PROVIDER_NAME;
const oauthHost = this.oauthHostFor(options.oauthRef, options.oauthHost);
const oauthKey = options.oauthRef?.key ?? this.defaultOAuthKey(options.baseUrl, oauthHost);
const manager = this.managerFor(name, oauthKey, oauthHost);
const hadToken = await manager.hasToken();
let usedDeviceLogin = false;
const loginWithDevice = async (): Promise<string> => {
usedDeviceLogin = true;
return (
await manager.login({
signal: options.signal,
onDeviceCode: options.onDeviceCode,
})
).accessToken;
};
let accessToken: string;
if (hadToken) {
try {
accessToken = await manager.ensureFresh();
} catch (error) {
if (!(error instanceof OAuthUnauthorizedError)) throw error;
accessToken = await loginWithDevice();
}
} else {
accessToken = await loginWithDevice();
}
const shouldProvision = options.provisionConfig ?? this.configAdapter !== undefined;
const configAdapter = this.configAdapter;
let provision: ManagedKimiCodeProvisionResult | undefined;
if (shouldProvision && configAdapter !== undefined) {
const provisionWithToken = (token: string): Promise<ManagedKimiCodeProvisionResult> =>
provisionManagedKimiCodeConfig({
accessToken: token,
adapter: configAdapter,
baseUrl: options.baseUrl,
oauthKey,
oauthHost,
preserveDefaultModel: hadToken,
fetchImpl: this.fetchImpl,
headers: this.identityHeaders(),
});
try {
provision = await provisionWithToken(accessToken);
} catch (error) {
if (!(error instanceof OAuthUnauthorizedError) || !hadToken || usedDeviceLogin) {
throw error;
}
let retryToken: string;
try {
retryToken = await manager.ensureFresh({ force: true });
} catch (refreshError) {
if (!(refreshError instanceof OAuthUnauthorizedError)) throw refreshError;
retryToken = await loginWithDevice();
}
try {
provision = await provisionWithToken(retryToken);
} catch (retryError) {
if (!(retryError instanceof OAuthUnauthorizedError) || usedDeviceLogin) {
throw retryError;
}
provision = await provisionWithToken(await loginWithDevice());
}
}
}
return { providerName: name, ok: true, provision };
}
async logout(
providerName?: string | undefined,
oauthRef?: KimiOAuthTokenRef | undefined,
): Promise<KimiOAuthLogoutResult> {
const name = providerName ?? KIMI_CODE_PROVIDER_NAME;
const oauthHost = this.oauthHostFor(oauthRef);
const oauthKey = oauthRef?.key ?? this.defaultOAuthKey(undefined, oauthHost);
await this.managerFor(name, oauthKey, oauthHost).logout();
if (this.configAdapter?.remove !== undefined && name === KIMI_CODE_PROVIDER_NAME) {
const config = await this.configAdapter.read();
this.configAdapter.remove(config);
await this.configAdapter.write(config);
}
return { providerName: name, ok: true };
}
async ensureFresh(
providerName?: string | undefined,
options: {
readonly force?: boolean | undefined;
readonly oauthRef?: KimiOAuthTokenRef | undefined;
} = {},
): Promise<string> {
const name = providerName ?? KIMI_CODE_PROVIDER_NAME;
const oauthHost = this.oauthHostFor(options.oauthRef);
const oauthKey = options.oauthRef?.key ?? this.defaultOAuthKey(undefined, oauthHost);
return this.managerFor(name, oauthKey, oauthHost).ensureFresh(options);
}
async getCachedAccessToken(
providerName?: string,
oauthRef?: KimiOAuthTokenRef,
): Promise<string | undefined> {
const name = providerName ?? KIMI_CODE_PROVIDER_NAME;
const oauthHost = this.oauthHostFor(oauthRef);
const oauthKey = oauthRef?.key ?? this.defaultOAuthKey(undefined, oauthHost);
return this.managerFor(name, oauthKey, oauthHost).getCachedAccessToken();
}
tokenProvider(
providerName?: string | undefined,
oauthRef?: KimiOAuthTokenRef | undefined,
): BearerTokenProvider {
const name = providerName ?? KIMI_CODE_PROVIDER_NAME;
const oauthHost = this.oauthHostFor(oauthRef);
const oauthKey = oauthRef?.key ?? this.defaultOAuthKey(undefined, oauthHost);
return {
getAccessToken: (options) => this.managerFor(name, oauthKey, oauthHost).ensureFresh(options),
};
}
async getManagedUsage(
providerName?: string | undefined,
options: {
readonly oauthRef?: KimiOAuthTokenRef | undefined;
readonly baseUrl?: string | undefined;
} = {},
): Promise<AuthManagedUsageResult> {
const name = providerName ?? KIMI_CODE_PROVIDER_NAME;
try {
const accessToken = await this.ensureFresh(name, {
oauthRef: options.oauthRef ?? this.defaultOAuthRef(options.baseUrl),
});
const result = await fetchManagedUsage(managedUsageUrl(options.baseUrl), accessToken);
if (result.kind === 'error') return result;
return { kind: 'ok', quota: result.quota };
} catch (error) {
return {
kind: 'error',
message: error instanceof Error ? error.message : String(error),
};
}
}
async getManagedUserInfo(
providerName?: string | undefined,
options: {
readonly oauthRef?: KimiOAuthTokenRef | undefined;
readonly baseUrl?: string | undefined;
} = {},
): Promise<AuthManagedUserInfoResult> {
const name = providerName ?? KIMI_CODE_PROVIDER_NAME;
try {
const accessToken = await this.ensureFresh(name, {
oauthRef: options.oauthRef ?? this.defaultOAuthRef(options.baseUrl),
});
const result = await fetchManagedUserInfo(managedUserInfoUrl(options.baseUrl), accessToken);
if (result.kind === 'error') return result;
return { kind: 'ok', userInfo: result.userInfo };
} catch (error) {
return {
kind: 'error',
message: error instanceof Error ? error.message : String(error),
};
}
}
async submitFeedback(
body: SubmitFeedbackBody,
providerName?: string | undefined,
options: {
readonly oauthRef?: KimiOAuthTokenRef | undefined;
readonly baseUrl?: string | undefined;
} = {},
): Promise<FetchSubmitFeedbackResult> {
return this.withAccessToken(
providerName,
options,
(accessToken) => fetchSubmitFeedback(managedFeedbackUrl(options.baseUrl), accessToken, body),
);
}
private async withAccessToken<T>(
providerName: string | undefined,
options: {
readonly oauthRef?: KimiOAuthTokenRef | undefined;
readonly baseUrl?: string | undefined;
},
run: (accessToken: string) => Promise<T>,
): Promise<T | { readonly kind: 'error'; readonly message: string }> {
const name = providerName ?? KIMI_CODE_PROVIDER_NAME;
try {
const accessToken = await this.ensureFresh(name, {
oauthRef: options.oauthRef ?? this.defaultOAuthRef(options.baseUrl),
});
return await run(accessToken);
} catch (error) {
return {
kind: 'error',
message: error instanceof Error ? error.message : String(error),
};
}
}
async createFeedbackUploadUrl(
body: CreateFeedbackUploadUrlBody,
providerName?: string | undefined,
options: {
readonly oauthRef?: KimiOAuthTokenRef | undefined;
readonly baseUrl?: string | undefined;
} = {},
): Promise<FetchCreateFeedbackUploadUrlResult> {
return this.withAccessToken(
providerName,
options,
(accessToken) => fetchCreateFeedbackUploadUrl(accessToken, body, { baseUrl: options.baseUrl }),
);
}
async completeFeedbackUpload(
body: CompleteFeedbackUploadBody,
providerName?: string | undefined,
options: {
readonly oauthRef?: KimiOAuthTokenRef | undefined;
readonly baseUrl?: string | undefined;
} = {},
): Promise<FetchCompleteFeedbackUploadResult> {
return this.withAccessToken(
providerName,
options,
(accessToken) => fetchCompleteFeedbackUpload(accessToken, body, { baseUrl: options.baseUrl }),
);
}
managerFor(
providerName: string,
oauthKey = KIMI_CODE_OAUTH_KEY,
oauthHost?: string | undefined,
): OAuthManager {
const storageName = resolveKimiTokenStorageName({ providerName, oauthKey });
const effectiveOAuthHost = oauthHost ?? this.flowConfig.oauthHost;
const managerKey = `${storageName}\0${normalizeOAuthHost(effectiveOAuthHost)}`;
let manager = this.managers.get(managerKey);
if (manager !== undefined) return manager;
const identity = this.identity;
manager = new OAuthManager({
config: {
...this.flowConfig,
oauthHost: effectiveOAuthHost,
name: storageName,
},
storage: this.storage,
configDir: this.homeDir,
deviceHeaders:
identity === undefined
? undefined
: () =>
// Full identity headers (User-Agent + X-Msh-*): the OAuth host
// reads the platform for the client family and the UA (suffix)
// for the runtime surface, e.g. kimi web's `(web)`.
createKimiDefaultHeaders({
homeDir: this.homeDir,
...identity,
}),
...this.managerOptions,
});
this.managers.set(managerKey, manager);
return manager;
}
private defaultOAuthKey(
baseUrl?: string | undefined,
oauthHost?: string | undefined,
): string {
return resolveKimiCodeOAuthKey({
oauthHost: oauthHost ?? this.flowConfig.oauthHost,
baseUrl,
});
}
private defaultOAuthRef(baseUrl?: string | undefined): KimiOAuthTokenRef {
return {
key: this.defaultOAuthKey(baseUrl, this.flowConfig.oauthHost),
oauthHost: this.flowConfig.oauthHost,
};
}
private oauthHostFor(
oauthRef?: KimiOAuthTokenRef | undefined,
oauthHost?: string | undefined,
): string {
return oauthRef?.oauthHost ?? oauthHost ?? this.flowConfig.oauthHost;
}
private identityHeaders(): Record<string, string> | undefined {
if (this.identity === undefined) return undefined;
this._identityHeaders ??= createKimiDefaultHeaders({
homeDir: this.homeDir,
...this.identity,
});
return this._identityHeaders;
}
}
export function resolveKimiTokenStorageName(input: {
readonly providerName?: string | undefined;
readonly oauthKey?: string | undefined;
}): string {
const key = input.oauthKey ?? KIMI_CODE_OAUTH_KEY;
if (key === 'kimi-code' || key === KIMI_CODE_OAUTH_KEY) return 'kimi-code';
const prefix = 'oauth/';
if (key.startsWith(prefix) && key.slice(prefix.length).length > 0) {
return key.slice(prefix.length);
}
if (!key.includes('/') && !key.startsWith('.')) return key;
throw new Error(`Invalid Kimi OAuth token key: "${key}".`);
}
function defaultKimiHome(): string {
const override = process.env['KIMI_CODE_HOME'];
if (override !== undefined && override.length > 0) return override;
return join(homedir(), '.kimi-code');
}
function managedUsageUrl(baseUrl: string | undefined): string {
if (baseUrl === undefined) return kimiCodeUsageUrl();
return `${baseUrl.replace(/\/+$/, '')}/usages`;
}
function managedUserInfoUrl(baseUrl: string | undefined): string {
if (baseUrl === undefined) return kimiCodeUserInfoUrl();
return `${baseUrl.replace(/\/+$/, '')}/me`;
}
function managedFeedbackUrl(baseUrl: string | undefined): string {
return kimiCodeFeedbackUrl(baseUrl);
}
function normalizeOAuthHost(oauthHost: string): string {
return oauthHost.trim().replace(/\/+$/, '');
}
|