dsh-mcp-ops 0.2.1 → 0.3.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/lib/oauth-web.js DELETED
@@ -1,119 +0,0 @@
1
- import { timingSafeEqual } from "node:crypto";
2
- const WEB_CALLBACK_PATH = "/mcp-ops/oauth/callback";
3
- const WEB_CALLBACK_BUDGET_MS = 5 * 6e4;
4
- const LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
5
- const FINISHED_LIMIT = 64;
6
- function sanitizeOrigin(value) {
7
- if (typeof value !== "string") return void 0;
8
- const text = value.trim();
9
- if (text === "") return void 0;
10
- let url;
11
- try {
12
- url = new URL(text);
13
- } catch {
14
- return void 0;
15
- }
16
- if (url.protocol !== "http:" && url.protocol !== "https:") return void 0;
17
- if (url.username !== "" || url.password !== "") return void 0;
18
- if (url.pathname !== "/" || url.search !== "" || url.hash !== "") return void 0;
19
- if (url.protocol === "http:" && !LOOPBACK_HOSTS.has(url.hostname)) return void 0;
20
- return url.origin;
21
- }
22
- function webCallbackUri(origin) {
23
- return `${origin}${WEB_CALLBACK_PATH}`;
24
- }
25
- const pending = /* @__PURE__ */ new Map();
26
- const finished = /* @__PURE__ */ new Set();
27
- function pendingWebCallbacks() {
28
- return pending.size;
29
- }
30
- function resetWebCallbackState() {
31
- for (const entry of [...pending.values()]) entry.settle(new Error("OAuth callback cancelled"));
32
- pending.clear();
33
- finished.clear();
34
- }
35
- function rememberFinished(state) {
36
- finished.delete(state);
37
- finished.add(state);
38
- while (finished.size > FINISHED_LIMIT) {
39
- const oldest = finished.values().next();
40
- if (oldest.done === true) break;
41
- finished.delete(oldest.value);
42
- }
43
- }
44
- function awaitWebCallback(options) {
45
- const budgetMs = options.budgetMs ?? WEB_CALLBACK_BUDGET_MS;
46
- const redirectUri = webCallbackUri(options.origin);
47
- let done = false;
48
- let timer;
49
- let settle = () => {
50
- };
51
- const promise = new Promise((resolve, reject) => {
52
- settle = (result) => {
53
- if (done) return;
54
- done = true;
55
- if (timer !== void 0) clearTimeout(timer);
56
- pending.delete(options.state);
57
- rememberFinished(options.state);
58
- if (result instanceof Error) reject(result);
59
- else resolve(result);
60
- };
61
- });
62
- timer = setTimeout(() => {
63
- settle(new Error(`OAuth callback timed out after ${budgetMs}ms\uFF08\u9884\u7B97\u5185\u6CA1\u7B49\u5230\u6388\u6743\u56DE\u8C03\uFF09`));
64
- }, budgetMs);
65
- timer.unref?.();
66
- pending.set(options.state, { state: options.state, redirectUri, settle });
67
- return { promise, dispose: () => {
68
- settle(new Error("OAuth callback cancelled"));
69
- } };
70
- }
71
- function stateMatches(received, expected) {
72
- const a = Buffer.from(received);
73
- const b = Buffer.from(expected);
74
- if (a.length !== b.length) return false;
75
- return timingSafeEqual(a, b);
76
- }
77
- const SUCCESS_HTML = '<!doctype html><meta charset="utf-8"><title>OAuth</title><p>\u6388\u6743\u5B8C\u6210\uFF0C\u53EF\u4EE5\u5173\u95ED\u6B64\u7A97\u53E3\u3002</p><p>Authorization complete \u2014 you can close this window.</p>';
78
- function handleWebCallback(req, res) {
79
- const send = (status, html) => {
80
- res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
81
- res.end(html);
82
- };
83
- const invalid = () => send(400, '<!doctype html><meta charset="utf-8"><p>\u56DE\u8C03\u5730\u5740\u4E0D\u5408\u6CD5\u3002</p>');
84
- let url;
85
- try {
86
- url = new URL(req.url ?? "/", "http://127.0.0.1");
87
- } catch {
88
- invalid();
89
- return;
90
- }
91
- if (req.method !== "GET" || url.pathname !== WEB_CALLBACK_PATH) {
92
- invalid();
93
- return;
94
- }
95
- const code = url.searchParams.get("code");
96
- const state = url.searchParams.get("state");
97
- if (code === null || code === "" || state === null || state === "" || url.searchParams.getAll("code").length !== 1 || url.searchParams.getAll("state").length !== 1) {
98
- send(400, '<!doctype html><meta charset="utf-8"><p>\u56DE\u8C03\u53C2\u6570\u4E0D\u5408\u6CD5\uFF08code/state \u7F3A\u5931\u6216\u91CD\u590D\uFF09\u3002</p>');
99
- return;
100
- }
101
- const candidate = [...pending.values()].find((entry) => stateMatches(state, entry.state));
102
- if (candidate === void 0) {
103
- const known = [...finished].some((key) => stateMatches(state, key));
104
- send(known ? 410 : 400, known ? '<!doctype html><meta charset="utf-8"><p>\u8FD9\u6B21\u6388\u6743\u5DF2\u7ECF\u7ED3\u675F\uFF08\u91CD\u590D\u56DE\u8C03\u6216\u5DF2\u8D85\u65F6\uFF09\u3002</p>' : '<!doctype html><meta charset="utf-8"><p>\u56DE\u8C03\u53C2\u6570\u4E0D\u5408\u6CD5\uFF08state \u6821\u9A8C\u5931\u8D25\uFF09\u3002</p>');
105
- return;
106
- }
107
- candidate.settle({ code, redirectUri: candidate.redirectUri });
108
- send(200, SUCCESS_HTML);
109
- }
110
- export {
111
- WEB_CALLBACK_BUDGET_MS,
112
- WEB_CALLBACK_PATH,
113
- awaitWebCallback,
114
- handleWebCallback,
115
- pendingWebCallbacks,
116
- resetWebCallbackState,
117
- sanitizeOrigin,
118
- webCallbackUri
119
- };
package/lib/oauth.js DELETED
@@ -1,228 +0,0 @@
1
- import { createHash, randomBytes } from "node:crypto";
2
- import { createServer } from "node:http";
3
- const LOOPBACK_PORT_MIN = 49152;
4
- const LOOPBACK_PORT_MAX = 65535;
5
- const LOOPBACK_PORT_ATTEMPTS = 16;
6
- const LOOPBACK_PATH = "/callback";
7
- function base64url(buffer) {
8
- return buffer.toString("base64").replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
9
- }
10
- function oauthPortFor(serverName) {
11
- const span = LOOPBACK_PORT_MAX - LOOPBACK_PORT_MIN + 1;
12
- const digest = createHash("sha256").update(`oauth-port:${serverName}`, "utf8").digest();
13
- return LOOPBACK_PORT_MIN + digest.readUInt32BE(0) % span;
14
- }
15
- function createPkcePair(verifier) {
16
- const value = verifier ?? base64url(randomBytes(32));
17
- return { verifier: value, challenge: base64url(createHash("sha256").update(value, "utf8").digest()) };
18
- }
19
- function createState() {
20
- return base64url(randomBytes(16));
21
- }
22
- function buildAuthorizationUrl(options) {
23
- const url = new URL(options.authorizationEndpoint);
24
- url.searchParams.set("response_type", "code");
25
- url.searchParams.set("client_id", options.clientId);
26
- url.searchParams.set("redirect_uri", options.redirectUri);
27
- url.searchParams.set("state", options.state);
28
- url.searchParams.set("code_challenge", options.challenge);
29
- url.searchParams.set("code_challenge_method", "S256");
30
- if (options.scope !== void 0 && options.scope !== "") url.searchParams.set("scope", options.scope);
31
- for (const [key, value] of Object.entries(options.extra ?? {})) url.searchParams.set(key, value);
32
- return url.toString();
33
- }
34
- function isTokenFresh(token, skewMs = 6e4, now = Date.now()) {
35
- if (token === void 0 || token.accessToken === "") return false;
36
- if (token.expiresAt === void 0) return true;
37
- return token.expiresAt - skewMs > now;
38
- }
39
- function authorizationHeader(token) {
40
- return `${token.tokenType ?? "Bearer"} ${token.accessToken}`;
41
- }
42
- function serializeToken(token) {
43
- return JSON.stringify({
44
- accessToken: token.accessToken,
45
- ...token.refreshToken === void 0 ? {} : { refreshToken: token.refreshToken },
46
- ...token.expiresAt === void 0 ? {} : { expiresAt: token.expiresAt },
47
- ...token.tokenType === void 0 ? {} : { tokenType: token.tokenType }
48
- });
49
- }
50
- function parseToken(text) {
51
- if (text === void 0 || text.trim() === "") return void 0;
52
- try {
53
- const parsed = JSON.parse(text);
54
- if (typeof parsed.accessToken !== "string" || parsed.accessToken === "") return void 0;
55
- return {
56
- accessToken: parsed.accessToken,
57
- ...typeof parsed.refreshToken === "string" ? { refreshToken: parsed.refreshToken } : {},
58
- ...typeof parsed.expiresAt === "number" ? { expiresAt: parsed.expiresAt } : {},
59
- ...typeof parsed.tokenType === "string" ? { tokenType: parsed.tokenType } : {}
60
- };
61
- } catch {
62
- return void 0;
63
- }
64
- }
65
- function serializeClient(info) {
66
- return JSON.stringify({
67
- clientId: info.clientId,
68
- ...info.clientSecret === void 0 ? {} : { clientSecret: info.clientSecret },
69
- ...info.redirectUris === void 0 ? {} : { redirectUris: info.redirectUris }
70
- });
71
- }
72
- function parseClient(text) {
73
- if (text === void 0 || text.trim() === "") return void 0;
74
- try {
75
- const parsed = JSON.parse(text);
76
- if (typeof parsed.clientId !== "string" || parsed.clientId === "") return void 0;
77
- const redirectUris = Array.isArray(parsed.redirectUris) && parsed.redirectUris.every((item) => typeof item === "string") ? parsed.redirectUris : void 0;
78
- return {
79
- clientId: parsed.clientId,
80
- ...typeof parsed.clientSecret === "string" ? { clientSecret: parsed.clientSecret } : {},
81
- ...redirectUris === void 0 ? {} : { redirectUris }
82
- };
83
- } catch {
84
- return void 0;
85
- }
86
- }
87
- async function discoverMetadata(issuerUrl, fetchImpl = fetch) {
88
- const base = new URL(issuerUrl);
89
- const candidates = [
90
- new URL("/.well-known/oauth-authorization-server", base).toString(),
91
- new URL("/.well-known/openid-configuration", base).toString()
92
- ];
93
- const problems = [];
94
- for (const candidate of candidates) {
95
- try {
96
- const response = await fetchImpl(candidate, { headers: { accept: "application/json" } });
97
- if (!response.ok) {
98
- problems.push(`${candidate}: HTTP ${response.status}`);
99
- continue;
100
- }
101
- const body = await response.json();
102
- const authorizationEndpoint = body.authorization_endpoint;
103
- const tokenEndpoint = body.token_endpoint;
104
- if (typeof authorizationEndpoint !== "string" || typeof tokenEndpoint !== "string") {
105
- problems.push(`${candidate}: missing authorization_endpoint/token_endpoint`);
106
- continue;
107
- }
108
- return {
109
- authorizationEndpoint,
110
- tokenEndpoint,
111
- ...typeof body.registration_endpoint === "string" ? { registrationEndpoint: body.registration_endpoint } : {},
112
- ...Array.isArray(body.scopes_supported) ? { scopesSupported: body.scopes_supported.filter((item) => typeof item === "string") } : {}
113
- };
114
- } catch (error) {
115
- problems.push(`${candidate}: ${error instanceof Error ? error.message : String(error)}`);
116
- }
117
- }
118
- throw new Error(`OAuth metadata discovery failed: ${problems.join("; ")}`);
119
- }
120
- async function exchangeCode(options) {
121
- const fetchImpl = options.fetchImpl ?? fetch;
122
- const body = new URLSearchParams({
123
- grant_type: "authorization_code",
124
- code: options.code,
125
- code_verifier: options.verifier,
126
- client_id: options.clientId,
127
- redirect_uri: options.redirectUri
128
- });
129
- if (options.clientSecret !== void 0) body.set("client_secret", options.clientSecret);
130
- const response = await fetchImpl(options.tokenEndpoint, {
131
- method: "POST",
132
- headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
133
- body: body.toString()
134
- });
135
- if (!response.ok) throw new Error(`token exchange failed: HTTP ${response.status}`);
136
- const payload = await response.json();
137
- if (typeof payload.access_token !== "string" || payload.access_token === "") {
138
- throw new Error("token exchange failed: response has no access_token");
139
- }
140
- return {
141
- accessToken: payload.access_token,
142
- ...typeof payload.refresh_token === "string" ? { refreshToken: payload.refresh_token } : {},
143
- ...typeof payload.expires_in === "number" ? { expiresAt: Date.now() + payload.expires_in * 1e3 } : {},
144
- ...typeof payload.token_type === "string" ? { tokenType: payload.token_type } : {}
145
- };
146
- }
147
- async function awaitLoopbackCallback(options) {
148
- const budgetMs = options.budgetMs ?? 5 * 6e4;
149
- let server;
150
- let port = 0;
151
- let lastError;
152
- for (let attempt = 0; attempt < LOOPBACK_PORT_ATTEMPTS; attempt += 1) {
153
- const candidate = LOOPBACK_PORT_MIN + (oauthPortFor(options.serverName) - LOOPBACK_PORT_MIN + attempt) % (LOOPBACK_PORT_MAX - LOOPBACK_PORT_MIN + 1);
154
- try {
155
- server = createServer();
156
- await new Promise((resolve, reject) => {
157
- server.once("error", reject);
158
- server.listen(candidate, "127.0.0.1", () => resolve());
159
- });
160
- port = candidate;
161
- break;
162
- } catch (error) {
163
- lastError = error;
164
- server = void 0;
165
- }
166
- }
167
- if (server === void 0 || port === 0) {
168
- throw new Error(`cannot bind a loopback port in ${LOOPBACK_PORT_MIN}..${LOOPBACK_PORT_MAX}: ${String(lastError)}`);
169
- }
170
- const redirectUri = `http://127.0.0.1:${port}${LOOPBACK_PATH}`;
171
- await options.onReady?.(redirectUri);
172
- return await new Promise((resolve, reject) => {
173
- const timer = setTimeout(() => {
174
- server.close();
175
- reject(new Error(`OAuth callback timed out after ${budgetMs}ms`));
176
- }, budgetMs);
177
- timer.unref?.();
178
- server.on("request", (request, response) => {
179
- const url = new URL(request.url ?? "/", redirectUri);
180
- if (url.pathname !== LOOPBACK_PATH) {
181
- response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
182
- response.end("not found");
183
- return;
184
- }
185
- const code = url.searchParams.get("code");
186
- const state = url.searchParams.get("state");
187
- const error = url.searchParams.get("error");
188
- const finish = (status, text) => {
189
- response.writeHead(status, { "content-type": "text/html; charset=utf-8" });
190
- response.end(`<!doctype html><meta charset="utf-8"><p>${text}</p>`);
191
- };
192
- if (error !== null) {
193
- finish(400, `\u6388\u6743\u5931\u8D25\uFF1A${error}`);
194
- clearTimeout(timer);
195
- server.close();
196
- reject(new Error(`authorization failed: ${error}`));
197
- return;
198
- }
199
- if (code === null || state !== options.state) {
200
- finish(400, "\u56DE\u8C03\u53C2\u6570\u4E0D\u5408\u6CD5\uFF08code/state \u6821\u9A8C\u5931\u8D25\uFF09");
201
- return;
202
- }
203
- finish(200, "\u6388\u6743\u5B8C\u6210\uFF0C\u53EF\u4EE5\u5173\u95ED\u672C\u9875\u3002");
204
- clearTimeout(timer);
205
- server.close();
206
- resolve({ code, redirectUri });
207
- });
208
- });
209
- }
210
- export {
211
- LOOPBACK_PATH,
212
- LOOPBACK_PORT_ATTEMPTS,
213
- LOOPBACK_PORT_MAX,
214
- LOOPBACK_PORT_MIN,
215
- authorizationHeader,
216
- awaitLoopbackCallback,
217
- buildAuthorizationUrl,
218
- createPkcePair,
219
- createState,
220
- discoverMetadata,
221
- exchangeCode,
222
- isTokenFresh,
223
- oauthPortFor,
224
- parseClient,
225
- parseToken,
226
- serializeClient,
227
- serializeToken
228
- };