-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathauth.ts
More file actions
249 lines (226 loc) · 8.08 KB
/
Copy pathauth.ts
File metadata and controls
249 lines (226 loc) · 8.08 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
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
/**
* Authentication management commands
*/
import { formatSuccess, formatError, formatOutput, formatInfo, formatWarning } from '../output.js';
import type { CommandOptions } from '../../lib/types.js';
import { deleteAuthProfiles } from '../../lib/auth/profiles.js';
import { performOAuthFlow } from '../../lib/auth/oauth-flow.js';
import { performClientCredentialsFlow } from '../../lib/auth/client-credentials-flow.js';
import { normalizeServerUrl, validateProfileName } from '../../lib/utils.js';
import chalk from 'chalk';
import { DEFAULT_AUTH_PROFILE, DEFAULT_CLIENT_METADATA_URL } from '../../lib/auth/oauth-utils.js';
/**
* Authenticate with a server and create/update auth profile
*/
export async function login(
serverUrl: string,
options: CommandOptions & {
profile?: string;
scope?: string;
clientId?: string;
clientSecret?: string;
clientMetadataUrl?: string | false;
callbackPort?: number;
grant?: string;
tokenEndpoint?: string;
}
): Promise<void> {
try {
const normalizedUrl = normalizeServerUrl(serverUrl);
const profileName = options.profile || DEFAULT_AUTH_PROFILE;
validateProfileName(profileName);
// Normalize grant type — accept both hyphen and underscore variants.
const grantRaw = (options.grant ?? 'authorization-code').toLowerCase().replace(/_/g, '-');
if (grantRaw !== 'authorization-code' && grantRaw !== 'client-credentials') {
throw new Error(
`Invalid --grant "${options.grant}". Expected "authorization-code" or "client-credentials".`
);
}
const useClientCredentials = grantRaw === 'client-credentials';
if (useClientCredentials) {
if (!options.clientId || !options.clientSecret) {
throw new Error('--grant client-credentials requires both --client-id and --client-secret');
}
if (options.clientMetadataUrl) {
throw new Error(
'--client-metadata-url is not supported with --grant client-credentials ' +
'(CIMD applies to interactive authorization-code flow only)'
);
}
if (options.outputMode === 'human') {
console.log(
formatInfo(`Starting OAuth client_credentials authentication for ${normalizedUrl}`)
);
console.log(formatInfo(`Profile: ${chalk.magenta(profileName)}`));
}
const result = await performClientCredentialsFlow({
serverUrl: normalizedUrl,
profileName,
clientId: options.clientId,
clientSecret: options.clientSecret,
...(options.scope !== undefined && { scope: options.scope }),
...(options.tokenEndpoint !== undefined && { tokenEndpoint: options.tokenEndpoint }),
});
if (options.outputMode === 'human') {
console.log(formatSuccess('Authentication successful!'));
console.log(formatInfo(`Profile ${chalk.magenta(profileName)} saved`));
if (result.profile.scopes && result.profile.scopes.length > 0) {
console.log(formatInfo(`Scopes: ${result.profile.scopes.join(', ')}`));
}
} else {
console.log(
formatOutput(
{
profile: profileName,
serverUrl: normalizedUrl,
scopes: result.profile.scopes,
grant: 'client-credentials',
},
'json'
)
);
}
return;
}
if (options.clientSecret && !options.clientId) {
throw new Error('--client-secret requires --client-id');
}
if (options.clientMetadataUrl && options.clientId) {
throw new Error(
'--client-metadata-url cannot be combined with --client-id (they are mutually exclusive ' +
'client registration approaches)'
);
}
if (options.tokenEndpoint) {
throw new Error('--token-endpoint is only supported with --grant client-credentials');
}
// Resolve the effective CIMD URL:
// - --client-id → no CIMD (pre-registered client)
// - --no-client-metadata-url → explicitly disabled (force DCR)
// - --client-metadata-url <url> → user override
// - default → mcpc's hosted CIMD
let resolvedClientMetadataUrl: string | undefined;
if (options.clientId) {
resolvedClientMetadataUrl = undefined;
} else if (options.clientMetadataUrl === false) {
resolvedClientMetadataUrl = undefined;
} else if (typeof options.clientMetadataUrl === 'string') {
resolvedClientMetadataUrl = options.clientMetadataUrl;
} else {
resolvedClientMetadataUrl = DEFAULT_CLIENT_METADATA_URL;
}
if (options.outputMode === 'human') {
console.log(formatInfo(`Starting OAuth authentication for ${normalizedUrl}`));
console.log(formatInfo(`Profile: ${chalk.magenta(profileName)}`));
}
// Perform OAuth flow
const clientCredentials: {
clientId?: string;
clientSecret?: string;
clientMetadataUrl?: string;
} = {};
if (options.clientId) {
clientCredentials.clientId = options.clientId;
}
if (options.clientSecret) {
clientCredentials.clientSecret = options.clientSecret;
}
if (resolvedClientMetadataUrl) {
clientCredentials.clientMetadataUrl = resolvedClientMetadataUrl;
}
const result = await performOAuthFlow(
normalizedUrl,
profileName,
options.scope,
clientCredentials,
options.callbackPort
);
if (options.outputMode === 'human') {
console.log(formatSuccess('Authentication successful!'));
console.log(formatInfo(`Profile ${chalk.magenta(profileName)} saved`));
if (result.profile.scopes && result.profile.scopes.length > 0) {
console.log(formatInfo(`Scopes: ${result.profile.scopes.join(', ')}`));
}
} else {
console.log(
formatOutput(
{
profile: profileName,
serverUrl: normalizedUrl,
scopes: result.profile.scopes,
},
'json'
)
);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
if (options.outputMode === 'human') {
console.error(formatError(errorMessage));
} else {
console.error(formatOutput({ error: errorMessage }, 'json'));
}
process.exit(4); // Authentication error
}
}
/**
* Delete an authentication profile (logout)
*/
export async function logout(
serverUrl: string,
options: CommandOptions & { profile?: string }
): Promise<void> {
try {
const normalizedUrl = normalizeServerUrl(serverUrl);
const profileName = options.profile || DEFAULT_AUTH_PROFILE;
validateProfileName(profileName);
const result = await deleteAuthProfiles(normalizedUrl, profileName);
if (result.count === 0) {
if (options.outputMode === 'human') {
console.error(
formatError(`Profile ${chalk.magenta(profileName)} for ${normalizedUrl} not found`)
);
} else {
console.error(formatOutput({ error: 'Profile not found' }, 'json'));
}
process.exit(1); // Client error
return;
}
if (options.outputMode === 'human') {
console.log(
formatSuccess(`Profile ${chalk.magenta(profileName)} for ${normalizedUrl} deleted`)
);
// Warn about affected sessions
if (result.affectedSessions.length > 0) {
console.log(
formatWarning(
`Warning: ${result.affectedSessions.length} session(s) were using this profile: ${result.affectedSessions.join(', ')}`
)
);
console.log(
formatWarning('These sessions may fail to authenticate. Recreate them or login again.')
);
}
} else {
console.log(
formatOutput(
{
profile: profileName,
serverUrl: normalizedUrl,
deleted: true,
affectedSessions: result.affectedSessions,
},
'json'
)
);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
if (options.outputMode === 'human') {
console.error(formatError(errorMessage));
} else {
console.error(formatOutput({ error: errorMessage }, 'json'));
}
process.exit(1); // Client error
}
}