@moxn/mcp-kb 0.3.1 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth.d.ts +12 -67
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +13 -490
- package/dist/auth.js.map +1 -1
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +53 -24
- package/dist/proxy.js.map +1 -1
- package/dist/schema-refresh.d.ts +78 -14
- package/dist/schema-refresh.d.ts.map +1 -1
- package/dist/schema-refresh.js +168 -34
- package/dist/schema-refresh.js.map +1 -1
- package/dist/shared-schema-cache.d.ts +20 -0
- package/dist/shared-schema-cache.d.ts.map +1 -0
- package/dist/shared-schema-cache.js +72 -0
- package/dist/shared-schema-cache.js.map +1 -0
- package/dist/vercel-bypass.d.ts +4 -16
- package/dist/vercel-bypass.d.ts.map +1 -1
- package/dist/vercel-bypass.js +4 -34
- package/dist/vercel-bypass.js.map +1 -1
- package/package.json +6 -3
package/dist/auth.d.ts
CHANGED
|
@@ -1,43 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Authentication module for Moxn MCP KB client.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* The OAuth 2.0 + PKCE implementation and the shared per-workspace credential
|
|
5
|
+
* store live in @moxn/auth (shared with the Moxn CLI so all local Moxn
|
|
6
|
+
* processes coordinate on one token per workspace — see that package's docs
|
|
7
|
+
* for why that sharing is load-bearing). This module keeps the proxy-specific
|
|
8
|
+
* pieces: argv/env parsing, the stderr log prefix, and base-URL construction.
|
|
5
9
|
*/
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
* Useful when the server rejects a token with HTTP 401 (revoked/invalid).
|
|
14
|
-
*/
|
|
15
|
-
forceRefresh?: boolean;
|
|
16
|
-
/**
|
|
17
|
-
* The token the server just refused. Lets a forced refresh tell "my cached
|
|
18
|
-
* token is stale, but a sibling proxy has already put a live one on disk"
|
|
19
|
-
* apart from "the stored token itself is dead" — only the latter may mint.
|
|
20
|
-
* Omitting it forces a mint. See {@link planAuthAction}.
|
|
21
|
-
*/
|
|
22
|
-
rejectedToken?: string | null;
|
|
23
|
-
/**
|
|
24
|
-
* Optional scope override from WWW-Authenticate challenge.
|
|
25
|
-
*/
|
|
26
|
-
oauthScope?: string;
|
|
27
|
-
/**
|
|
28
|
-
* Optional resource metadata URL from WWW-Authenticate challenge.
|
|
29
|
-
*/
|
|
30
|
-
resourceMetadataUrl?: string;
|
|
31
|
-
}
|
|
32
|
-
interface StoredCredentials {
|
|
33
|
-
accessToken: string;
|
|
34
|
-
refreshToken?: string;
|
|
35
|
-
expiresAt: string;
|
|
36
|
-
workspace: string;
|
|
37
|
-
clientId?: string;
|
|
38
|
-
clientSecret?: string;
|
|
39
|
-
tokenEndpoint?: string;
|
|
40
|
-
}
|
|
10
|
+
import { type AuthConfig, type GetAuthOptions as SharedGetAuthOptions } from '@moxn/auth';
|
|
11
|
+
export type { AuthConfig };
|
|
12
|
+
export type GetAuthOptions = Omit<SharedGetAuthOptions, 'workspace' | 'interactive'>;
|
|
13
|
+
/**
|
|
14
|
+
* Parse CLI arguments to extract workspace
|
|
15
|
+
*/
|
|
16
|
+
export declare function parseWorkspace(): string | undefined;
|
|
41
17
|
/**
|
|
42
18
|
* Parse --filesystems CLI argument or MOXN_FILESYSTEMS env var.
|
|
43
19
|
* Returns an array of filesystem slugs, or undefined if not specified.
|
|
@@ -47,36 +23,6 @@ interface StoredCredentials {
|
|
|
47
23
|
* MOXN_FILESYSTEMS=engineering,product
|
|
48
24
|
*/
|
|
49
25
|
export declare function parseFilesystems(): string[] | undefined;
|
|
50
|
-
export type AuthAction = {
|
|
51
|
-
action: 'use-stored';
|
|
52
|
-
accessToken: string;
|
|
53
|
-
} | {
|
|
54
|
-
action: 'refresh';
|
|
55
|
-
} | {
|
|
56
|
-
action: 'reauth';
|
|
57
|
-
};
|
|
58
|
-
/**
|
|
59
|
-
* Decide how to satisfy an auth request, given whatever is on disk right now.
|
|
60
|
-
*
|
|
61
|
-
* Pure so it is unit-testable without a filesystem or a network (same idiom as
|
|
62
|
-
* schema-refresh.ts), and single so the 401 path and the ordinary path cannot
|
|
63
|
-
* drift apart.
|
|
64
|
-
*
|
|
65
|
-
* `rejectedToken` is the token the server just refused, when recovering from a
|
|
66
|
-
* 401. Passing it is what keeps concurrent proxies from invalidating one
|
|
67
|
-
* another: every process for a workspace shares one credentials file and one
|
|
68
|
-
* clientId, and Clerk keeps only the newest access token alive per
|
|
69
|
-
* (clientId, user) — so each mint silently kills every sibling's cached token.
|
|
70
|
-
* If a sibling has already refreshed, the store holds a *different* live token;
|
|
71
|
-
* reuse it rather than minting, and no one else gets invalidated. Minting is
|
|
72
|
-
* reserved for the case where the dead token is the one in the store, which is
|
|
73
|
-
* the only case where nobody else has done the work for us.
|
|
74
|
-
*/
|
|
75
|
-
export declare function planAuthAction(params: {
|
|
76
|
-
stored: StoredCredentials | null;
|
|
77
|
-
rejectedToken?: string | null;
|
|
78
|
-
now?: number;
|
|
79
|
-
}): AuthAction;
|
|
80
26
|
/**
|
|
81
27
|
* Get authentication configuration.
|
|
82
28
|
*
|
|
@@ -92,5 +38,4 @@ export declare function getAuth(options?: GetAuthOptions): Promise<AuthConfig>;
|
|
|
92
38
|
* - Local dev (path-based): http://localhost:3001/{workspace}/api/mcp/http
|
|
93
39
|
*/
|
|
94
40
|
export declare function buildBaseUrl(workspace: string): string;
|
|
95
|
-
export {};
|
|
96
41
|
//# sourceMappingURL=auth.d.ts.map
|
package/dist/auth.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAEL,KAAK,UAAU,EACf,KAAK,cAAc,IAAI,oBAAoB,EAC5C,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,UAAU,EAAE,CAAC;AAE3B,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,oBAAoB,EAAE,WAAW,GAAG,aAAa,CAAC,CAAC;AAErF;;GAEG;AACH,wBAAgB,cAAc,IAAI,MAAM,GAAG,SAAS,CAYnD;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,EAAE,GAAG,SAAS,CAyBvD;AAED;;;;;GAKG;AACH,wBAAsB,OAAO,CAAC,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,UAAU,CAAC,CAkB/E;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAQtD"}
|
package/dist/auth.js
CHANGED
|
@@ -1,30 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Authentication module for Moxn MCP KB client.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* The OAuth 2.0 + PKCE implementation and the shared per-workspace credential
|
|
5
|
+
* store live in @moxn/auth (shared with the Moxn CLI so all local Moxn
|
|
6
|
+
* processes coordinate on one token per workspace — see that package's docs
|
|
7
|
+
* for why that sharing is load-bearing). This module keeps the proxy-specific
|
|
8
|
+
* pieces: argv/env parsing, the stderr log prefix, and base-URL construction.
|
|
5
9
|
*/
|
|
6
|
-
import {
|
|
7
|
-
import { randomBytes, createHash } from 'node:crypto';
|
|
8
|
-
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
9
|
-
import { homedir } from 'node:os';
|
|
10
|
-
import { join } from 'node:path';
|
|
11
|
-
import { vercelBypassHeaders } from './vercel-bypass.js';
|
|
12
|
-
const CREDENTIALS_DIR = join(homedir(), '.moxn');
|
|
13
|
-
const CALLBACK_PORT = 9876; // Port for OAuth callback
|
|
14
|
-
/**
|
|
15
|
-
* Get the credentials file path for a specific workspace.
|
|
16
|
-
* Each workspace gets its own credentials file to support multi-tenant usage.
|
|
17
|
-
*/
|
|
18
|
-
function getCredentialsFile(workspace) {
|
|
19
|
-
// Sanitize workspace name for filename (replace invalid chars)
|
|
20
|
-
const safeWorkspace = workspace.replace(/[^a-zA-Z0-9-_]/g, '_');
|
|
21
|
-
return join(CREDENTIALS_DIR, `credentials-${safeWorkspace}.json`);
|
|
22
|
-
}
|
|
23
|
-
const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;
|
|
10
|
+
import { getAuth as getAuthShared, } from '@moxn/auth';
|
|
24
11
|
/**
|
|
25
12
|
* Parse CLI arguments to extract workspace
|
|
26
13
|
*/
|
|
27
|
-
function parseWorkspace() {
|
|
14
|
+
export function parseWorkspace() {
|
|
28
15
|
const workspaceArg = process.argv.find((arg) => arg.startsWith('--workspace='));
|
|
29
16
|
if (workspaceArg) {
|
|
30
17
|
return workspaceArg.split('=')[1];
|
|
@@ -66,434 +53,6 @@ export function parseFilesystems() {
|
|
|
66
53
|
}
|
|
67
54
|
return undefined;
|
|
68
55
|
}
|
|
69
|
-
/**
|
|
70
|
-
* Generate PKCE code verifier and challenge
|
|
71
|
-
*
|
|
72
|
-
* RFC 7636 specifies:
|
|
73
|
-
* - code_verifier: 43-128 chars from [A-Z, a-z, 0-9, "-", ".", "_", "~"]
|
|
74
|
-
* - base64url uses [A-Z, a-z, 0-9, "-", "_"] which is a valid subset
|
|
75
|
-
*/
|
|
76
|
-
function generatePKCE() {
|
|
77
|
-
// Generate 64 bytes → ~86 base64url chars, then slice to 128 (max allowed)
|
|
78
|
-
// This ensures we always have a valid verifier length (43-128 chars)
|
|
79
|
-
const codeVerifier = randomBytes(64).toString('base64url').slice(0, 128);
|
|
80
|
-
const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url');
|
|
81
|
-
return { codeVerifier, codeChallenge };
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Load stored credentials for a specific workspace
|
|
85
|
-
*/
|
|
86
|
-
async function loadCredentials(workspace) {
|
|
87
|
-
try {
|
|
88
|
-
const credentialsFile = getCredentialsFile(workspace);
|
|
89
|
-
const data = await readFile(credentialsFile, 'utf-8');
|
|
90
|
-
return JSON.parse(data);
|
|
91
|
-
}
|
|
92
|
-
catch {
|
|
93
|
-
return null;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Save credentials to disk for a specific workspace
|
|
98
|
-
*/
|
|
99
|
-
async function saveCredentials(creds) {
|
|
100
|
-
await mkdir(CREDENTIALS_DIR, { recursive: true });
|
|
101
|
-
const credentialsFile = getCredentialsFile(creds.workspace);
|
|
102
|
-
const tempFile = `${credentialsFile}.tmp-${process.pid}-${Date.now()}`;
|
|
103
|
-
await writeFile(tempFile, JSON.stringify(creds, null, 2), { mode: 0o600 });
|
|
104
|
-
await rename(tempFile, credentialsFile);
|
|
105
|
-
console.error(`[moxn-mcp-kb] Credentials saved to ${credentialsFile}`);
|
|
106
|
-
}
|
|
107
|
-
/** Retire tokens this long before their real expiry, to be safe. */
|
|
108
|
-
const EXPIRY_SKEW_MS = 5 * 60 * 1000;
|
|
109
|
-
/**
|
|
110
|
-
* Check if credentials are expired
|
|
111
|
-
*/
|
|
112
|
-
function isExpired(creds, now = Date.now()) {
|
|
113
|
-
const expiresAt = new Date(creds.expiresAt);
|
|
114
|
-
return expiresAt.getTime() - EXPIRY_SKEW_MS < now;
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Decide how to satisfy an auth request, given whatever is on disk right now.
|
|
118
|
-
*
|
|
119
|
-
* Pure so it is unit-testable without a filesystem or a network (same idiom as
|
|
120
|
-
* schema-refresh.ts), and single so the 401 path and the ordinary path cannot
|
|
121
|
-
* drift apart.
|
|
122
|
-
*
|
|
123
|
-
* `rejectedToken` is the token the server just refused, when recovering from a
|
|
124
|
-
* 401. Passing it is what keeps concurrent proxies from invalidating one
|
|
125
|
-
* another: every process for a workspace shares one credentials file and one
|
|
126
|
-
* clientId, and Clerk keeps only the newest access token alive per
|
|
127
|
-
* (clientId, user) — so each mint silently kills every sibling's cached token.
|
|
128
|
-
* If a sibling has already refreshed, the store holds a *different* live token;
|
|
129
|
-
* reuse it rather than minting, and no one else gets invalidated. Minting is
|
|
130
|
-
* reserved for the case where the dead token is the one in the store, which is
|
|
131
|
-
* the only case where nobody else has done the work for us.
|
|
132
|
-
*/
|
|
133
|
-
export function planAuthAction(params) {
|
|
134
|
-
const { stored, rejectedToken = null, now = Date.now() } = params;
|
|
135
|
-
if (!stored) {
|
|
136
|
-
return { action: 'reauth' };
|
|
137
|
-
}
|
|
138
|
-
if (!isExpired(stored, now) && stored.accessToken !== rejectedToken) {
|
|
139
|
-
return { action: 'use-stored', accessToken: stored.accessToken };
|
|
140
|
-
}
|
|
141
|
-
if (stored.refreshToken && stored.tokenEndpoint) {
|
|
142
|
-
return { action: 'refresh' };
|
|
143
|
-
}
|
|
144
|
-
return { action: 'reauth' };
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Refresh access token using stored refresh token
|
|
148
|
-
*/
|
|
149
|
-
async function refreshAccessToken(creds) {
|
|
150
|
-
if (!creds.refreshToken || !creds.tokenEndpoint || !creds.clientId) {
|
|
151
|
-
throw new Error('Missing credentials for token refresh');
|
|
152
|
-
}
|
|
153
|
-
console.error('[moxn-mcp-kb] Refreshing access token...');
|
|
154
|
-
const tokenParams = {
|
|
155
|
-
grant_type: 'refresh_token',
|
|
156
|
-
refresh_token: creds.refreshToken,
|
|
157
|
-
client_id: creds.clientId,
|
|
158
|
-
};
|
|
159
|
-
if (creds.clientSecret) {
|
|
160
|
-
tokenParams.client_secret = creds.clientSecret;
|
|
161
|
-
}
|
|
162
|
-
const response = await fetch(creds.tokenEndpoint, {
|
|
163
|
-
method: 'POST',
|
|
164
|
-
headers: {
|
|
165
|
-
'Content-Type': 'application/x-www-form-urlencoded',
|
|
166
|
-
...vercelBypassHeaders(creds.tokenEndpoint),
|
|
167
|
-
},
|
|
168
|
-
body: new URLSearchParams(tokenParams),
|
|
169
|
-
});
|
|
170
|
-
if (!response.ok) {
|
|
171
|
-
const errorText = await response.text();
|
|
172
|
-
console.error(`[moxn-mcp-kb] Token refresh failed: ${response.status} ${errorText}`);
|
|
173
|
-
throw new Error(`Token refresh failed: ${response.status}`);
|
|
174
|
-
}
|
|
175
|
-
const tokenData = (await response.json());
|
|
176
|
-
const expiresAt = new Date(Date.now() + tokenData.expires_in * 1000).toISOString();
|
|
177
|
-
// Update stored credentials with new tokens
|
|
178
|
-
await saveCredentials({
|
|
179
|
-
...creds,
|
|
180
|
-
accessToken: tokenData.access_token,
|
|
181
|
-
refreshToken: tokenData.refresh_token || creds.refreshToken, // Keep old if not returned
|
|
182
|
-
expiresAt,
|
|
183
|
-
});
|
|
184
|
-
console.error('[moxn-mcp-kb] Token refreshed successfully!');
|
|
185
|
-
return tokenData.access_token;
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* Start callback server and wait for OAuth redirect
|
|
189
|
-
*/
|
|
190
|
-
function waitForCallback() {
|
|
191
|
-
return new Promise((resolve, reject) => {
|
|
192
|
-
let server;
|
|
193
|
-
const timeout = setTimeout(() => {
|
|
194
|
-
server?.close();
|
|
195
|
-
reject(new Error('OAuth callback timed out after 5 minutes'));
|
|
196
|
-
}, 5 * 60 * 1000);
|
|
197
|
-
server = createServer((req, res) => {
|
|
198
|
-
const url = new URL(req.url || '/', `http://localhost:${CALLBACK_PORT}`);
|
|
199
|
-
if (url.pathname === '/callback') {
|
|
200
|
-
const code = url.searchParams.get('code');
|
|
201
|
-
const state = url.searchParams.get('state');
|
|
202
|
-
const error = url.searchParams.get('error');
|
|
203
|
-
if (error) {
|
|
204
|
-
res.writeHead(400, { 'Content-Type': 'text/html' });
|
|
205
|
-
res.end(`
|
|
206
|
-
<html><body>
|
|
207
|
-
<h1>Authentication Failed</h1>
|
|
208
|
-
<p>Error: ${error}</p>
|
|
209
|
-
<p>You can close this window.</p>
|
|
210
|
-
</body></html>
|
|
211
|
-
`);
|
|
212
|
-
clearTimeout(timeout);
|
|
213
|
-
server.close();
|
|
214
|
-
reject(new Error(`OAuth error: ${error}`));
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
if (code && state) {
|
|
218
|
-
res.writeHead(200, { 'Content-Type': 'text/html' });
|
|
219
|
-
res.end(`
|
|
220
|
-
<html><body>
|
|
221
|
-
<h1>Authentication Successful!</h1>
|
|
222
|
-
<p>You can close this window and return to your terminal.</p>
|
|
223
|
-
<script>window.close();</script>
|
|
224
|
-
</body></html>
|
|
225
|
-
`);
|
|
226
|
-
clearTimeout(timeout);
|
|
227
|
-
server.close();
|
|
228
|
-
resolve({ code, state });
|
|
229
|
-
}
|
|
230
|
-
else {
|
|
231
|
-
res.writeHead(400, { 'Content-Type': 'text/plain' });
|
|
232
|
-
res.end('Missing code or state parameter');
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
else {
|
|
236
|
-
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
|
237
|
-
res.end('Not found');
|
|
238
|
-
}
|
|
239
|
-
});
|
|
240
|
-
server.listen(CALLBACK_PORT, () => {
|
|
241
|
-
console.error(`[moxn-mcp-kb] Callback server listening on port ${CALLBACK_PORT}`);
|
|
242
|
-
});
|
|
243
|
-
server.on('error', (err) => {
|
|
244
|
-
clearTimeout(timeout);
|
|
245
|
-
reject(err);
|
|
246
|
-
});
|
|
247
|
-
});
|
|
248
|
-
}
|
|
249
|
-
/**
|
|
250
|
-
* Discover OAuth endpoints from the protected resource metadata
|
|
251
|
-
*
|
|
252
|
-
* For local development, set MOXN_AUTH_SERVER=https://clerk.moxn.dev to skip
|
|
253
|
-
* resource metadata discovery (which can be slow on localhost).
|
|
254
|
-
*/
|
|
255
|
-
async function discoverOAuthEndpoints(workspace, options = {}) {
|
|
256
|
-
// Allow skipping resource metadata discovery for local dev
|
|
257
|
-
const authServerOverride = process.env.MOXN_AUTH_SERVER;
|
|
258
|
-
let authServer;
|
|
259
|
-
let scopesSupported;
|
|
260
|
-
if (authServerOverride) {
|
|
261
|
-
console.error(`[moxn-mcp-kb] Using auth server from MOXN_AUTH_SERVER: ${authServerOverride}`);
|
|
262
|
-
authServer = authServerOverride;
|
|
263
|
-
}
|
|
264
|
-
else {
|
|
265
|
-
// Build discovery URL based on MOXN_BASE_URL or default to production
|
|
266
|
-
let resourceUrl = options.resourceMetadataUrl;
|
|
267
|
-
if (!resourceUrl) {
|
|
268
|
-
const baseUrl = process.env.MOXN_BASE_URL;
|
|
269
|
-
if (baseUrl) {
|
|
270
|
-
// Local dev: derive discovery URL from base URL
|
|
271
|
-
const url = new URL(baseUrl);
|
|
272
|
-
const resourcePath = url.pathname;
|
|
273
|
-
resourceUrl = `${url.origin}/.well-known/oauth-protected-resource${resourcePath}`;
|
|
274
|
-
}
|
|
275
|
-
else {
|
|
276
|
-
// Production: use subdomain routing
|
|
277
|
-
resourceUrl = `https://${workspace}.moxn.dev/.well-known/oauth-protected-resource/api/mcp/http`;
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
console.error(`[moxn-mcp-kb] Discovering OAuth endpoints from ${resourceUrl}`);
|
|
281
|
-
const resourceRes = await fetch(resourceUrl, {
|
|
282
|
-
headers: vercelBypassHeaders(resourceUrl),
|
|
283
|
-
});
|
|
284
|
-
if (!resourceRes.ok) {
|
|
285
|
-
throw new Error(`Failed to fetch resource metadata: ${resourceRes.status}`);
|
|
286
|
-
}
|
|
287
|
-
const resourceMeta = (await resourceRes.json());
|
|
288
|
-
authServer = resourceMeta.authorization_servers[0];
|
|
289
|
-
if (!authServer) {
|
|
290
|
-
throw new Error('No authorization server found in resource metadata');
|
|
291
|
-
}
|
|
292
|
-
scopesSupported = resourceMeta.scopes_supported;
|
|
293
|
-
}
|
|
294
|
-
const authServerUrl = new URL(authServer);
|
|
295
|
-
const hasPath = authServerUrl.pathname !== '/';
|
|
296
|
-
const path = authServerUrl.pathname.endsWith('/')
|
|
297
|
-
? authServerUrl.pathname.slice(0, -1)
|
|
298
|
-
: authServerUrl.pathname;
|
|
299
|
-
const discoveryCandidates = [];
|
|
300
|
-
const seen = new Set();
|
|
301
|
-
const pushCandidate = (url) => {
|
|
302
|
-
const key = url.toString();
|
|
303
|
-
if (!seen.has(key)) {
|
|
304
|
-
seen.add(key);
|
|
305
|
-
discoveryCandidates.push(url);
|
|
306
|
-
}
|
|
307
|
-
};
|
|
308
|
-
if (hasPath) {
|
|
309
|
-
// Try direct path first for compatibility with some real-world providers.
|
|
310
|
-
pushCandidate(new URL(`${path}/.well-known/oauth-authorization-server`, authServerUrl.origin));
|
|
311
|
-
// RFC 8414 path-insertion style.
|
|
312
|
-
pushCandidate(new URL(`/.well-known/oauth-authorization-server${path}`, authServerUrl.origin));
|
|
313
|
-
// OIDC discovery fallbacks.
|
|
314
|
-
pushCandidate(new URL(`/.well-known/openid-configuration${path}`, authServerUrl.origin));
|
|
315
|
-
pushCandidate(new URL(`${path}/.well-known/openid-configuration`, authServerUrl.origin));
|
|
316
|
-
}
|
|
317
|
-
else {
|
|
318
|
-
pushCandidate(new URL('/.well-known/oauth-authorization-server', authServerUrl.origin));
|
|
319
|
-
pushCandidate(new URL('/.well-known/openid-configuration', authServerUrl.origin));
|
|
320
|
-
}
|
|
321
|
-
// Root fallback for path-based issuers.
|
|
322
|
-
pushCandidate(new URL('/.well-known/oauth-authorization-server', authServerUrl.origin));
|
|
323
|
-
pushCandidate(new URL('/.well-known/openid-configuration', authServerUrl.origin));
|
|
324
|
-
let oauthAsConfig = null;
|
|
325
|
-
let lastError = 'unknown';
|
|
326
|
-
for (const candidate of discoveryCandidates) {
|
|
327
|
-
console.error(`[moxn-mcp-kb] Fetching OAuth AS metadata from ${candidate.toString()}`);
|
|
328
|
-
const res = await fetch(candidate.toString(), {
|
|
329
|
-
headers: {
|
|
330
|
-
Accept: 'application/json',
|
|
331
|
-
...vercelBypassHeaders(candidate.toString()),
|
|
332
|
-
},
|
|
333
|
-
});
|
|
334
|
-
if (!res.ok) {
|
|
335
|
-
lastError = `${res.status} ${res.statusText}`;
|
|
336
|
-
continue;
|
|
337
|
-
}
|
|
338
|
-
const json = (await res.json());
|
|
339
|
-
if (json.authorization_endpoint && json.token_endpoint) {
|
|
340
|
-
oauthAsConfig = {
|
|
341
|
-
authorization_endpoint: json.authorization_endpoint,
|
|
342
|
-
token_endpoint: json.token_endpoint,
|
|
343
|
-
registration_endpoint: json.registration_endpoint,
|
|
344
|
-
};
|
|
345
|
-
break;
|
|
346
|
-
}
|
|
347
|
-
lastError = 'metadata missing required authorization_endpoint or token_endpoint';
|
|
348
|
-
}
|
|
349
|
-
if (!oauthAsConfig) {
|
|
350
|
-
throw new Error(`Failed to discover OAuth authorization server metadata: ${lastError}`);
|
|
351
|
-
}
|
|
352
|
-
return {
|
|
353
|
-
authorizationEndpoint: oauthAsConfig.authorization_endpoint,
|
|
354
|
-
tokenEndpoint: oauthAsConfig.token_endpoint,
|
|
355
|
-
registrationEndpoint: oauthAsConfig.registration_endpoint,
|
|
356
|
-
scopesSupported,
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
/**
|
|
360
|
-
* Register a new OAuth client dynamically (RFC 7591)
|
|
361
|
-
*/
|
|
362
|
-
async function registerClient(registrationEndpoint) {
|
|
363
|
-
console.error('[moxn-mcp-kb] Registering OAuth client dynamically...');
|
|
364
|
-
const clientMetadata = {
|
|
365
|
-
client_name: 'moxn-mcp-kb',
|
|
366
|
-
redirect_uris: [REDIRECT_URI],
|
|
367
|
-
grant_types: ['authorization_code', 'refresh_token'],
|
|
368
|
-
response_types: ['code'],
|
|
369
|
-
token_endpoint_auth_method: 'none', // Public client (PKCE only)
|
|
370
|
-
};
|
|
371
|
-
const res = await fetch(registrationEndpoint, {
|
|
372
|
-
method: 'POST',
|
|
373
|
-
headers: {
|
|
374
|
-
'Content-Type': 'application/json',
|
|
375
|
-
...vercelBypassHeaders(registrationEndpoint),
|
|
376
|
-
},
|
|
377
|
-
body: JSON.stringify(clientMetadata),
|
|
378
|
-
});
|
|
379
|
-
if (!res.ok) {
|
|
380
|
-
const errorText = await res.text();
|
|
381
|
-
throw new Error(`Client registration failed: ${res.status} ${errorText}`);
|
|
382
|
-
}
|
|
383
|
-
const clientInfo = (await res.json());
|
|
384
|
-
console.error(`[moxn-mcp-kb] Client registered: ${clientInfo.client_id}`);
|
|
385
|
-
return {
|
|
386
|
-
clientId: clientInfo.client_id,
|
|
387
|
-
clientSecret: clientInfo.client_secret,
|
|
388
|
-
};
|
|
389
|
-
}
|
|
390
|
-
/**
|
|
391
|
-
* Run the OAuth flow
|
|
392
|
-
*/
|
|
393
|
-
async function runOAuthFlow(workspace, options = {}) {
|
|
394
|
-
console.error('[moxn-mcp-kb] === Starting OAuth flow ===');
|
|
395
|
-
console.error('[moxn-mcp-kb] Step 1: Discovering OAuth endpoints...');
|
|
396
|
-
const { authorizationEndpoint, tokenEndpoint, registrationEndpoint, scopesSupported, } = await discoverOAuthEndpoints(workspace, {
|
|
397
|
-
resourceMetadataUrl: options.resourceMetadataUrl,
|
|
398
|
-
});
|
|
399
|
-
console.error(`[moxn-mcp-kb] Step 1 complete: auth=${authorizationEndpoint}`);
|
|
400
|
-
// Check if we have cached client credentials, otherwise register a new client
|
|
401
|
-
const stored = await loadCredentials(workspace);
|
|
402
|
-
const envClientId = process.env.MOXN_CLIENT_ID;
|
|
403
|
-
const envClientSecret = process.env.MOXN_CLIENT_SECRET;
|
|
404
|
-
let clientId;
|
|
405
|
-
let clientSecret;
|
|
406
|
-
if (envClientId) {
|
|
407
|
-
console.error('[moxn-mcp-kb] Step 2: Using pre-registered client from environment');
|
|
408
|
-
clientId = envClientId;
|
|
409
|
-
clientSecret = envClientSecret;
|
|
410
|
-
}
|
|
411
|
-
else if (stored?.clientId) {
|
|
412
|
-
console.error('[moxn-mcp-kb] Step 2: Using cached client credentials');
|
|
413
|
-
clientId = stored.clientId;
|
|
414
|
-
clientSecret = stored.clientSecret;
|
|
415
|
-
}
|
|
416
|
-
else if (registrationEndpoint) {
|
|
417
|
-
console.error('[moxn-mcp-kb] Step 2: Registering new OAuth client...');
|
|
418
|
-
const clientInfo = await registerClient(registrationEndpoint);
|
|
419
|
-
clientId = clientInfo.clientId;
|
|
420
|
-
clientSecret = clientInfo.clientSecret;
|
|
421
|
-
console.error(`[moxn-mcp-kb] Step 2 complete: clientId=${clientId}`);
|
|
422
|
-
}
|
|
423
|
-
else {
|
|
424
|
-
throw new Error('Authorization server does not expose dynamic client registration and no pre-registered client is configured. Set MOXN_CLIENT_ID (and MOXN_CLIENT_SECRET if required).');
|
|
425
|
-
}
|
|
426
|
-
const { codeVerifier, codeChallenge } = generatePKCE();
|
|
427
|
-
const state = randomBytes(16).toString('hex');
|
|
428
|
-
// Build authorization URL
|
|
429
|
-
const authUrl = new URL(authorizationEndpoint);
|
|
430
|
-
const scope = options.oauthScope?.trim() || scopesSupported?.join(' ') || 'profile email';
|
|
431
|
-
authUrl.searchParams.set('response_type', 'code');
|
|
432
|
-
authUrl.searchParams.set('client_id', clientId);
|
|
433
|
-
authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
|
|
434
|
-
authUrl.searchParams.set('scope', scope);
|
|
435
|
-
authUrl.searchParams.set('state', state);
|
|
436
|
-
authUrl.searchParams.set('code_challenge', codeChallenge);
|
|
437
|
-
authUrl.searchParams.set('code_challenge_method', 'S256');
|
|
438
|
-
console.error('[moxn-mcp-kb] Opening browser for authentication...');
|
|
439
|
-
console.error(`[moxn-mcp-kb] Auth URL: ${authUrl.toString()}`);
|
|
440
|
-
// Dynamic import of 'open' package to launch browser
|
|
441
|
-
try {
|
|
442
|
-
const { default: open } = await import('open');
|
|
443
|
-
const subprocess = await open(authUrl.toString());
|
|
444
|
-
console.error(`[moxn-mcp-kb] Browser launch initiated (pid: ${subprocess.pid ?? 'unknown'})`);
|
|
445
|
-
}
|
|
446
|
-
catch (openError) {
|
|
447
|
-
console.error(`[moxn-mcp-kb] ERROR: Failed to open browser: ${openError instanceof Error ? openError.message : String(openError)}`);
|
|
448
|
-
console.error(`[moxn-mcp-kb] Please open this URL manually: ${authUrl.toString()}`);
|
|
449
|
-
}
|
|
450
|
-
// Wait for callback
|
|
451
|
-
const { code, state: returnedState } = await waitForCallback();
|
|
452
|
-
if (returnedState !== state) {
|
|
453
|
-
throw new Error('State mismatch - possible CSRF attack');
|
|
454
|
-
}
|
|
455
|
-
// Exchange code for tokens
|
|
456
|
-
console.error('[moxn-mcp-kb] Exchanging authorization code for tokens...');
|
|
457
|
-
const tokenParams = {
|
|
458
|
-
grant_type: 'authorization_code',
|
|
459
|
-
client_id: clientId,
|
|
460
|
-
code,
|
|
461
|
-
redirect_uri: REDIRECT_URI,
|
|
462
|
-
code_verifier: codeVerifier,
|
|
463
|
-
};
|
|
464
|
-
// Add client_secret if we have one (confidential client)
|
|
465
|
-
if (clientSecret) {
|
|
466
|
-
tokenParams.client_secret = clientSecret;
|
|
467
|
-
}
|
|
468
|
-
const tokenRes = await fetch(tokenEndpoint, {
|
|
469
|
-
method: 'POST',
|
|
470
|
-
headers: {
|
|
471
|
-
'Content-Type': 'application/x-www-form-urlencoded',
|
|
472
|
-
...vercelBypassHeaders(tokenEndpoint),
|
|
473
|
-
},
|
|
474
|
-
body: new URLSearchParams(tokenParams),
|
|
475
|
-
});
|
|
476
|
-
if (!tokenRes.ok) {
|
|
477
|
-
const errorText = await tokenRes.text();
|
|
478
|
-
throw new Error(`Token exchange failed: ${tokenRes.status} ${errorText}`);
|
|
479
|
-
}
|
|
480
|
-
const tokenData = (await tokenRes.json());
|
|
481
|
-
// Calculate expiry (default to 1 hour if not specified)
|
|
482
|
-
const expiresIn = tokenData.expires_in || 3600;
|
|
483
|
-
const expiresAt = new Date(Date.now() + expiresIn * 1000).toISOString();
|
|
484
|
-
// Save credentials (including client credentials for future use)
|
|
485
|
-
await saveCredentials({
|
|
486
|
-
accessToken: tokenData.access_token,
|
|
487
|
-
refreshToken: tokenData.refresh_token,
|
|
488
|
-
expiresAt,
|
|
489
|
-
workspace,
|
|
490
|
-
clientId,
|
|
491
|
-
clientSecret,
|
|
492
|
-
tokenEndpoint,
|
|
493
|
-
});
|
|
494
|
-
console.error('[moxn-mcp-kb] Authentication successful!');
|
|
495
|
-
return tokenData.access_token;
|
|
496
|
-
}
|
|
497
56
|
/**
|
|
498
57
|
* Get authentication configuration.
|
|
499
58
|
*
|
|
@@ -507,49 +66,13 @@ export async function getAuth(options = {}) {
|
|
|
507
66
|
console.error('Example: moxn-mcp-kb --workspace=smoggy-azure-hummingbird');
|
|
508
67
|
process.exit(1);
|
|
509
68
|
}
|
|
510
|
-
//
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
}
|
|
517
|
-
console.error('[moxn-mcp-kb] Using token from MOXN_TOKEN env var');
|
|
518
|
-
return { token: envToken, workspace };
|
|
519
|
-
}
|
|
520
|
-
// Always re-read the store: every proxy for this workspace writes to this one
|
|
521
|
-
// file, so a sibling may have already minted a token newer than ours.
|
|
522
|
-
const stored = await loadCredentials(workspace);
|
|
523
|
-
// A forced refresh with no known rejected token cannot tell whether the
|
|
524
|
-
// stored token is the dead one, so assume it is — otherwise forceRefresh
|
|
525
|
-
// would no-op and strand the caller on a token the server keeps refusing.
|
|
526
|
-
const rejectedToken = options.forceRefresh
|
|
527
|
-
? (options.rejectedToken ?? stored?.accessToken ?? null)
|
|
528
|
-
: null;
|
|
529
|
-
const plan = planAuthAction({ stored, rejectedToken });
|
|
530
|
-
if (plan.action === 'use-stored') {
|
|
531
|
-
console.error(options.forceRefresh
|
|
532
|
-
? '[moxn-mcp-kb] Server refused our token, but the store already holds a newer one - adopting it'
|
|
533
|
-
: '[moxn-mcp-kb] Using stored credentials');
|
|
534
|
-
return { token: plan.accessToken, workspace };
|
|
535
|
-
}
|
|
536
|
-
if (plan.action === 'refresh' && stored) {
|
|
537
|
-
try {
|
|
538
|
-
const token = await refreshAccessToken(stored);
|
|
539
|
-
return { token, workspace };
|
|
540
|
-
}
|
|
541
|
-
catch {
|
|
542
|
-
console.error('[moxn-mcp-kb] Token refresh failed, falling back to full OAuth flow');
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
else {
|
|
546
|
-
console.error('[moxn-mcp-kb] No usable stored credentials, starting OAuth flow...');
|
|
547
|
-
}
|
|
548
|
-
const token = await runOAuthFlow(workspace, {
|
|
549
|
-
oauthScope: options.oauthScope,
|
|
550
|
-
resourceMetadataUrl: options.resourceMetadataUrl,
|
|
69
|
+
// The proxy is long-lived: its first real request may bootstrap auth via
|
|
70
|
+
// the interactive browser flow (interactive: true, the default).
|
|
71
|
+
return getAuthShared({
|
|
72
|
+
...options,
|
|
73
|
+
workspace,
|
|
74
|
+
log: (message) => console.error(`[moxn-mcp-kb] ${message}`),
|
|
551
75
|
});
|
|
552
|
-
return { token, workspace };
|
|
553
76
|
}
|
|
554
77
|
/**
|
|
555
78
|
* Build the base URL for the MCP API
|