forked from MiniMax-AI/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoauth.ts
More file actions
216 lines (186 loc) · 6.5 KB
/
oauth.ts
File metadata and controls
216 lines (186 loc) · 6.5 KB
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
import type { OAuthTokens } from './types';
import type { Region } from '../config/schema';
import { CLIError } from '../errors/base';
import { ExitCode } from '../errors/codes';
// OAuth configuration — exact endpoints TBD pending MiniMax OAuth docs
export interface OAuthConfig {
clientId: string;
authorizationUrl: string;
tokenUrl: string;
deviceCodeUrl: string;
scopes: string[];
callbackPort: number;
}
const OAUTH_ENDPOINTS = {
global: {
authorizationUrl: 'https://platform.minimax.io/oauth/authorize',
tokenUrl: 'https://api.minimax.io/v1/oauth/token',
deviceCodeUrl: 'https://api.minimax.io/v1/oauth/device/code',
},
cn: {
authorizationUrl: 'https://platform.minimaxi.com/oauth/authorize',
tokenUrl: 'https://api.minimaxi.com/v1/oauth/token',
deviceCodeUrl: 'https://api.minimaxi.com/v1/oauth/device/code',
},
} as const;
export function getOAuthConfig(region: Region, options?: { callbackPort?: number }): OAuthConfig {
const endpoints = OAUTH_ENDPOINTS[region];
return {
clientId: 'mmx-cli',
authorizationUrl: endpoints.authorizationUrl,
tokenUrl: endpoints.tokenUrl,
deviceCodeUrl: endpoints.deviceCodeUrl,
scopes: ['api'],
callbackPort: options?.callbackPort ?? 18991,
};
}
export async function startBrowserFlow(
config: OAuthConfig = getOAuthConfig('global'),
): Promise<OAuthTokens> {
const { randomBytes, createHash } = await import('crypto');
const codeVerifier = randomBytes(32).toString('base64url');
const codeChallenge = createHash('sha256')
.update(codeVerifier)
.digest('base64url');
const state = randomBytes(16).toString('hex');
const params = new URLSearchParams({
client_id: config.clientId,
response_type: 'code',
redirect_uri: `http://localhost:${config.callbackPort}/callback`,
scope: config.scopes.join(' '),
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
const authUrl = `${config.authorizationUrl}?${params}`;
// Open browser
const { exec } = await import('child_process');
const platform = process.platform;
const openCmd = platform === 'darwin' ? 'open' :
platform === 'win32' ? 'start' : 'xdg-open';
exec(`${openCmd} "${authUrl}"`);
process.stderr.write('Opening browser to authenticate with MiniMax...\n');
// Start local server to receive callback
const code = await waitForCallback(config.callbackPort, state);
// Exchange code for tokens
const tokenRes = await fetch(config.tokenUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id: config.clientId,
redirect_uri: `http://localhost:${config.callbackPort}/callback`,
code_verifier: codeVerifier,
}),
});
if (!tokenRes.ok) {
const body = await tokenRes.text();
throw new CLIError(
`OAuth token exchange failed: ${body}`,
ExitCode.AUTH,
);
}
return (await tokenRes.json()) as OAuthTokens;
}
async function waitForCallback(port: number, expectedState: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
const timeout = setTimeout(() => {
server.stop();
reject(new CLIError('OAuth callback timed out.', ExitCode.TIMEOUT));
}, 120_000);
const server = Bun.serve({
port,
fetch(req) {
const url = new URL(req.url);
if (url.pathname !== '/callback') {
return new Response('Not found', { status: 404 });
}
const code = url.searchParams.get('code');
const state = url.searchParams.get('state');
const error = url.searchParams.get('error');
if (error) {
clearTimeout(timeout);
server.stop();
reject(new CLIError(`OAuth error: ${error}`, ExitCode.AUTH));
return new Response(
'<html><body><h1>Authentication Failed</h1><p>You can close this tab.</p></body></html>',
{ headers: { 'Content-Type': 'text/html' } },
);
}
if (!code || state !== expectedState) {
clearTimeout(timeout);
server.stop();
reject(new CLIError('Invalid OAuth callback.', ExitCode.AUTH));
return new Response('Invalid callback', { status: 400 });
}
clearTimeout(timeout);
server.stop();
resolve(code);
return new Response(
'<html><body><h1>Authentication Successful</h1><p>You can close this tab.</p></body></html>',
{ headers: { 'Content-Type': 'text/html' } },
);
},
});
});
}
export async function startDeviceCodeFlow(
config: OAuthConfig = getOAuthConfig('global'),
): Promise<OAuthTokens> {
// Request device code
const codeRes = await fetch(config.deviceCodeUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: config.clientId,
scope: config.scopes.join(' '),
}),
});
if (!codeRes.ok) {
throw new CLIError(
'Failed to start device code flow.',
ExitCode.AUTH,
);
}
const { device_code, user_code, verification_uri, interval, expires_in } =
(await codeRes.json()) as {
device_code: string;
user_code: string;
verification_uri: string;
interval: number;
expires_in: number;
};
process.stderr.write(`\nVisit: ${verification_uri}\n`);
process.stderr.write(`Enter code: ${user_code}\n`);
process.stderr.write('Waiting for authorization...\n');
// Poll for authorization
const deadline = Date.now() + expires_in * 1000;
const pollInterval = (interval || 5) * 1000;
while (Date.now() < deadline) {
await new Promise(r => setTimeout(r, pollInterval));
const tokenRes = await fetch(config.tokenUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
device_code,
client_id: config.clientId,
}),
});
if (tokenRes.ok) {
return (await tokenRes.json()) as OAuthTokens;
}
const err = (await tokenRes.json()) as { error: string };
if (err.error === 'authorization_pending') continue;
if (err.error === 'slow_down') {
await new Promise(r => setTimeout(r, 5000));
continue;
}
throw new CLIError(
`Device code authorization failed: ${err.error}`,
ExitCode.AUTH,
);
}
throw new CLIError('Device code authorization timed out.', ExitCode.TIMEOUT);
}