@agentmesh-md/mcp-server 0.1.1 → 0.2.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/dist/index.js CHANGED
@@ -1,123 +1,24 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * Entrypoint (package.json "bin": "dist/index.js").
4
- *
5
- * Stdout purity (PLAN §PRESERVE 2): this file, and every module it imports,
6
- * writes diagnostics ONLY via logStderr (-> console.error -> stderr). The
7
- * ONE sanctioned writer of stdout in this whole package is the stdio MCP
8
- * transport itself — under v2, `serveStdio`'s internally-constructed
9
- * `StdioServerTransport`, which binds the real `process.stdout` for MCP
10
- * JSON-RPC frames (that IS the transport, not a logging path).
11
- *
12
- * v2 migration (td-7dd275, Seam B): stdio is served through
13
- * `serveStdio(() => buildServer())` from `@modelcontextprotocol/server/stdio`
14
- * — dual-era by default (`legacy: 'serve'`): a 2025-era opening (an
15
- * `initialize` handshake, the deployed 1a behavior) pins a legacy-era
16
- * instance from the SAME factory and is served exactly as the hand-wired 1a
17
- * stdio server served it; a modern (2026-07-28) opening gets a modern
18
- * instance. One factory backs both eras and both transports (http.ts uses
19
- * the same `buildServer`), so the tool surface cannot drift.
20
- */
21
- import { config } from "./config.js";
22
- import { logStderr } from "./logger.js";
23
- import { buildServer } from "./server.js";
24
- import { startHttpServer } from "./http.js";
25
- import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
26
- import { readWakeConfig, WakeLoop } from "./wake.js";
27
- async function main() {
28
- logStderr(`agentmesh-mcp: starting (transport=${config.transport}, apiBaseUrl=${config.apiBaseUrl})`);
29
- if (config.transport === "http") {
30
- // Phase 1 (td-7dd275): v2 per-request Streamable HTTP — single /mcp
31
- // endpoint, per-request `Authorization: Bearer <am_* key>` required and
32
- // forwarded upstream as that request's credential (http.ts). The 1A
33
- // stdout rule is trivially preserved here: http mode writes nothing to
34
- // stdout.
35
- const running = await startHttpServer();
36
- // Graceful shutdown: close the MCP handler + listener, then exit. The
37
- // timer fallback guarantees a wedged connection can never turn SIGTERM
38
- // into a hang.
39
- const shutdown = (signal) => {
40
- logStderr(`agentmesh-mcp: ${signal} received, closing http transport.`);
41
- setTimeout(() => process.exit(1), 3000).unref();
42
- running.close().then(() => process.exit(0), () => process.exit(1));
43
- };
44
- process.once("SIGTERM", () => shutdown("SIGTERM"));
45
- process.once("SIGINT", () => shutdown("SIGINT"));
46
- return;
47
- }
48
- // stdio (default): serveStdio owns the transport (constructed over this
49
- // process's stdio) and the per-connection era decision; `legacy` is left
50
- // at its 'serve' default deliberately — 2025-era clients (the deployed 1a
51
- // consumers) remain first-class. The banner text is load-bearing: the c1
52
- // controls (and the deployed 00028-qak behavior) key on it.
53
- // td-ef46e2: optional session wake. Off unless AGENTMESH_WAKE_MODE is set,
54
- // so the default stdio behavior above is unchanged.
55
- const wake = readWakeConfig();
56
- const channel = wake?.mode === "channel";
57
- let pinned;
58
- let initialized = false;
59
- // Claude Code drops channel pushes on a 2026-era connection, so a channel
60
- // server is wired by hand: it has no server/discover handler, and the
61
- // client falls back to the 2025 initialize handshake by itself.
62
- if (channel) {
63
- const server = buildServer({ channel });
64
- server.oninitialized = () => {
65
- initialized = true;
66
- };
67
- pinned = server;
68
- await server.connect(new StdioServerTransport());
69
- }
70
- else
71
- serveStdio(() => {
72
- const server = buildServer({ channel });
73
- server.oninitialized = () => {
74
- initialized = true;
75
- };
76
- pinned = server;
77
- return server;
78
- }, {
79
- onerror: (err) => {
80
- // Reporting only; logStderr redacts (RULE-10).
81
- logStderr("agentmesh-mcp: stdio transport error:", err);
82
- },
83
- });
84
- logStderr("agentmesh-mcp: connected over stdio, ready.");
85
- if (wake !== null) {
86
- const stop = new AbortController();
87
- process.stdin.once("end", () => stop.abort());
88
- // A signal listener replaces Node's default exit, so exit explicitly
89
- // (this also runs the wake lock's exit cleanup).
90
- for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
91
- process.once(signal, () => {
92
- stop.abort();
93
- process.exit(0);
94
- });
95
- }
96
- const push = async (item, replay) => {
97
- // Hold the event (it stays queued on disk) until a 2025-era handshake
98
- // completes; a notification written before that would be dropped.
99
- let waited = 0;
100
- while (!initialized && !stop.signal.aborted) {
101
- if (waited === 30_000) {
102
- logStderr("agentmesh-mcp: wake is holding channel events: the client has not completed the initialize handshake.");
103
- }
104
- await new Promise((r) => setTimeout(r, 200));
105
- waited += 200;
106
- }
107
- if (!initialized || pinned === undefined)
108
- throw new Error("not delivered");
109
- await pinned.notification({
110
- method: "notifications/claude/channel",
111
- params: { content: item.content, meta: replay ? { ...item.meta, replay: "possible" } : item.meta },
112
- });
113
- };
114
- void new WakeLoop({ ...wake, push: channel ? push : undefined, signal: stop.signal })
115
- .run()
116
- .catch((err) => logStderr("agentmesh-mcp: wake failed:", err instanceof Error ? err : String(err)));
117
- }
2
+ // Dispatch before loading the legacy key-required configuration.
3
+ const action = process.argv[2];
4
+ if (action === "connect") {
5
+ const { connect } = await import("./connect.js");
6
+ const { terminalDiagnostic } = await import("./terminal-diagnostic.js");
7
+ await connect(process.argv.slice(3)).catch((error) => {
8
+ process.stderr.write(`AgentMesh ${terminalDiagnostic(error, 'index.js', 'connect')}.\n`);
9
+ process.stderr.write("AgentMesh Connect failed at connect.ts:connect. Re-run Connect to sign in or check the installed client version. No credentials were printed.\n");
10
+ process.exitCode = 1;
11
+ });
118
12
  }
119
- main().catch((err) => {
120
- const message = err instanceof Error ? (err.stack ?? `${err.name}: ${err.message}`) : String(err);
121
- logStderr(`agentmesh-mcp: fatal error: ${message}`);
122
- process.exit(1);
123
- });
13
+ else if (action === "bridge") {
14
+ const { bridge } = await import("./connect-bridge.js");
15
+ const { terminalDiagnostic } = await import("./terminal-diagnostic.js");
16
+ await bridge(process.argv[3] ?? "").catch((error) => {
17
+ process.stderr.write(`AgentMesh ${terminalDiagnostic(error, 'index.js', 'bridge')}.\n`);
18
+ process.stderr.write("AgentMesh terminal bridge unavailable at connect-bridge.ts:bridge; re-run Connect.\n");
19
+ process.exitCode = 1;
20
+ });
21
+ }
22
+ else
23
+ await import("./legacy.js");
24
+ export {};
package/dist/legacy.js ADDED
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Entrypoint (package.json "bin": "dist/index.js").
4
+ *
5
+ * Stdout purity (PLAN §PRESERVE 2): this file, and every module it imports,
6
+ * writes diagnostics ONLY via logStderr (-> console.error -> stderr). The
7
+ * ONE sanctioned writer of stdout in this whole package is the stdio MCP
8
+ * transport itself — under v2, `serveStdio`'s internally-constructed
9
+ * `StdioServerTransport`, which binds the real `process.stdout` for MCP
10
+ * JSON-RPC frames (that IS the transport, not a logging path).
11
+ *
12
+ * v2 migration (td-7dd275, Seam B): stdio is served through
13
+ * `serveStdio(() => buildServer())` from `@modelcontextprotocol/server/stdio`
14
+ * — dual-era by default (`legacy: 'serve'`): a 2025-era opening (an
15
+ * `initialize` handshake, the deployed 1a behavior) pins a legacy-era
16
+ * instance from the SAME factory and is served exactly as the hand-wired 1a
17
+ * stdio server served it; a modern (2026-07-28) opening gets a modern
18
+ * instance. One factory backs both eras and both transports (http.ts uses
19
+ * the same `buildServer`), so the tool surface cannot drift.
20
+ */
21
+ import { config } from "./config.js";
22
+ import { logStderr } from "./logger.js";
23
+ import { buildServer } from "./server.js";
24
+ import { startHttpServer } from "./http.js";
25
+ import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
26
+ import { readWakeConfig, WakeLoop } from "./wake.js";
27
+ async function main() {
28
+ logStderr(`agentmesh-mcp: starting (transport=${config.transport}, apiBaseUrl=${config.apiBaseUrl})`);
29
+ if (config.transport === "http") {
30
+ // Phase 1 (td-7dd275): v2 per-request Streamable HTTP — single /mcp
31
+ // endpoint, per-request `Authorization: Bearer <am_* key>` required and
32
+ // forwarded upstream as that request's credential (http.ts). The 1A
33
+ // stdout rule is trivially preserved here: http mode writes nothing to
34
+ // stdout.
35
+ const running = await startHttpServer();
36
+ // Graceful shutdown: close the MCP handler + listener, then exit. The
37
+ // timer fallback guarantees a wedged connection can never turn SIGTERM
38
+ // into a hang.
39
+ const shutdown = (signal) => {
40
+ logStderr(`agentmesh-mcp: ${signal} received, closing http transport.`);
41
+ setTimeout(() => process.exit(1), 3000).unref();
42
+ running.close().then(() => process.exit(0), () => process.exit(1));
43
+ };
44
+ process.once("SIGTERM", () => shutdown("SIGTERM"));
45
+ process.once("SIGINT", () => shutdown("SIGINT"));
46
+ return;
47
+ }
48
+ // stdio (default): serveStdio owns the transport (constructed over this
49
+ // process's stdio) and the per-connection era decision; `legacy` is left
50
+ // at its 'serve' default deliberately — 2025-era clients (the deployed 1a
51
+ // consumers) remain first-class. The banner text is load-bearing: the c1
52
+ // controls (and the deployed 00028-qak behavior) key on it.
53
+ // td-ef46e2: optional session wake. Off unless AGENTMESH_WAKE_MODE is set,
54
+ // so the default stdio behavior above is unchanged.
55
+ const wake = readWakeConfig();
56
+ const channel = wake?.mode === "channel";
57
+ let pinned;
58
+ let initialized = false;
59
+ // Claude Code drops channel pushes on a 2026-era connection, so a channel
60
+ // server is wired by hand: it has no server/discover handler, and the
61
+ // client falls back to the 2025 initialize handshake by itself.
62
+ if (channel) {
63
+ const server = buildServer({ channel });
64
+ server.oninitialized = () => {
65
+ initialized = true;
66
+ };
67
+ pinned = server;
68
+ await server.connect(new StdioServerTransport());
69
+ }
70
+ else
71
+ serveStdio(() => {
72
+ const server = buildServer({ channel });
73
+ server.oninitialized = () => {
74
+ initialized = true;
75
+ };
76
+ pinned = server;
77
+ return server;
78
+ }, {
79
+ onerror: (err) => {
80
+ // Reporting only; logStderr redacts (RULE-10).
81
+ logStderr("agentmesh-mcp: stdio transport error:", err);
82
+ },
83
+ });
84
+ logStderr("agentmesh-mcp: connected over stdio, ready.");
85
+ if (wake !== null) {
86
+ const stop = new AbortController();
87
+ process.stdin.once("end", () => stop.abort());
88
+ // A signal listener replaces Node's default exit, so exit explicitly
89
+ // (this also runs the wake lock's exit cleanup).
90
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
91
+ process.once(signal, () => {
92
+ stop.abort();
93
+ process.exit(0);
94
+ });
95
+ }
96
+ const push = async (item, replay) => {
97
+ // Hold the event (it stays queued on disk) until a 2025-era handshake
98
+ // completes; a notification written before that would be dropped.
99
+ let waited = 0;
100
+ while (!initialized && !stop.signal.aborted) {
101
+ if (waited === 30_000) {
102
+ logStderr("agentmesh-mcp: wake is holding channel events: the client has not completed the initialize handshake.");
103
+ }
104
+ await new Promise((r) => setTimeout(r, 200));
105
+ waited += 200;
106
+ }
107
+ if (!initialized || pinned === undefined)
108
+ throw new Error("not delivered");
109
+ await pinned.notification({
110
+ method: "notifications/claude/channel",
111
+ params: { content: item.content, meta: replay ? { ...item.meta, replay: "possible" } : item.meta },
112
+ });
113
+ };
114
+ void new WakeLoop({ ...wake, push: channel ? push : undefined, signal: stop.signal })
115
+ .run()
116
+ .catch((err) => logStderr("agentmesh-mcp: wake failed:", err instanceof Error ? err : String(err)));
117
+ }
118
+ }
119
+ main().catch((err) => {
120
+ const message = err instanceof Error ? (err.stack ?? `${err.name}: ${err.message}`) : String(err);
121
+ logStderr(`agentmesh-mcp: fatal error: ${message}`);
122
+ process.exit(1);
123
+ });
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+ /** Groups from `groups` tagged as @group; '-' also ends a name, so @team-ops is not @team. */
3
+ function mentionedGroups(body, groups) {
4
+ const out = [];
5
+ for (const g of groups) {
6
+ const escaped = g.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7
+ if (new RegExp(`(?<![\\w@.])@${escaped}(?![\\w-])`, "i").test(body)) out.push(g);
8
+ }
9
+ return out;
10
+ }
11
+
12
+ /** True when the body @mentions anyone at all. */
13
+ function mentionsAnyone(body) {
14
+ return /(?<![\w@.])@[A-Za-z0-9]/.test(body);
15
+ }
16
+
17
+ function mentionsAgent(body, name) {
18
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19
+ return new RegExp(`(?<![\\w@.])@${escaped}(?![\\w])`, "i").test(body);
20
+ }
21
+
22
+ module.exports = { mentionedGroups, mentionsAnyone, mentionsAgent };
@@ -0,0 +1,110 @@
1
+ import { Readable } from "node:stream";
2
+ import { pipeline } from "node:stream/promises";
3
+ const NON_FORWARDED_HEADERS = new Set([
4
+ "connection",
5
+ "keep-alive",
6
+ "transfer-encoding",
7
+ "upgrade",
8
+ "te",
9
+ "trailer",
10
+ "proxy-authenticate",
11
+ "proxy-authorization",
12
+ "content-length",
13
+ // The raw credential NEVER rides into the SDK layer: the edge gate has
14
+ // already validated it and threaded identity through the ALS (context.ts).
15
+ // Stripping it here makes the documented three-seam OAuth-swap boundary true
16
+ // BY CONSTRUCTION — the v2 SDK neither reads nor derives authInfo from
17
+ // headers today, but it does echo other request-header values into response
18
+ // bodies/onerror, and a future SDK/middleware change must not be able to
19
+ // surface the key (code-review 18e6e24, transport dimension).
20
+ "authorization",
21
+ ]);
22
+ export function readBody(req, maxBytes = 4 * 1024 * 1024, signal) {
23
+ return new Promise((resolve, reject) => {
24
+ const abort = () => { req.pause(); reject(new Error("REQUEST_ABORTED")); };
25
+ if (signal?.aborted) {
26
+ abort();
27
+ return;
28
+ }
29
+ signal?.addEventListener("abort", abort, { once: true });
30
+ const cleanup = () => signal?.removeEventListener("abort", abort);
31
+ req.once("end", cleanup);
32
+ req.once("error", cleanup);
33
+ req.once("aborted", () => { cleanup(); abort(); });
34
+ const chunks = [];
35
+ let total = 0;
36
+ req.on("data", (chunk) => {
37
+ total += chunk.length;
38
+ if (total > maxBytes) {
39
+ reject(new Error("PAYLOAD_TOO_LARGE"));
40
+ req.pause();
41
+ return;
42
+ }
43
+ chunks.push(chunk);
44
+ });
45
+ req.on("end", () => resolve(Buffer.concat(chunks)));
46
+ req.on("error", (err) => reject(err));
47
+ });
48
+ }
49
+ /**
50
+ * Bridge a node:http request to the web-standard `Request` the v2 handler's
51
+ * `fetch` face consumes. (`@modelcontextprotocol/node`'s `toNodeHandler` is
52
+ * not a dependency of this package; the bridge is ~30 lines and keeps the
53
+ * edge auth gates in one file.) `body` is the already-buffered POST payload
54
+ * (cap enforced by readBody); GET/DELETE carry none. `signal` aborts the
55
+ * SDK's exchange when the client disconnects mid-response.
56
+ */
57
+ export function toWebRequest(req, url, body, signal) {
58
+ const headers = new Headers();
59
+ for (const [name, value] of Object.entries(req.headers)) {
60
+ if (value === undefined || NON_FORWARDED_HEADERS.has(name)) {
61
+ continue;
62
+ }
63
+ if (Array.isArray(value)) {
64
+ for (const item of value) {
65
+ headers.append(name, item);
66
+ }
67
+ }
68
+ else {
69
+ headers.set(name, value);
70
+ }
71
+ }
72
+ return new Request(url, {
73
+ method: req.method,
74
+ headers,
75
+ ...(body !== undefined ? { body: new Uint8Array(body) } : {}),
76
+ signal,
77
+ });
78
+ }
79
+ /**
80
+ * Write a web-standard `Response` back onto the node:http response. Streams
81
+ * the body (SSE responses stay open for as long as the SDK keeps them open);
82
+ * a client disconnect destroys the source stream via pipeline(), which
83
+ * cancels the SDK's underlying exchange.
84
+ */
85
+ export async function writeWebResponse(res, response) {
86
+ const headers = {};
87
+ response.headers.forEach((value, name) => {
88
+ headers[name] = value;
89
+ });
90
+ res.writeHead(response.status, headers);
91
+ if (response.body === null) {
92
+ res.end();
93
+ return;
94
+ }
95
+ res.flushHeaders();
96
+ try {
97
+ // Type note: undici's ReadableStream and node:stream/web's are the same
98
+ // runtime object; the lib typings disagree, hence the narrow cast.
99
+ await pipeline(Readable.fromWeb(response.body), res);
100
+ }
101
+ catch (err) {
102
+ // A client that goes away mid-stream (premature close / abort) is a
103
+ // normal end-of-life for an SSE response, not a server error. pipeline()
104
+ // has already destroyed the source, which cancels the SDK exchange.
105
+ const code = err?.code;
106
+ if (code !== "ERR_STREAM_PREMATURE_CLOSE" && code !== "ABORT_ERR") {
107
+ throw err;
108
+ }
109
+ }
110
+ }
@@ -0,0 +1,165 @@
1
+ import fs from 'node:fs';
2
+ import http from 'node:http';
3
+ import path from 'node:path';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { spawn } from 'node:child_process';
6
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
7
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
8
+ import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
9
+ import { readJson, writeAtomic } from './wake-storage.js';
10
+ export const RESOURCE = 'https://agentmesh.md/mcp';
11
+ export function ownerDirectory(dir) {
12
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
13
+ const stat = fs.lstatSync(dir);
14
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.())
15
+ throw new Error('OwnerDirectoryRequired');
16
+ fs.chmodSync(dir, 0o700);
17
+ }
18
+ export function credentialFile(file) {
19
+ if (!fs.existsSync(file))
20
+ return undefined;
21
+ const stat = fs.lstatSync(file);
22
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0)
23
+ throw new Error('OwnerCredentialsRequired');
24
+ const saved = readJson(file);
25
+ if (saved.resource !== RESOURCE)
26
+ throw new Error('ResourceMismatch');
27
+ return saved;
28
+ }
29
+ // One launcher owns this provider and serializes all remote calls. Its stdio
30
+ // children never receive credentials, including during refresh rotation.
31
+ class Provider {
32
+ file;
33
+ verifier = '';
34
+ secrets = new Set();
35
+ redact(value) {
36
+ let text = JSON.stringify(value);
37
+ for (const secret of this.secrets)
38
+ text = text.split(secret).join('[redacted]');
39
+ return JSON.parse(text);
40
+ }
41
+ remember(tokens) {
42
+ for (const token of [tokens?.access_token, tokens?.refresh_token])
43
+ if (token)
44
+ this.secrets.add(token);
45
+ }
46
+ nonce = randomBytes(32).toString('hex');
47
+ saved;
48
+ redirectUrl;
49
+ authorizationStarted = false;
50
+ constructor(file, redirect) {
51
+ this.file = file;
52
+ this.saved = credentialFile(file) ?? { resource: RESOURCE, redirect };
53
+ this.redirectUrl = this.saved.redirect;
54
+ this.remember(this.saved.tokens);
55
+ }
56
+ get clientMetadata() {
57
+ return { client_name: 'AgentMesh terminal Connect', redirect_uris: [this.redirectUrl],
58
+ grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none',
59
+ scope: 'mesh:read mesh:write offline_access' };
60
+ }
61
+ state() { return this.nonce; }
62
+ validState(value) { return value === this.nonce; }
63
+ clientInformation() { return this.saved.client; }
64
+ saveClientInformation(value) { this.saved.client = value; this.save(); }
65
+ tokens() { return this.saved.tokens; }
66
+ saveTokens(value) { this.remember(value); this.saved.tokens = value; this.save(); }
67
+ saveCodeVerifier(value) { this.verifier = value; }
68
+ codeVerifier() { return this.verifier; }
69
+ async validateResourceURL(server, resource) {
70
+ if (String(server) !== RESOURCE || (resource !== undefined && resource !== RESOURCE))
71
+ throw new Error('ResourceMismatch');
72
+ return new URL(RESOURCE);
73
+ }
74
+ async redirectToAuthorization(url) {
75
+ if (url.origin !== new URL(RESOURCE).origin || url.pathname !== '/authorize')
76
+ throw new Error('AuthorizationOriginMismatch');
77
+ this.authorizationStarted = true;
78
+ process.stderr.write('Approve the connection as your AgentMesh agent in the browser.\n');
79
+ // Never echo the authorization request/response. This URL contains only
80
+ // client ID, state and PKCE challenge; never bearer/refresh/code/verifier.
81
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32' : 'xdg-open';
82
+ const child = spawn(command, process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url.href] : [url.href], { stdio: 'ignore' });
83
+ await new Promise((resolve, reject) => { child.once('error', reject); child.once('exit', code => code === 0 ? resolve() : reject(new Error('BrowserOpenFailed'))); });
84
+ }
85
+ invalidateCredentials(scope) {
86
+ if (scope === 'all' || scope === 'client')
87
+ delete this.saved.client;
88
+ if (scope === 'all' || scope === 'tokens')
89
+ delete this.saved.tokens;
90
+ if (scope === 'all' || scope === 'verifier')
91
+ this.verifier = '';
92
+ this.save();
93
+ }
94
+ save() { writeAtomic(this.file, this.saved); fs.chmodSync(this.file, 0o600); }
95
+ }
96
+ // OAuth discovery/token requests stay on the canonical first-party origin;
97
+ // response redirects cannot exfiltrate Authorization or form credentials.
98
+ const safeFetch = async (input, init) => {
99
+ const url = new URL(input instanceof Request ? input.url : String(input));
100
+ if (url.origin !== new URL(RESOURCE).origin)
101
+ throw new Error('OAuthOriginMismatch');
102
+ return fetch(input, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(15_000)]) : AbortSignal.timeout(15_000) });
103
+ };
104
+ export async function openOAuth(profile) {
105
+ ownerDirectory(profile);
106
+ const file = path.join(profile, 'credentials.json');
107
+ const saved = credentialFile(file);
108
+ const server = http.createServer();
109
+ // Reuse the registered loopback port. An occupied port fails visibly;
110
+ // silently changing redirect URI would invalidate the registered client.
111
+ const savedURL = saved ? new URL(saved.redirect) : undefined;
112
+ if (savedURL && (savedURL.hostname !== '127.0.0.1' || savedURL.protocol !== 'http:' || savedURL.pathname !== '/callback'))
113
+ throw new Error('CallbackMismatch');
114
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(savedURL ? Number(savedURL.port) : 0, '127.0.0.1', resolve); });
115
+ const address = server.address();
116
+ if (!address || typeof address === 'string')
117
+ throw new Error('CallbackUnavailable');
118
+ const provider = new Provider(file, `http://127.0.0.1:${address.port}/callback`);
119
+ let timer;
120
+ const code = new Promise((resolve, reject) => {
121
+ timer = setTimeout(() => reject(new Error('ApprovalTimeout')), 180_000);
122
+ server.on('request', (req, res) => {
123
+ res.setHeader('Cache-Control', 'no-store');
124
+ res.setHeader('Referrer-Policy', 'no-referrer');
125
+ const url = new URL(req.url ?? '/', provider.redirectUrl);
126
+ const value = url.searchParams.get('code');
127
+ if (req.method !== 'GET' || req.headers.host !== `127.0.0.1:${address.port}` || url.pathname !== '/callback'
128
+ || !provider.validState(url.searchParams.get('state')) || !value || url.searchParams.has('error')) {
129
+ res.writeHead(400);
130
+ res.end('Approval was not accepted. Return to your terminal and retry Connect.');
131
+ return;
132
+ }
133
+ res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
134
+ res.end('Connection approved. Return to your terminal.');
135
+ resolve(value);
136
+ });
137
+ });
138
+ // A cached-token success never awaits the callback; prevent an unhandled
139
+ // rejection while its timer is being cancelled in finally.
140
+ void code.catch(() => undefined);
141
+ const transport = new StreamableHTTPClientTransport(new URL(RESOURCE), { authProvider: provider, fetch: safeFetch });
142
+ let client = new Client({ name: 'agentmesh-terminal', version: '0.2.0' });
143
+ try {
144
+ try {
145
+ await client.connect(transport);
146
+ }
147
+ catch (error) {
148
+ if (!(error instanceof UnauthorizedError) || !provider.authorizationStarted)
149
+ throw error;
150
+ await transport.finishAuth(await code);
151
+ await client.close();
152
+ client = new Client({ name: 'agentmesh-terminal', version: '0.2.0' });
153
+ await client.connect(new StreamableHTTPClientTransport(new URL(RESOURCE), { authProvider: provider, fetch: safeFetch }));
154
+ }
155
+ return { client, redact: (value) => provider.redact(value), close: () => client.close() };
156
+ }
157
+ catch (error) {
158
+ await client.close().catch(() => undefined);
159
+ throw error;
160
+ }
161
+ finally {
162
+ clearTimeout(timer);
163
+ server.close();
164
+ }
165
+ }
package/dist/redact.js CHANGED
@@ -13,7 +13,7 @@
13
13
  * import cycle with logger.ts/config.ts, and so redaction is available even on
14
14
  * paths that run before config validation.
15
15
  */
16
- import { currentRequestApiKey } from "./context.js";
16
+ import { currentRequestApiKey, currentRequestContext } from "./context.js";
17
17
  const PLACEHOLDER = "[redacted-credential]";
18
18
  /**
19
19
  * Every credential currently in scope: the env-configured key (stdio's
@@ -32,7 +32,7 @@ function secretsInScope() {
32
32
  if (requestKey !== undefined && requestKey.length > 0 && requestKey !== envKey) {
33
33
  secrets.push(requestKey);
34
34
  }
35
- return secrets;
35
+ return [...secrets, ...(currentRequestContext()?.secrets ?? []).filter((value) => value.length > 0)];
36
36
  }
37
37
  /**
38
38
  * Replace every occurrence of each in-scope credential in `text` with a