coremind-tools 1.0.1 → 1.4.0
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/README.md +2 -0
- package/dist/file-target.d.ts +2 -0
- package/dist/file-target.d.ts.map +1 -1
- package/dist/file-target.js +25 -1
- package/dist/file-target.js.map +1 -1
- package/dist/git-adapter.d.ts +1 -1
- package/dist/git-adapter.d.ts.map +1 -1
- package/dist/git-adapter.js +1 -1
- package/dist/git-adapter.js.map +1 -1
- package/dist/host-shell.d.ts +3 -3
- package/dist/host-shell.d.ts.map +1 -1
- package/dist/host-shell.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +6 -2
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +5 -2
- package/dist/internal.js.map +1 -1
- package/dist/linux-sandbox-backend.d.ts +33 -0
- package/dist/linux-sandbox-backend.d.ts.map +1 -0
- package/dist/linux-sandbox-backend.js +119 -0
- package/dist/linux-sandbox-backend.js.map +1 -0
- package/dist/linux-sandbox.d.ts +5 -5
- package/dist/linux-sandbox.d.ts.map +1 -1
- package/dist/linux-sandbox.js +5 -19
- package/dist/linux-sandbox.js.map +1 -1
- package/dist/mcp-authentication-types.d.ts +49 -0
- package/dist/mcp-authentication-types.d.ts.map +1 -0
- package/dist/mcp-authentication-types.js +2 -0
- package/dist/mcp-authentication-types.js.map +1 -0
- package/dist/mcp-authentication.d.ts +26 -0
- package/dist/mcp-authentication.d.ts.map +1 -0
- package/dist/mcp-authentication.js +702 -0
- package/dist/mcp-authentication.js.map +1 -0
- package/dist/mcp-client.d.ts +74 -0
- package/dist/mcp-client.d.ts.map +1 -0
- package/dist/mcp-client.js +399 -0
- package/dist/mcp-client.js.map +1 -0
- package/dist/mcp-http-client.d.ts +18 -0
- package/dist/mcp-http-client.d.ts.map +1 -0
- package/dist/mcp-http-client.js +21 -0
- package/dist/mcp-http-client.js.map +1 -0
- package/dist/mcp-http-fetch.d.ts +54 -0
- package/dist/mcp-http-fetch.d.ts.map +1 -0
- package/dist/mcp-http-fetch.js +603 -0
- package/dist/mcp-http-fetch.js.map +1 -0
- package/dist/mcp-http-transport.d.ts +31 -0
- package/dist/mcp-http-transport.d.ts.map +1 -0
- package/dist/mcp-http-transport.js +179 -0
- package/dist/mcp-http-transport.js.map +1 -0
- package/dist/mcp-stdio-client.d.ts +30 -0
- package/dist/mcp-stdio-client.d.ts.map +1 -0
- package/dist/mcp-stdio-client.js +17 -0
- package/dist/mcp-stdio-client.js.map +1 -0
- package/dist/mcp-stdio-error.d.ts +6 -0
- package/dist/mcp-stdio-error.d.ts.map +1 -0
- package/dist/mcp-stdio-error.js +10 -0
- package/dist/mcp-stdio-error.js.map +1 -0
- package/dist/mcp-stdio-transport.d.ts +41 -0
- package/dist/mcp-stdio-transport.d.ts.map +1 -0
- package/dist/mcp-stdio-transport.js +294 -0
- package/dist/mcp-stdio-transport.js.map +1 -0
- package/dist/platform-execution-environment.d.ts.map +1 -1
- package/dist/platform-execution-environment.js +3 -3
- package/dist/platform-execution-environment.js.map +1 -1
- package/dist/registry.d.ts +4 -0
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +21 -3
- package/dist/registry.js.map +1 -1
- package/dist/script-tool.d.ts +1 -1
- package/dist/script-tool.d.ts.map +1 -1
- package/dist/script-tool.js +4 -2
- package/dist/script-tool.js.map +1 -1
- package/dist/vendor/linux-sandbox/LICENSE +201 -0
- package/dist/vendor/linux-sandbox/backend.d.mts +13 -0
- package/dist/vendor/linux-sandbox/backend.mjs +1264 -0
- package/dist/vendor/linux-sandbox/bin/arm64/apply-seccomp +0 -0
- package/dist/vendor/linux-sandbox/bin/x64/apply-seccomp +0 -0
- package/dist/vendor/linux-sandbox/manifest.json +38 -0
- package/dist/vendor/linux-sandbox/metafile.json +320 -0
- package/dist/vendor/linux-sandbox/musl-COPYRIGHT +193 -0
- package/dist/vendor/windows-mcp/THIRD-PARTY-LICENSES.txt +408 -0
- package/dist/vendor/windows-mcp/guard.dll +0 -0
- package/dist/vendor/windows-mcp/host.exe +0 -0
- package/dist/vendor/windows-mcp/manifest.json +325 -0
- package/dist/vendor/windows-mcp/metafile.json +3894 -0
- package/dist/vendor/windows-mcp/service.mjs +7446 -0
- package/dist/web-tools.d.ts +1 -1
- package/dist/web-tools.d.ts.map +1 -1
- package/dist/web-tools.js +11 -3
- package/dist/web-tools.js.map +1 -1
- package/dist/windows-mcp-job.d.ts +20 -0
- package/dist/windows-mcp-job.d.ts.map +1 -0
- package/dist/windows-mcp-job.js +353 -0
- package/dist/windows-mcp-job.js.map +1 -0
- package/dist/windows-mcp-service-identity.d.ts +6 -0
- package/dist/windows-mcp-service-identity.d.ts.map +1 -0
- package/dist/windows-mcp-service-identity.js +7 -0
- package/dist/windows-mcp-service-identity.js.map +1 -0
- package/dist/windows-mcp-service.d.mts +2 -0
- package/dist/windows-mcp-service.d.mts.map +1 -0
- package/dist/windows-mcp-service.mjs +110 -0
- package/dist/windows-mcp-service.mjs.map +1 -0
- package/package.json +10 -8
|
@@ -0,0 +1,702 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { createMcpHttpFetch } from "./mcp-http-fetch.js";
|
|
4
|
+
import { McpStdioError } from "./mcp-stdio-transport.js";
|
|
5
|
+
import { createPlatformExecutionEnvironment } from "./platform-execution-environment.js";
|
|
6
|
+
const LOGIN_MS = 180_000;
|
|
7
|
+
const REQUEST_MS = 30_000;
|
|
8
|
+
const CLOSE_MS = 5_000;
|
|
9
|
+
const MAX_JSON = 64 * 1024;
|
|
10
|
+
export const MCP_AUTH_MAX_SECRET_LENGTH = 16 * 1024;
|
|
11
|
+
const engines = new WeakMap();
|
|
12
|
+
export function createMcpAuthenticationEngine(options) {
|
|
13
|
+
const engine = new AuthenticationEngine(options);
|
|
14
|
+
const session = Object.freeze({
|
|
15
|
+
login: (server, login) => engine.login(server, login),
|
|
16
|
+
logout: (server) => engine.logout(server),
|
|
17
|
+
close: () => engine.close(),
|
|
18
|
+
});
|
|
19
|
+
engines.set(session, engine);
|
|
20
|
+
return session;
|
|
21
|
+
}
|
|
22
|
+
export function bindMcpAuthentication(session, server, identity, _environment) {
|
|
23
|
+
const engine = engines.get(session);
|
|
24
|
+
if (!engine)
|
|
25
|
+
throw failed();
|
|
26
|
+
return engine.bind(server, identity);
|
|
27
|
+
}
|
|
28
|
+
class AuthenticationEngine {
|
|
29
|
+
options;
|
|
30
|
+
states = new Map();
|
|
31
|
+
namespace;
|
|
32
|
+
store;
|
|
33
|
+
memory = new Map();
|
|
34
|
+
controller = new AbortController();
|
|
35
|
+
owners = new Set();
|
|
36
|
+
callbacks = new Set();
|
|
37
|
+
pending = new Set();
|
|
38
|
+
transactions = new Set();
|
|
39
|
+
environment;
|
|
40
|
+
closing;
|
|
41
|
+
constructor(options) {
|
|
42
|
+
this.options = options;
|
|
43
|
+
if (options.tokenStore && (!options.namespace?.trim() || options.namespace.length > 256))
|
|
44
|
+
throw failed();
|
|
45
|
+
this.namespace = options.namespace ?? randomUUID();
|
|
46
|
+
this.store = options.tokenStore ?? {
|
|
47
|
+
load: async (key) => this.memory.get(key),
|
|
48
|
+
save: async (key, record) => {
|
|
49
|
+
this.memory.set(key, structuredClone(record));
|
|
50
|
+
},
|
|
51
|
+
delete: async (key) => {
|
|
52
|
+
this.memory.delete(key);
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
for (const entry of options.servers) {
|
|
56
|
+
if (this.states.has(entry.server) || !entry.config.oauth)
|
|
57
|
+
throw failed();
|
|
58
|
+
const snapshot = structuredClone(entry);
|
|
59
|
+
const oauth = snapshot.config.oauth;
|
|
60
|
+
const key = createHash("sha256")
|
|
61
|
+
.update(JSON.stringify([
|
|
62
|
+
this.namespace,
|
|
63
|
+
entry.serverIdentity,
|
|
64
|
+
new URL(entry.config.url).href,
|
|
65
|
+
oauth.issuer,
|
|
66
|
+
oauth.clientId,
|
|
67
|
+
[...oauth.scopes].sort(),
|
|
68
|
+
]), "utf8")
|
|
69
|
+
.digest("hex");
|
|
70
|
+
this.states.set(entry.server, {
|
|
71
|
+
entry: snapshot,
|
|
72
|
+
key,
|
|
73
|
+
epoch: 0,
|
|
74
|
+
controller: new AbortController(),
|
|
75
|
+
loaded: false,
|
|
76
|
+
queue: Promise.resolve(),
|
|
77
|
+
generations: 0,
|
|
78
|
+
secrets: new Set(),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
bind(server, identity) {
|
|
83
|
+
const state = this.state(server);
|
|
84
|
+
if (state.entry.serverIdentity !== identity)
|
|
85
|
+
throw failed();
|
|
86
|
+
const epoch = state.epoch;
|
|
87
|
+
const signal = state.controller.signal;
|
|
88
|
+
const assertActive = () => this.active(state, epoch);
|
|
89
|
+
return {
|
|
90
|
+
signal,
|
|
91
|
+
assertActive,
|
|
92
|
+
maxSecretLength: MCP_AUTH_MAX_SECRET_LENGTH,
|
|
93
|
+
authorize: (caller) => this.authorize(state, epoch, caller),
|
|
94
|
+
assertSafe: (text) => {
|
|
95
|
+
assertActive();
|
|
96
|
+
if ([...state.secrets].some((value) => text.includes(value)))
|
|
97
|
+
throw new McpStdioError("mcp_secret_blocked", "MCP 响应包含受保护凭据");
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
login(server, options = {}) {
|
|
102
|
+
if (typeof options.onAuthorization !== "function")
|
|
103
|
+
return Promise.reject(required());
|
|
104
|
+
if (this.options.network === "deny")
|
|
105
|
+
return Promise.reject(failed());
|
|
106
|
+
if (options.signal?.aborted)
|
|
107
|
+
return Promise.reject(aborted());
|
|
108
|
+
let state;
|
|
109
|
+
try {
|
|
110
|
+
state = this.state(server);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
return Promise.reject(error);
|
|
114
|
+
}
|
|
115
|
+
const transactionId = options.transactionId ?? randomUUID();
|
|
116
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/u.test(transactionId) ||
|
|
117
|
+
this.transactions.has(transactionId) ||
|
|
118
|
+
this.transactions.size >= 256 ||
|
|
119
|
+
state.login)
|
|
120
|
+
return Promise.reject(failed());
|
|
121
|
+
this.transactions.add(transactionId);
|
|
122
|
+
this.revoke(state);
|
|
123
|
+
state.generations = 0;
|
|
124
|
+
state.secrets.clear();
|
|
125
|
+
const epoch = state.epoch;
|
|
126
|
+
const transaction = new AbortController();
|
|
127
|
+
const signal = AbortSignal.any([
|
|
128
|
+
transaction.signal,
|
|
129
|
+
this.controller.signal,
|
|
130
|
+
state.controller.signal,
|
|
131
|
+
...(options.signal ? [options.signal] : []),
|
|
132
|
+
]);
|
|
133
|
+
const expiresAt = Date.now() + LOGIN_MS;
|
|
134
|
+
const timer = setTimeout(() => transaction.abort(new McpStdioError("run_timeout", "MCP 授权事务超时")), LOGIN_MS);
|
|
135
|
+
const promise = this.track((async () => {
|
|
136
|
+
try {
|
|
137
|
+
const metadata = await this.discover(state, signal);
|
|
138
|
+
const callback = await this.callback(state, metadata, signal);
|
|
139
|
+
try {
|
|
140
|
+
const { startAuthorization, exchangeAuthorization } = await import("@modelcontextprotocol/client");
|
|
141
|
+
const oauth = state.entry.config.oauth;
|
|
142
|
+
const authorization = await startAuthorization(oauth.issuer, {
|
|
143
|
+
metadata,
|
|
144
|
+
clientInformation: { client_id: oauth.clientId, token_endpoint_auth_method: "none" },
|
|
145
|
+
redirectUrl: callback.url,
|
|
146
|
+
state: callback.state,
|
|
147
|
+
scope: oauth.scopes.join(" "),
|
|
148
|
+
resource: new URL(state.entry.config.url).href,
|
|
149
|
+
});
|
|
150
|
+
if (signal.aborted)
|
|
151
|
+
throw safeError(undefined, signal);
|
|
152
|
+
this.active(state, epoch);
|
|
153
|
+
const request = Object.freeze({
|
|
154
|
+
transactionId,
|
|
155
|
+
server,
|
|
156
|
+
serverIdentity: state.entry.serverIdentity,
|
|
157
|
+
authorizationUrl: authorization.authorizationUrl.href,
|
|
158
|
+
expiresAt: new Date(expiresAt).toISOString(),
|
|
159
|
+
issuer: oauth.issuer,
|
|
160
|
+
clientId: oauth.clientId,
|
|
161
|
+
resource: new URL(state.entry.config.url).href,
|
|
162
|
+
scopes: Object.freeze([...oauth.scopes]),
|
|
163
|
+
});
|
|
164
|
+
const handler = this.track(Promise.resolve().then(() => {
|
|
165
|
+
if (signal.aborted)
|
|
166
|
+
throw safeError(undefined, signal);
|
|
167
|
+
this.active(state, epoch);
|
|
168
|
+
return options.onAuthorization(request, signal);
|
|
169
|
+
}));
|
|
170
|
+
const [code] = await Promise.all([wait(callback.code, signal), wait(handler, signal)]);
|
|
171
|
+
this.active(state, epoch);
|
|
172
|
+
const tokens = await exchangeAuthorization(oauth.issuer, {
|
|
173
|
+
metadata,
|
|
174
|
+
clientInformation: { client_id: oauth.clientId, token_endpoint_auth_method: "none" },
|
|
175
|
+
authorizationCode: code.code,
|
|
176
|
+
iss: code.issuer,
|
|
177
|
+
codeVerifier: authorization.codeVerifier,
|
|
178
|
+
redirectUri: callback.url,
|
|
179
|
+
resource: new URL(state.entry.config.url).href,
|
|
180
|
+
fetchFn: (input, init) => this.request(state, String(input), init, signal, true),
|
|
181
|
+
});
|
|
182
|
+
await this.publish(state, epoch, this.tokenRecord(state, tokens), signal);
|
|
183
|
+
return {
|
|
184
|
+
status: "authorized",
|
|
185
|
+
transactionId,
|
|
186
|
+
server,
|
|
187
|
+
serverIdentity: state.entry.serverIdentity,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
await callback.close();
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
catch (cause) {
|
|
195
|
+
const error = safeError(cause, signal);
|
|
196
|
+
if (state.epoch === epoch)
|
|
197
|
+
this.revoke(state);
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
clearTimeout(timer);
|
|
202
|
+
transaction.abort();
|
|
203
|
+
}
|
|
204
|
+
})());
|
|
205
|
+
state.login = promise;
|
|
206
|
+
void promise
|
|
207
|
+
.finally(() => {
|
|
208
|
+
if (state.login === promise)
|
|
209
|
+
state.login = undefined;
|
|
210
|
+
})
|
|
211
|
+
.catch(() => { });
|
|
212
|
+
return promise;
|
|
213
|
+
}
|
|
214
|
+
async logout(server) {
|
|
215
|
+
const state = this.state(server);
|
|
216
|
+
const transactions = [state.login, state.refresh?.promise].filter((value) => value !== undefined);
|
|
217
|
+
this.revoke(state);
|
|
218
|
+
await this.storage(state, () => this.store.delete(state.key, this.controller.signal), this.controller.signal);
|
|
219
|
+
try {
|
|
220
|
+
await wait(Promise.allSettled(transactions), AbortSignal.timeout(CLOSE_MS));
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
throw storeFailed();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
close() {
|
|
227
|
+
if (this.closing)
|
|
228
|
+
return this.closing;
|
|
229
|
+
this.controller.abort();
|
|
230
|
+
for (const state of this.states.values())
|
|
231
|
+
this.revoke(state);
|
|
232
|
+
this.memory.clear();
|
|
233
|
+
this.closing = (async () => {
|
|
234
|
+
const timer = new AbortController();
|
|
235
|
+
const timeout = setTimeout(() => timer.abort(), CLOSE_MS);
|
|
236
|
+
try {
|
|
237
|
+
const cleanup = await wait(Promise.allSettled([
|
|
238
|
+
...[...this.owners].map((owner) => owner.close()),
|
|
239
|
+
...[...this.callbacks].map((close) => close()),
|
|
240
|
+
]), timer.signal);
|
|
241
|
+
if (cleanup.some((item) => item.status === "rejected"))
|
|
242
|
+
throw storeFailed();
|
|
243
|
+
await wait(Promise.allSettled([...this.pending]), timer.signal);
|
|
244
|
+
if (this.pending.size)
|
|
245
|
+
throw storeFailed();
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
throw storeFailed();
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
clearTimeout(timeout);
|
|
252
|
+
}
|
|
253
|
+
for (const state of this.states.values())
|
|
254
|
+
state.secrets.clear();
|
|
255
|
+
})();
|
|
256
|
+
return this.closing;
|
|
257
|
+
}
|
|
258
|
+
state(server) {
|
|
259
|
+
if (this.closing || this.controller.signal.aborted)
|
|
260
|
+
throw required();
|
|
261
|
+
const state = this.states.get(server);
|
|
262
|
+
if (!state)
|
|
263
|
+
throw failed();
|
|
264
|
+
return state;
|
|
265
|
+
}
|
|
266
|
+
active(state, epoch) {
|
|
267
|
+
if (this.controller.signal.aborted || state.epoch !== epoch || state.controller.signal.aborted)
|
|
268
|
+
throw required();
|
|
269
|
+
}
|
|
270
|
+
revoke(state) {
|
|
271
|
+
state.controller.abort();
|
|
272
|
+
state.epoch++;
|
|
273
|
+
state.controller = new AbortController();
|
|
274
|
+
state.record = undefined;
|
|
275
|
+
state.loaded = true;
|
|
276
|
+
state.loading = undefined;
|
|
277
|
+
state.refresh = undefined;
|
|
278
|
+
}
|
|
279
|
+
async authorize(state, epoch, caller) {
|
|
280
|
+
if (caller?.aborted)
|
|
281
|
+
throw aborted();
|
|
282
|
+
this.active(state, epoch);
|
|
283
|
+
if (this.options.network === "deny")
|
|
284
|
+
throw failed();
|
|
285
|
+
if (!state.loaded) {
|
|
286
|
+
state.loading ??= this.track((async () => {
|
|
287
|
+
const value = await this.storage(state, () => this.store.load(state.key, state.controller.signal), state.controller.signal);
|
|
288
|
+
this.active(state, epoch);
|
|
289
|
+
if (value !== undefined) {
|
|
290
|
+
state.record = this.checkRecord(state, value);
|
|
291
|
+
this.remember(state, state.record);
|
|
292
|
+
}
|
|
293
|
+
state.loaded = true;
|
|
294
|
+
})());
|
|
295
|
+
await wait(state.loading, caller);
|
|
296
|
+
}
|
|
297
|
+
this.active(state, epoch);
|
|
298
|
+
if (caller?.aborted)
|
|
299
|
+
throw aborted();
|
|
300
|
+
const record = state.record;
|
|
301
|
+
if (!record)
|
|
302
|
+
throw required();
|
|
303
|
+
if (record.expiresAt === undefined || record.expiresAt > Date.now())
|
|
304
|
+
return record.accessToken;
|
|
305
|
+
if (!record.refreshToken) {
|
|
306
|
+
this.revoke(state);
|
|
307
|
+
throw required();
|
|
308
|
+
}
|
|
309
|
+
if (!state.refresh) {
|
|
310
|
+
const controller = new AbortController();
|
|
311
|
+
const signal = AbortSignal.any([
|
|
312
|
+
this.controller.signal,
|
|
313
|
+
state.controller.signal,
|
|
314
|
+
controller.signal,
|
|
315
|
+
]);
|
|
316
|
+
const refresh = this.track((async () => {
|
|
317
|
+
try {
|
|
318
|
+
const metadata = state.metadata ?? (await this.discover(state, signal));
|
|
319
|
+
const { refreshAuthorization } = await import("@modelcontextprotocol/client");
|
|
320
|
+
const oauth = state.entry.config.oauth;
|
|
321
|
+
const tokens = await refreshAuthorization(oauth.issuer, {
|
|
322
|
+
metadata,
|
|
323
|
+
clientInformation: { client_id: oauth.clientId, token_endpoint_auth_method: "none" },
|
|
324
|
+
refreshToken: record.refreshToken,
|
|
325
|
+
resource: new URL(state.entry.config.url).href,
|
|
326
|
+
fetchFn: (input, init) => this.request(state, String(input), init, signal, true),
|
|
327
|
+
});
|
|
328
|
+
const next = this.tokenRecord(state, tokens);
|
|
329
|
+
await this.publish(state, epoch, next, signal);
|
|
330
|
+
return next.accessToken;
|
|
331
|
+
}
|
|
332
|
+
catch (cause) {
|
|
333
|
+
const error = safeError(cause, signal);
|
|
334
|
+
if (state.epoch === epoch)
|
|
335
|
+
this.revoke(state);
|
|
336
|
+
throw error;
|
|
337
|
+
}
|
|
338
|
+
})());
|
|
339
|
+
const flight = { controller, promise: refresh, waiters: 0 };
|
|
340
|
+
state.refresh = flight;
|
|
341
|
+
void refresh
|
|
342
|
+
.finally(() => {
|
|
343
|
+
if (state.refresh === flight)
|
|
344
|
+
state.refresh = undefined;
|
|
345
|
+
})
|
|
346
|
+
.catch(() => { });
|
|
347
|
+
}
|
|
348
|
+
const flight = state.refresh;
|
|
349
|
+
flight.waiters++;
|
|
350
|
+
try {
|
|
351
|
+
const token = await wait(flight.promise, caller);
|
|
352
|
+
if (caller?.aborted)
|
|
353
|
+
throw aborted();
|
|
354
|
+
this.active(state, epoch);
|
|
355
|
+
return token;
|
|
356
|
+
}
|
|
357
|
+
finally {
|
|
358
|
+
flight.waiters--;
|
|
359
|
+
if (flight.waiters === 0 && state.refresh === flight)
|
|
360
|
+
flight.controller.abort();
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async publish(state, epoch, record, signal) {
|
|
364
|
+
this.active(state, epoch);
|
|
365
|
+
this.remember(state, record);
|
|
366
|
+
await this.storage(state, () => {
|
|
367
|
+
this.active(state, epoch);
|
|
368
|
+
return this.store.save(state.key, structuredClone(record), signal);
|
|
369
|
+
}, signal);
|
|
370
|
+
this.active(state, epoch);
|
|
371
|
+
state.record = record;
|
|
372
|
+
state.loaded = true;
|
|
373
|
+
}
|
|
374
|
+
storage(state, action, signal) {
|
|
375
|
+
const operation = this.track(state.queue.then(action));
|
|
376
|
+
state.queue = operation.catch(() => { });
|
|
377
|
+
const deadline = new AbortController();
|
|
378
|
+
const timer = setTimeout(() => deadline.abort(), REQUEST_MS);
|
|
379
|
+
return wait(operation, AbortSignal.any([signal, deadline.signal]))
|
|
380
|
+
.catch((cause) => {
|
|
381
|
+
if (signal.aborted)
|
|
382
|
+
throw safeError(cause, signal);
|
|
383
|
+
this.revoke(state);
|
|
384
|
+
throw storeFailed();
|
|
385
|
+
})
|
|
386
|
+
.finally(() => clearTimeout(timer));
|
|
387
|
+
}
|
|
388
|
+
fields(state) {
|
|
389
|
+
const oauth = state.entry.config.oauth;
|
|
390
|
+
return {
|
|
391
|
+
schemaVersion: 1,
|
|
392
|
+
namespace: this.namespace,
|
|
393
|
+
serverIdentity: state.entry.serverIdentity,
|
|
394
|
+
resource: new URL(state.entry.config.url).href,
|
|
395
|
+
issuer: oauth.issuer,
|
|
396
|
+
clientId: oauth.clientId,
|
|
397
|
+
scopes: [...oauth.scopes].sort(),
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
tokenRecord(state, tokens) {
|
|
401
|
+
const scope = tokens.scope === undefined
|
|
402
|
+
? state.entry.config.oauth.scopes
|
|
403
|
+
: tokens.scope.split(" ").filter(Boolean);
|
|
404
|
+
if (new Set(scope).size !== scope.length ||
|
|
405
|
+
scope.some((value) => !state.entry.config.oauth.scopes.includes(value)) ||
|
|
406
|
+
tokens.token_type.toLowerCase() !== "bearer" ||
|
|
407
|
+
!validSecret(tokens.access_token) ||
|
|
408
|
+
(tokens.refresh_token !== undefined && !validSecret(tokens.refresh_token)) ||
|
|
409
|
+
(tokens.expires_in !== undefined &&
|
|
410
|
+
(!Number.isFinite(tokens.expires_in) ||
|
|
411
|
+
tokens.expires_in < 0 ||
|
|
412
|
+
!Number.isFinite(Date.now() + tokens.expires_in * 1000))))
|
|
413
|
+
throw failed();
|
|
414
|
+
return {
|
|
415
|
+
...this.fields(state),
|
|
416
|
+
scopes: [...scope].sort(),
|
|
417
|
+
tokenType: "Bearer",
|
|
418
|
+
accessToken: tokens.access_token,
|
|
419
|
+
...(tokens.refresh_token !== undefined ? { refreshToken: tokens.refresh_token } : {}),
|
|
420
|
+
...(tokens.expires_in !== undefined
|
|
421
|
+
? { expiresAt: Date.now() + tokens.expires_in * 1000 }
|
|
422
|
+
: {}),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
checkRecord(state, record) {
|
|
426
|
+
const expected = this.fields(state);
|
|
427
|
+
if (!record ||
|
|
428
|
+
typeof record !== "object" ||
|
|
429
|
+
record.schemaVersion !== 1 ||
|
|
430
|
+
record.namespace !== expected.namespace ||
|
|
431
|
+
record.serverIdentity !== expected.serverIdentity ||
|
|
432
|
+
record.resource !== expected.resource ||
|
|
433
|
+
record.issuer !== expected.issuer ||
|
|
434
|
+
record.clientId !== expected.clientId ||
|
|
435
|
+
!Array.isArray(record.scopes) ||
|
|
436
|
+
new Set(record.scopes).size !== record.scopes.length ||
|
|
437
|
+
record.scopes.some((scope) => !expected.scopes.includes(scope)) ||
|
|
438
|
+
record.tokenType !== "Bearer" ||
|
|
439
|
+
!validSecret(record.accessToken) ||
|
|
440
|
+
(record.refreshToken !== undefined && !validSecret(record.refreshToken)) ||
|
|
441
|
+
(record.expiresAt !== undefined &&
|
|
442
|
+
(!Number.isFinite(record.expiresAt) || record.expiresAt < 0))) {
|
|
443
|
+
this.revoke(state);
|
|
444
|
+
throw storeFailed();
|
|
445
|
+
}
|
|
446
|
+
return structuredClone(record);
|
|
447
|
+
}
|
|
448
|
+
remember(state, record) {
|
|
449
|
+
if (state.generations >= 32) {
|
|
450
|
+
this.revoke(state);
|
|
451
|
+
throw required();
|
|
452
|
+
}
|
|
453
|
+
state.generations++;
|
|
454
|
+
state.secrets.add(record.accessToken);
|
|
455
|
+
if (record.refreshToken)
|
|
456
|
+
state.secrets.add(record.refreshToken);
|
|
457
|
+
}
|
|
458
|
+
async discover(state, signal) {
|
|
459
|
+
const { discoverOAuthProtectedResourceMetadata, discoverAuthorizationServerMetadata, buildDiscoveryUrls, } = await import("@modelcontextprotocol/client");
|
|
460
|
+
const config = state.entry.config;
|
|
461
|
+
const oauth = config.oauth;
|
|
462
|
+
const resource = new URL(config.url);
|
|
463
|
+
const resourceMetadataUrl = new URL("/.well-known/oauth-protected-resource" +
|
|
464
|
+
(resource.pathname === "/" ? "" : resource.pathname), resource.origin).href;
|
|
465
|
+
const resourceMetadata = await discoverOAuthProtectedResourceMetadata(config.url, { resourceMetadataUrl }, (input, init) => {
|
|
466
|
+
if (new URL(String(input)).href !== resourceMetadataUrl)
|
|
467
|
+
throw failed();
|
|
468
|
+
return this.request(state, String(input), init, signal, false);
|
|
469
|
+
});
|
|
470
|
+
if (resourceMetadata.resource !== resource.href ||
|
|
471
|
+
!resourceMetadata.authorization_servers?.includes(oauth.issuer))
|
|
472
|
+
throw failed();
|
|
473
|
+
const allowed = new Set(buildDiscoveryUrls(oauth.issuer).map(({ url }) => url.href));
|
|
474
|
+
const metadata = await discoverAuthorizationServerMetadata(oauth.issuer, {
|
|
475
|
+
fetchFn: (input, init) => {
|
|
476
|
+
if (!allowed.has(new URL(String(input)).href))
|
|
477
|
+
throw failed();
|
|
478
|
+
return this.request(state, String(input), init, signal, true);
|
|
479
|
+
},
|
|
480
|
+
});
|
|
481
|
+
if (!metadata ||
|
|
482
|
+
metadata.issuer !== oauth.issuer ||
|
|
483
|
+
!metadata.code_challenge_methods_supported?.includes("S256"))
|
|
484
|
+
throw failed();
|
|
485
|
+
for (const endpoint of [metadata.authorization_endpoint, metadata.token_endpoint]) {
|
|
486
|
+
if (!endpoint)
|
|
487
|
+
throw failed();
|
|
488
|
+
this.endpoint(state, endpoint, true);
|
|
489
|
+
}
|
|
490
|
+
state.metadata = metadata;
|
|
491
|
+
return metadata;
|
|
492
|
+
}
|
|
493
|
+
endpoint(state, value, as) {
|
|
494
|
+
const url = new URL(value);
|
|
495
|
+
const origin = new URL(as ? state.entry.config.oauth.issuer : state.entry.config.url).origin;
|
|
496
|
+
if (url.origin !== origin ||
|
|
497
|
+
url.username ||
|
|
498
|
+
url.password ||
|
|
499
|
+
url.search ||
|
|
500
|
+
url.hash ||
|
|
501
|
+
/[\s\\]/u.test(value))
|
|
502
|
+
throw failed();
|
|
503
|
+
return url.href;
|
|
504
|
+
}
|
|
505
|
+
async request(state, url, init, signal, as) {
|
|
506
|
+
const fixed = this.endpoint(state, url, as);
|
|
507
|
+
this.environment ??= createPlatformExecutionEnvironment({ workspaceRoot: process.cwd() });
|
|
508
|
+
const owner = createMcpHttpFetch({
|
|
509
|
+
url: fixed,
|
|
510
|
+
headers: {},
|
|
511
|
+
allowedAddresses: as
|
|
512
|
+
? state.entry.config.oauth.allowedAddresses
|
|
513
|
+
: state.entry.config.allowedAddresses,
|
|
514
|
+
runEnvironment: this.environment.hostNetwork ?? this.environment,
|
|
515
|
+
signal,
|
|
516
|
+
});
|
|
517
|
+
this.owners.add(owner);
|
|
518
|
+
const deadline = new AbortController();
|
|
519
|
+
const timer = setTimeout(() => deadline.abort(), REQUEST_MS);
|
|
520
|
+
try {
|
|
521
|
+
const response = await owner.fetch(fixed, {
|
|
522
|
+
...init,
|
|
523
|
+
...(init?.body !== undefined ? { body: String(init.body) } : {}),
|
|
524
|
+
signal: AbortSignal.any([signal, deadline.signal]),
|
|
525
|
+
});
|
|
526
|
+
const reader = response.body?.getReader();
|
|
527
|
+
const chunks = [];
|
|
528
|
+
let bytes = 0;
|
|
529
|
+
if (reader)
|
|
530
|
+
for (;;) {
|
|
531
|
+
const result = await reader.read();
|
|
532
|
+
if (result.done)
|
|
533
|
+
break;
|
|
534
|
+
bytes += result.value.byteLength;
|
|
535
|
+
if (bytes > MAX_JSON) {
|
|
536
|
+
await reader.cancel();
|
|
537
|
+
throw failed();
|
|
538
|
+
}
|
|
539
|
+
chunks.push(result.value);
|
|
540
|
+
}
|
|
541
|
+
return new Response(Buffer.concat(chunks), {
|
|
542
|
+
status: response.status,
|
|
543
|
+
headers: response.headers,
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
finally {
|
|
547
|
+
clearTimeout(timer);
|
|
548
|
+
await owner.close();
|
|
549
|
+
this.owners.delete(owner);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
async callback(state, metadata, signal) {
|
|
553
|
+
const expectedState = randomBytes(32).toString("base64url");
|
|
554
|
+
const callbackPath = `/callback/${randomUUID()}`;
|
|
555
|
+
const sockets = new Set();
|
|
556
|
+
let callbackUrl = "";
|
|
557
|
+
let consumed = false;
|
|
558
|
+
let accept;
|
|
559
|
+
let reject;
|
|
560
|
+
const code = new Promise((resolve, fail) => {
|
|
561
|
+
accept = resolve;
|
|
562
|
+
reject = fail;
|
|
563
|
+
});
|
|
564
|
+
void code.catch(() => { });
|
|
565
|
+
const listener = createServer({ maxHeaderSize: 8 * 1024, requestTimeout: REQUEST_MS }, (request, response) => {
|
|
566
|
+
try {
|
|
567
|
+
const target = new URL(request.url ?? "", callbackUrl);
|
|
568
|
+
const params = target.searchParams;
|
|
569
|
+
const seen = new Set();
|
|
570
|
+
if (consumed ||
|
|
571
|
+
signal.aborted ||
|
|
572
|
+
request.method !== "GET" ||
|
|
573
|
+
request.headers.host !== new URL(callbackUrl).host ||
|
|
574
|
+
target.origin !== new URL(callbackUrl).origin ||
|
|
575
|
+
target.pathname !== callbackPath ||
|
|
576
|
+
(request.url?.length ?? 0) > 8192)
|
|
577
|
+
throw failed();
|
|
578
|
+
for (const key of params.keys()) {
|
|
579
|
+
if (seen.has(key))
|
|
580
|
+
throw failed();
|
|
581
|
+
seen.add(key);
|
|
582
|
+
}
|
|
583
|
+
const actual = Buffer.from(params.get("state") ?? "", "utf8");
|
|
584
|
+
const expected = Buffer.from(expectedState, "utf8");
|
|
585
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
|
|
586
|
+
throw failed();
|
|
587
|
+
const issuer = params.get("iss");
|
|
588
|
+
if ((issuer !== null && issuer !== state.entry.config.oauth.issuer) ||
|
|
589
|
+
(metadata.authorization_response_iss_parameter_supported === true && issuer === null))
|
|
590
|
+
throw failed();
|
|
591
|
+
if (params.has("error") || !params.get("code"))
|
|
592
|
+
throw failed();
|
|
593
|
+
consumed = true;
|
|
594
|
+
response
|
|
595
|
+
.writeHead(200, {
|
|
596
|
+
"content-type": "text/plain; charset=utf-8",
|
|
597
|
+
"cache-control": "no-store",
|
|
598
|
+
})
|
|
599
|
+
.end("授权已接收,可以关闭此页面。");
|
|
600
|
+
accept({ code: params.get("code"), ...(issuer !== null ? { issuer } : {}) });
|
|
601
|
+
}
|
|
602
|
+
catch {
|
|
603
|
+
consumed = true;
|
|
604
|
+
response.writeHead(400).end("授权响应无效");
|
|
605
|
+
reject(failed());
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
listener.on("connection", (socket) => {
|
|
609
|
+
sockets.add(socket);
|
|
610
|
+
socket.once("close", () => sockets.delete(socket));
|
|
611
|
+
});
|
|
612
|
+
await new Promise((resolve, fail) => {
|
|
613
|
+
listener.once("error", fail);
|
|
614
|
+
listener.listen(0, "127.0.0.1", resolve);
|
|
615
|
+
});
|
|
616
|
+
const address = listener.address();
|
|
617
|
+
if (!address || typeof address === "string")
|
|
618
|
+
throw failed();
|
|
619
|
+
callbackUrl = `http://127.0.0.1:${address.port}${callbackPath}`;
|
|
620
|
+
let closing;
|
|
621
|
+
const cancel = () => reject(safeError(undefined, signal));
|
|
622
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
623
|
+
const close = () => {
|
|
624
|
+
if (closing)
|
|
625
|
+
return closing;
|
|
626
|
+
signal.removeEventListener("abort", cancel);
|
|
627
|
+
for (const socket of sockets)
|
|
628
|
+
socket.destroy();
|
|
629
|
+
closing = new Promise((resolve, fail) => listener.close((error) => (error ? fail(failed()) : resolve())));
|
|
630
|
+
this.callbacks.delete(close);
|
|
631
|
+
return closing;
|
|
632
|
+
};
|
|
633
|
+
this.callbacks.add(close);
|
|
634
|
+
if (signal.aborted) {
|
|
635
|
+
await close();
|
|
636
|
+
throw aborted();
|
|
637
|
+
}
|
|
638
|
+
return { url: callbackUrl, state: expectedState, code, close };
|
|
639
|
+
}
|
|
640
|
+
track(promise) {
|
|
641
|
+
this.pending.add(promise);
|
|
642
|
+
void promise.finally(() => this.pending.delete(promise)).catch(() => { });
|
|
643
|
+
return promise;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
function validSecret(value) {
|
|
647
|
+
return (typeof value === "string" &&
|
|
648
|
+
value.length > 0 &&
|
|
649
|
+
value.length <= MCP_AUTH_MAX_SECRET_LENGTH &&
|
|
650
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: 拒绝控制字符与空白,防止 Token 注入 Header。
|
|
651
|
+
!/[\u0000-\u0020\u007f]/u.test(value));
|
|
652
|
+
}
|
|
653
|
+
function wait(promise, signal) {
|
|
654
|
+
if (!signal)
|
|
655
|
+
return promise;
|
|
656
|
+
if (signal.aborted)
|
|
657
|
+
return Promise.reject(safeError(undefined, signal));
|
|
658
|
+
return new Promise((resolve, reject) => {
|
|
659
|
+
const cancel = () => reject(safeError(undefined, signal));
|
|
660
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
661
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", cancel));
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
function safeError(cause, signal) {
|
|
665
|
+
const knownCause = cause instanceof McpStdioError &&
|
|
666
|
+
[
|
|
667
|
+
"mcp_auth_required",
|
|
668
|
+
"mcp_auth_failed",
|
|
669
|
+
"mcp_auth_store_failed",
|
|
670
|
+
"aborted",
|
|
671
|
+
"run_timeout",
|
|
672
|
+
].includes(cause.code);
|
|
673
|
+
const source = knownCause ? cause : signal?.aborted ? signal.reason : undefined;
|
|
674
|
+
if (source instanceof McpStdioError) {
|
|
675
|
+
switch (source.code) {
|
|
676
|
+
case "mcp_auth_required":
|
|
677
|
+
return required();
|
|
678
|
+
case "mcp_auth_failed":
|
|
679
|
+
return failed();
|
|
680
|
+
case "mcp_auth_store_failed":
|
|
681
|
+
return storeFailed();
|
|
682
|
+
case "aborted":
|
|
683
|
+
return aborted();
|
|
684
|
+
case "run_timeout":
|
|
685
|
+
return new McpStdioError("run_timeout", "MCP 授权事务超时");
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return signal?.aborted ? aborted() : failed();
|
|
689
|
+
}
|
|
690
|
+
function required() {
|
|
691
|
+
return new McpStdioError("mcp_auth_required", "需要显式 MCP 授权或重新登录");
|
|
692
|
+
}
|
|
693
|
+
function failed() {
|
|
694
|
+
return new McpStdioError("mcp_auth_failed", "MCP 认证失败,未自动重试或更换身份");
|
|
695
|
+
}
|
|
696
|
+
function storeFailed() {
|
|
697
|
+
return new McpStdioError("mcp_auth_store_failed", "MCP 安全存储或认证关闭未完成");
|
|
698
|
+
}
|
|
699
|
+
function aborted() {
|
|
700
|
+
return new McpStdioError("aborted", "MCP 授权或等待已取消");
|
|
701
|
+
}
|
|
702
|
+
//# sourceMappingURL=mcp-authentication.js.map
|