passport-bridge 0.7.0 → 0.7.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/README.md +80 -48
- package/dist/boundedFile.js +46 -0
- package/dist/boundedMcpFetch.js +98 -0
- package/dist/boundedResponse.js +56 -0
- package/dist/bridge.js +426 -99
- package/dist/bridgeConfig.js +19 -0
- package/dist/bridgeShutdown.js +30 -0
- package/dist/cli.js +193 -37
- package/dist/cliArgs.js +2 -0
- package/dist/cliClient.js +24 -46
- package/dist/cliDeadline.js +27 -0
- package/dist/cliLogin.js +103 -0
- package/dist/cliOffline.js +53 -0
- package/dist/cliOutput.js +106 -0
- package/dist/cliPagination.js +55 -0
- package/dist/cliResult.js +87 -0
- package/dist/cliSession.js +163 -0
- package/dist/cliSupport.js +191 -0
- package/dist/completion.js +22 -9
- package/dist/credentials.js +584 -83
- package/dist/discover.js +60 -34
- package/dist/doctor.js +56 -13
- package/dist/legacyCliSecurity.js +26 -0
- package/dist/passport.js +87 -469
- package/dist/privateStableFile.js +170 -0
- package/dist/recoveryCleanup.js +17 -0
- package/dist/recoveryIdentity.js +80 -0
- package/dist/version.js +1 -1
- package/npm-shrinkwrap.json +1740 -0
- package/package.json +21 -7
- package/dist/discover.test.js +0 -51
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { value } from "./cliArgs.js";
|
|
2
|
+
import { completionScript } from "./completion.js";
|
|
3
|
+
import { readCreds } from "./credentials.js";
|
|
4
|
+
import { endpoint, failure, profileName } from "./cliSupport.js";
|
|
5
|
+
import { VERSION } from "./version.js";
|
|
6
|
+
export function completionResult(args) {
|
|
7
|
+
const shell = args.positionals[0];
|
|
8
|
+
if (shell !== "bash" && shell !== "zsh" && shell !== "fish") {
|
|
9
|
+
return failure("completion requires bash, zsh, or fish.", 6, "usage");
|
|
10
|
+
}
|
|
11
|
+
const script = completionScript(shell);
|
|
12
|
+
return { json: { shell, script }, human: script, essential: true, raw: true };
|
|
13
|
+
}
|
|
14
|
+
export function versionResult(args, env) {
|
|
15
|
+
let profile;
|
|
16
|
+
let resolvedEndpoint;
|
|
17
|
+
if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT && value(args, "profile") !== undefined) {
|
|
18
|
+
return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
|
|
19
|
+
}
|
|
20
|
+
if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT) {
|
|
21
|
+
resolvedEndpoint = endpoint(env.PASSPORT_ENDPOINT);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
const creds = readCreds();
|
|
25
|
+
const names = Object.keys(creds);
|
|
26
|
+
const explicitProfile = value(args, "profile");
|
|
27
|
+
const candidate = explicitProfile !== undefined
|
|
28
|
+
? profileName(explicitProfile)
|
|
29
|
+
: env.PASSPORT_PROFILE
|
|
30
|
+
? profileName(env.PASSPORT_PROFILE)
|
|
31
|
+
: names.length === 1
|
|
32
|
+
? profileName(names[0])
|
|
33
|
+
: "";
|
|
34
|
+
if (candidate && creds[candidate]) {
|
|
35
|
+
profile = candidate;
|
|
36
|
+
resolvedEndpoint = endpoint(creds[candidate].endpoint);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const data = {
|
|
40
|
+
version: VERSION,
|
|
41
|
+
...(resolvedEndpoint ? { endpoint: resolvedEndpoint } : {}),
|
|
42
|
+
...(profile ? { profile } : {})
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
json: data,
|
|
46
|
+
human: [
|
|
47
|
+
`passport ${VERSION}`,
|
|
48
|
+
...(resolvedEndpoint ? [`Endpoint: ${resolvedEndpoint}`] : []),
|
|
49
|
+
...(profile ? [`Profile: ${profile}`] : [])
|
|
50
|
+
].join("\n"),
|
|
51
|
+
essential: true
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { ArgError, bool } from "./cliArgs.js";
|
|
2
|
+
import { SERVER_TOO_OLD } from "./cliProtocol.js";
|
|
3
|
+
import { CliFailure, sanitize } from "./cliSupport.js";
|
|
4
|
+
import { VERSION } from "./version.js";
|
|
5
|
+
function helpText(verb) {
|
|
6
|
+
const details = {
|
|
7
|
+
login: "passport login --cloud <origin> [--workspace <id>] [--client <id>] [--profile <name>]\nStarts device sign-in and stores a cli-surface rotating credential.",
|
|
8
|
+
logout: "passport logout [--profile <name>]\nRevokes the rotating credential and always removes the local profile.",
|
|
9
|
+
status: "passport status\nJSON: {workspace,member,endpoint,auth,profile?,client,mcps:[{app,name,status,toolCount}]}",
|
|
10
|
+
doctor: "passport doctor [--profile <name>]\nChecks Node, credential-store safety, endpoint security, server health, authentication, serverInfo, and the exact CLI protocol. JSON includes {ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}.",
|
|
11
|
+
search: "passport search [query...] [--app <key>]\nEmpty query lists the complete permitted catalog. JSON is the server search payload.",
|
|
12
|
+
describe: "passport describe <tool>\nShows the exact tool definition and complete parameter schema.",
|
|
13
|
+
run: "passport run <tool> [json-object]\n --args - read the JSON object from stdin\n --set key=value set a string argument (repeatable)\n --set-json key=<json> set a typed argument (repeatable)\n --wait <sec> retry only a definite approval_pending call\nJSON is the complete MCP tool result; human stdout is verbatim tool text.",
|
|
14
|
+
connect: "passport connect [app...] [--alias <name>] [--open] [--wait <sec>]\nShows member-bound connection links and can wait for sign-in to finish. JSON is the manage_connections payload.",
|
|
15
|
+
resources: "passport resources [uri] [--out <file>]\nLists or reads workspace MCP resources. Binary content requires --out or --json.",
|
|
16
|
+
prompts: "passport prompts [name] [--set key=value] [--out <file>]\nLists or gets workspace MCP prompts. Binary content requires --out or --json.",
|
|
17
|
+
discover: "passport discover\nScans supported local MCP configuration, submits privacy-minimized inventory, and exits 5 when a managed policy reports a violation.",
|
|
18
|
+
session: 'passport session\nReads newline-delimited {"id"?:string|number,"argv":string[]} requests from stdin and emits one JSON response per line. Reuses one authenticated MCP session. Supported request commands: status, search, describe, run, connect, resources, prompts, discover.',
|
|
19
|
+
completion: "passport completion <bash|zsh|fish>\nPrints an offline shell-completion script to stdout.",
|
|
20
|
+
help: "passport help [verb]",
|
|
21
|
+
version: "passport version\nWorks without a profile or network."
|
|
22
|
+
};
|
|
23
|
+
if (verb && details[verb])
|
|
24
|
+
return `${details[verb]}\n\nGlobal: --profile <name> --json --timeout <sec> --quiet --caller <id>`;
|
|
25
|
+
return `Passport CLI ${VERSION}
|
|
26
|
+
|
|
27
|
+
Usage: passport <command> [options]
|
|
28
|
+
|
|
29
|
+
login Sign in with the device flow
|
|
30
|
+
logout Revoke and remove a profile
|
|
31
|
+
status Show identity and visible MCP connection state
|
|
32
|
+
doctor Diagnose local setup and server compatibility
|
|
33
|
+
search Find permitted tools or list the catalog
|
|
34
|
+
describe Show one exact tool definition
|
|
35
|
+
run Run a governed tool
|
|
36
|
+
connect Connect member MCP accounts
|
|
37
|
+
resources List or read MCP resources
|
|
38
|
+
prompts List or get MCP prompts
|
|
39
|
+
discover Scan this computer for direct MCP configuration
|
|
40
|
+
session Reuse one authenticated MCP session for NDJSON commands
|
|
41
|
+
completion Generate bash, zsh, or fish completion
|
|
42
|
+
help Show command help
|
|
43
|
+
version Show CLI version and local context
|
|
44
|
+
|
|
45
|
+
Global: --profile <name> --json --timeout <sec> --quiet --caller <id>
|
|
46
|
+
|
|
47
|
+
Exit codes: 0 success · 1 network/server · 2 auth · 3 needs-connect · 4 approval-pending · 5 policy/guardrail/selection/approval-denial · 6 usage/unknown
|
|
48
|
+
With --json, stdout is exactly one JSON value. Hints and warnings use stderr.`;
|
|
49
|
+
}
|
|
50
|
+
export function helpResult(args) {
|
|
51
|
+
const verb = args.positionals[0];
|
|
52
|
+
const text = helpText(verb);
|
|
53
|
+
return { json: { command: verb ?? null, help: text }, human: text, essential: true };
|
|
54
|
+
}
|
|
55
|
+
export function emitResult(result, args, runtime) {
|
|
56
|
+
if (bool(args, "json")) {
|
|
57
|
+
runtime.stdout.write(`${JSON.stringify(result.json)}\n`);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (result.human === undefined || (bool(args, "quiet") && !result.essential))
|
|
61
|
+
return;
|
|
62
|
+
if (Buffer.isBuffer(result.human))
|
|
63
|
+
runtime.stdout.write(result.human);
|
|
64
|
+
else
|
|
65
|
+
runtime.stdout.write(result.raw ? result.human : `${result.human}${result.human.endsWith("\n") ? "" : "\n"}`);
|
|
66
|
+
}
|
|
67
|
+
export function asFailure(error) {
|
|
68
|
+
if (error instanceof CliFailure)
|
|
69
|
+
return error;
|
|
70
|
+
if (error instanceof ArgError)
|
|
71
|
+
return new CliFailure(sanitize(error.message), 6, "usage");
|
|
72
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
73
|
+
const message = sanitize(raw);
|
|
74
|
+
if (message === SERVER_TOO_OLD || message.includes("CLI-compatible server")) {
|
|
75
|
+
return new CliFailure(SERVER_TOO_OLD, 1, "server_too_old");
|
|
76
|
+
}
|
|
77
|
+
if (/token exchange failed|invalid_or_revoked|unauthori[sz]ed|\b401\b/i.test(message)) {
|
|
78
|
+
return new CliFailure("Passport authentication expired or was revoked.", 2, "auth", {
|
|
79
|
+
hint: "Run: passport login"
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (/timeout|timed out|aborted|aborterror|requesttimeout/i.test(message)) {
|
|
83
|
+
return new CliFailure("The Passport request timed out; it was not retried.", 1, "timeout");
|
|
84
|
+
}
|
|
85
|
+
return new CliFailure(message || "Passport request failed.", 1, "network_or_server");
|
|
86
|
+
}
|
|
87
|
+
export function emitFailure(error, json, quiet, runtime) {
|
|
88
|
+
if (json) {
|
|
89
|
+
runtime.stdout.write(`${JSON.stringify(failurePayload(error))}\n`);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
runtime.stderr.write(`${error.message}\n`);
|
|
93
|
+
}
|
|
94
|
+
if (error.details.hint && !quiet)
|
|
95
|
+
runtime.stderr.write(`${error.details.hint}\n`);
|
|
96
|
+
}
|
|
97
|
+
export function failurePayload(error) {
|
|
98
|
+
return {
|
|
99
|
+
error: error.message,
|
|
100
|
+
cause: error.cause,
|
|
101
|
+
exitCode: error.exitCode,
|
|
102
|
+
...(error.details.approvalId ? { approvalId: error.details.approvalId } : {}),
|
|
103
|
+
...(error.details.app ? { app: error.details.app } : {}),
|
|
104
|
+
...(error.details.connectUrl ? { connectUrl: error.details.connectUrl } : {})
|
|
105
|
+
};
|
|
106
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export const DEFAULT_CLI_PAGINATION_LIMITS = Object.freeze({
|
|
2
|
+
maxPages: 32,
|
|
3
|
+
maxItems: 10_000,
|
|
4
|
+
maxSerializedBytes: 8 * 1024 * 1024,
|
|
5
|
+
maxCursorBytes: 1024
|
|
6
|
+
});
|
|
7
|
+
function validateLimits(limits) {
|
|
8
|
+
for (const [name, value] of Object.entries(limits)) {
|
|
9
|
+
if (!Number.isSafeInteger(value) || value < 1)
|
|
10
|
+
throw new Error(`Invalid CLI pagination limit: ${name}.`);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** Aggregate the MCP pages a one-shot CLI command prints while bounding every
|
|
14
|
+
* attacker/provider-controlled dimension. Cursor cycles fail closed. */
|
|
15
|
+
export async function collectCliPages(kind, load, itemsFrom, limits = DEFAULT_CLI_PAGINATION_LIMITS) {
|
|
16
|
+
validateLimits(limits);
|
|
17
|
+
const items = [];
|
|
18
|
+
const seenCursors = new Set();
|
|
19
|
+
let cursor;
|
|
20
|
+
let serializedBytes = 2; // JSON array brackets.
|
|
21
|
+
for (let pageNumber = 0;; pageNumber += 1) {
|
|
22
|
+
if (pageNumber >= limits.maxPages) {
|
|
23
|
+
throw new Error(`Passport returned more ${kind} pages than the CLI can safely aggregate.`);
|
|
24
|
+
}
|
|
25
|
+
if (cursor !== undefined)
|
|
26
|
+
seenCursors.add(cursor);
|
|
27
|
+
const last = await load(cursor);
|
|
28
|
+
const pageItems = itemsFrom(last);
|
|
29
|
+
if (!Array.isArray(pageItems))
|
|
30
|
+
throw new Error(`Passport returned an invalid ${kind} page.`);
|
|
31
|
+
for (const item of pageItems) {
|
|
32
|
+
if (items.length >= limits.maxItems) {
|
|
33
|
+
throw new Error(`Passport returned more ${kind}s than the CLI can safely aggregate.`);
|
|
34
|
+
}
|
|
35
|
+
const serialized = JSON.stringify(item);
|
|
36
|
+
if (serialized === undefined)
|
|
37
|
+
throw new Error(`Passport returned an invalid ${kind}.`);
|
|
38
|
+
serializedBytes += Buffer.byteLength(serialized) + (items.length ? 1 : 0);
|
|
39
|
+
if (serializedBytes > limits.maxSerializedBytes) {
|
|
40
|
+
throw new Error(`Passport returned ${kind} data larger than the CLI can safely aggregate.`);
|
|
41
|
+
}
|
|
42
|
+
items.push(item);
|
|
43
|
+
}
|
|
44
|
+
const next = last.nextCursor;
|
|
45
|
+
if (next === undefined || next === "")
|
|
46
|
+
return { last, items };
|
|
47
|
+
if (typeof next !== "string" ||
|
|
48
|
+
Buffer.byteLength(next) > limits.maxCursorBytes ||
|
|
49
|
+
next === cursor ||
|
|
50
|
+
seenCursors.has(next)) {
|
|
51
|
+
throw new Error(`Passport returned invalid ${kind} pagination.`);
|
|
52
|
+
}
|
|
53
|
+
cursor = next;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { CliFailure, failure } from "./cliSupport.js";
|
|
2
|
+
export function firstText(result) {
|
|
3
|
+
return result.content
|
|
4
|
+
.filter((part) => part.type === "text")
|
|
5
|
+
.map((part) => part.text)
|
|
6
|
+
.join("");
|
|
7
|
+
}
|
|
8
|
+
export function hasNonText(result) {
|
|
9
|
+
return result.content.some((part) => part.type !== "text");
|
|
10
|
+
}
|
|
11
|
+
export function payloadOf(result, label) {
|
|
12
|
+
const text = firstText(result);
|
|
13
|
+
if (text) {
|
|
14
|
+
try {
|
|
15
|
+
const parsed = JSON.parse(text);
|
|
16
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
17
|
+
return parsed;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
/* structured content may carry a future server payload */
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (result.structuredContent && !result.structuredContent.cause)
|
|
24
|
+
return result.structuredContent;
|
|
25
|
+
return failure(`Passport returned an invalid ${label} payload.`, 1, "invalid_server_response");
|
|
26
|
+
}
|
|
27
|
+
export function refusalOf(result) {
|
|
28
|
+
const structured = result.structuredContent;
|
|
29
|
+
if (result._meta?.["passport/refusal"] !== true) {
|
|
30
|
+
return result.isError
|
|
31
|
+
? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error")
|
|
32
|
+
: undefined;
|
|
33
|
+
}
|
|
34
|
+
const cause = typeof structured?.cause === "string" ? structured.cause : "";
|
|
35
|
+
if (!cause) {
|
|
36
|
+
return new CliFailure("Passport returned an invalid refusal payload.", 1, "invalid_server_response");
|
|
37
|
+
}
|
|
38
|
+
const recognized = new Set(["needs_connect", "approval_pending", "approval_denied", "blocked", "unknown_tool"]);
|
|
39
|
+
if (!recognized.has(cause)) {
|
|
40
|
+
return result.isError
|
|
41
|
+
? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error")
|
|
42
|
+
: undefined;
|
|
43
|
+
}
|
|
44
|
+
const app = typeof structured?.app === "string" ? structured.app : undefined;
|
|
45
|
+
const approvalId = typeof structured?.approvalId === "string" ? structured.approvalId : undefined;
|
|
46
|
+
const connectUrl = (() => {
|
|
47
|
+
if (typeof structured?.connectUrl !== "string")
|
|
48
|
+
return undefined;
|
|
49
|
+
try {
|
|
50
|
+
const parsed = new URL(structured.connectUrl);
|
|
51
|
+
return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.toString() : undefined;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
})();
|
|
57
|
+
let message = firstText(result) || "Passport refused the call.";
|
|
58
|
+
if (cause === "needs_connect") {
|
|
59
|
+
return new CliFailure(message, 3, cause, {
|
|
60
|
+
app,
|
|
61
|
+
connectUrl,
|
|
62
|
+
hint: connectUrl
|
|
63
|
+
? "Finish the browser sign-in, then retry the command."
|
|
64
|
+
: `Run: passport connect ${app ?? "<app>"}`
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
if (cause === "approval_pending") {
|
|
68
|
+
if (approvalId && !message.includes(approvalId))
|
|
69
|
+
message = `${message}\nApproval ID: ${approvalId}`;
|
|
70
|
+
return new CliFailure(message, 4, cause, { app, approvalId });
|
|
71
|
+
}
|
|
72
|
+
if (cause === "approval_denied" || cause === "blocked") {
|
|
73
|
+
return new CliFailure(message, 5, cause, { app, approvalId });
|
|
74
|
+
}
|
|
75
|
+
if (cause === "unknown_tool")
|
|
76
|
+
return new CliFailure(message, 6, cause, { app });
|
|
77
|
+
return new CliFailure(`Passport returned an unsupported refusal cause: ${cause}.`, 1, "invalid_server_response", {
|
|
78
|
+
app,
|
|
79
|
+
approvalId
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
export function requireSuccess(result) {
|
|
83
|
+
const refusal = refusalOf(result);
|
|
84
|
+
if (refusal)
|
|
85
|
+
throw refusal;
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { once } from "node:events";
|
|
2
|
+
import { bool, parseArgs, value } from "./cliArgs.js";
|
|
3
|
+
import { asFailure, failurePayload } from "./cliOutput.js";
|
|
4
|
+
import { callerFrom, CliFailure, failure, resolveCliAuth, timeoutMs } from "./cliSupport.js";
|
|
5
|
+
export const CLI_SESSION_LINE_MAX_BYTES = 1024 * 1024;
|
|
6
|
+
export const CLI_SESSION_ARGV_MAX_ITEMS = 128;
|
|
7
|
+
/**
|
|
8
|
+
* Split an async byte stream into bounded UTF-8 lines. The limit applies before
|
|
9
|
+
* decoding, so a caller cannot grow an unbounded string while omitting `\n`.
|
|
10
|
+
*/
|
|
11
|
+
export async function* readBoundedSessionLines(input, signal, maxBytes = CLI_SESSION_LINE_MAX_BYTES) {
|
|
12
|
+
const iterator = input[Symbol.asyncIterator]();
|
|
13
|
+
let pending = Buffer.alloc(0);
|
|
14
|
+
let rejectAborted = () => { };
|
|
15
|
+
const fail = () => rejectAborted(signal.reason ?? new Error("Cancelled."));
|
|
16
|
+
const aborted = new Promise((_, reject) => {
|
|
17
|
+
rejectAborted = reject;
|
|
18
|
+
});
|
|
19
|
+
if (signal.aborted)
|
|
20
|
+
fail();
|
|
21
|
+
else
|
|
22
|
+
signal.addEventListener("abort", fail, { once: true });
|
|
23
|
+
try {
|
|
24
|
+
for (;;) {
|
|
25
|
+
const step = await Promise.race([iterator.next(), aborted]);
|
|
26
|
+
if (step.done)
|
|
27
|
+
break;
|
|
28
|
+
const chunk = Buffer.from(step.value);
|
|
29
|
+
let offset = 0;
|
|
30
|
+
for (;;) {
|
|
31
|
+
const newline = chunk.indexOf(0x0a, offset);
|
|
32
|
+
const end = newline < 0 ? chunk.length : newline;
|
|
33
|
+
const segment = chunk.subarray(offset, end);
|
|
34
|
+
if (pending.byteLength + segment.byteLength > maxBytes) {
|
|
35
|
+
throw new CliFailure(`Session input lines are limited to ${maxBytes} bytes.`, 6, "usage");
|
|
36
|
+
}
|
|
37
|
+
if (segment.byteLength)
|
|
38
|
+
pending = Buffer.concat([pending, segment]);
|
|
39
|
+
if (newline < 0)
|
|
40
|
+
break;
|
|
41
|
+
const line = pending.byteLength && pending[pending.byteLength - 1] === 0x0d ? pending.subarray(0, -1) : pending;
|
|
42
|
+
yield line.toString("utf8");
|
|
43
|
+
pending = Buffer.alloc(0);
|
|
44
|
+
offset = newline + 1;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (pending.byteLength)
|
|
48
|
+
yield pending.toString("utf8");
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
signal.removeEventListener("abort", fail);
|
|
52
|
+
await iterator.return?.();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export function parseSessionRequest(line) {
|
|
56
|
+
if (!line.trim())
|
|
57
|
+
return undefined;
|
|
58
|
+
let parsed;
|
|
59
|
+
try {
|
|
60
|
+
parsed = JSON.parse(line);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
throw new CliFailure("Session input must contain one JSON object per line.", 6, "usage");
|
|
64
|
+
}
|
|
65
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
66
|
+
throw new CliFailure("Each session request must be a JSON object.", 6, "usage");
|
|
67
|
+
}
|
|
68
|
+
const request = parsed;
|
|
69
|
+
if (request.id !== undefined &&
|
|
70
|
+
!((typeof request.id === "string" && Buffer.byteLength(request.id) <= 128) ||
|
|
71
|
+
(typeof request.id === "number" && Number.isSafeInteger(request.id)))) {
|
|
72
|
+
throw new CliFailure("Session request id must be a safe integer or a string of at most 128 bytes.", 6, "usage");
|
|
73
|
+
}
|
|
74
|
+
if (!Array.isArray(request.argv) ||
|
|
75
|
+
request.argv.length === 0 ||
|
|
76
|
+
request.argv.length > CLI_SESSION_ARGV_MAX_ITEMS ||
|
|
77
|
+
!request.argv.every((part) => typeof part === "string")) {
|
|
78
|
+
throw new CliFailure(`Session request argv must contain 1-${CLI_SESSION_ARGV_MAX_ITEMS} strings.`, 6, "usage");
|
|
79
|
+
}
|
|
80
|
+
return { ...(request.id !== undefined ? { id: request.id } : {}), argv: request.argv };
|
|
81
|
+
}
|
|
82
|
+
const SESSION_COMMANDS = new Set([
|
|
83
|
+
"status",
|
|
84
|
+
"search",
|
|
85
|
+
"describe",
|
|
86
|
+
"run",
|
|
87
|
+
"connect",
|
|
88
|
+
"resources",
|
|
89
|
+
"prompts",
|
|
90
|
+
"discover"
|
|
91
|
+
]);
|
|
92
|
+
async function writeSessionResponse(runtime, value) {
|
|
93
|
+
if (runtime.stdout.write(`${JSON.stringify(value)}\n`) !== false)
|
|
94
|
+
return;
|
|
95
|
+
// A long-running producer must honor pipe backpressure or a slow agent could
|
|
96
|
+
// make Node retain an unbounded queue of otherwise bounded results.
|
|
97
|
+
await once(runtime.stdout, "drain", { signal: runtime.signal });
|
|
98
|
+
}
|
|
99
|
+
export function writeCliSessionFailure(runtime, error) {
|
|
100
|
+
return writeSessionResponse(runtime, { ok: false, ...failurePayload(error) });
|
|
101
|
+
}
|
|
102
|
+
/** Keep one token manager and MCP client alive while processing sequential
|
|
103
|
+
* NDJSON requests. Authorization and policy still run at the gateway for every
|
|
104
|
+
* operation; only local process, token-exchange, initialization, and protocol
|
|
105
|
+
* assertion overhead is shared. */
|
|
106
|
+
export async function runCliSession(args, runtime, dispatch) {
|
|
107
|
+
const auth = resolveCliAuth(args, runtime.env);
|
|
108
|
+
const { CliGateway } = await import("./cliClient.js");
|
|
109
|
+
const gateway = await CliGateway.connect({
|
|
110
|
+
auth,
|
|
111
|
+
caller: callerFrom(args, runtime.env),
|
|
112
|
+
timeoutMs: timeoutMs(args),
|
|
113
|
+
signal: runtime.signal
|
|
114
|
+
});
|
|
115
|
+
try {
|
|
116
|
+
await gateway.assertCliProtocol();
|
|
117
|
+
const nestedRuntime = { ...runtime, sharedGateway: { gateway, auth } };
|
|
118
|
+
for await (const line of readBoundedSessionLines(runtime.stdin ?? process.stdin, runtime.signal)) {
|
|
119
|
+
let id;
|
|
120
|
+
try {
|
|
121
|
+
const request = parseSessionRequest(line);
|
|
122
|
+
if (!request)
|
|
123
|
+
continue;
|
|
124
|
+
id = request.id;
|
|
125
|
+
const nested = parseArgs(request.argv);
|
|
126
|
+
if (!SESSION_COMMANDS.has(nested.command)) {
|
|
127
|
+
return failure(`Command "${nested.command}" is not available in session mode.`, 6, "usage");
|
|
128
|
+
}
|
|
129
|
+
if (value(nested, "profile") !== undefined ||
|
|
130
|
+
value(nested, "caller") !== undefined ||
|
|
131
|
+
value(nested, "timeout") !== undefined ||
|
|
132
|
+
bool(nested, "quiet") ||
|
|
133
|
+
bool(nested, "json")) {
|
|
134
|
+
return failure("Set global options on `passport session`; per-request --profile, --caller, --timeout, --quiet, and --json are not allowed.", 6, "usage");
|
|
135
|
+
}
|
|
136
|
+
if (nested.command === "run" && value(nested, "args") === "-") {
|
|
137
|
+
return failure("Session run requests cannot use --args -; include arguments in argv instead.", 6, "usage");
|
|
138
|
+
}
|
|
139
|
+
nested.booleans.add("json");
|
|
140
|
+
const result = await dispatch(nested, nestedRuntime);
|
|
141
|
+
const exitCode = result.exitCode ?? 0;
|
|
142
|
+
await writeSessionResponse(runtime, {
|
|
143
|
+
...(id !== undefined ? { id } : {}),
|
|
144
|
+
ok: exitCode === 0,
|
|
145
|
+
result: result.json,
|
|
146
|
+
exitCode
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
const cliError = asFailure(error);
|
|
151
|
+
await writeSessionResponse(runtime, {
|
|
152
|
+
...(id !== undefined ? { id } : {}),
|
|
153
|
+
ok: false,
|
|
154
|
+
...failurePayload(cliError)
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { json: { closed: true }, exitCode: 0 };
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
await gateway.close();
|
|
162
|
+
}
|
|
163
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { value } from "./cliArgs.js";
|
|
3
|
+
import { assertProfileName, readCreds } from "./credentials.js";
|
|
4
|
+
import { readBoundedJson } from "./boundedResponse.js";
|
|
5
|
+
export { readBoundedJson } from "./boundedResponse.js";
|
|
6
|
+
export const DEFAULT_TIMEOUT_MS = 30_000;
|
|
7
|
+
export class CliFailure extends Error {
|
|
8
|
+
exitCode;
|
|
9
|
+
cause;
|
|
10
|
+
details;
|
|
11
|
+
constructor(message, exitCode, cause, details = {}) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.exitCode = exitCode;
|
|
14
|
+
this.cause = cause;
|
|
15
|
+
this.details = details;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function failure(message, exitCode, cause, details = {}) {
|
|
19
|
+
throw new CliFailure(message, exitCode, cause, details);
|
|
20
|
+
}
|
|
21
|
+
export function timeoutMs(args) {
|
|
22
|
+
return Math.ceil(Number(value(args, "timeout") ?? DEFAULT_TIMEOUT_MS / 1000) * 1000);
|
|
23
|
+
}
|
|
24
|
+
export function profileName(raw) {
|
|
25
|
+
try {
|
|
26
|
+
assertProfileName(raw);
|
|
27
|
+
return raw;
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
return failure(error instanceof Error ? error.message : "Invalid profile name.", 6, "usage");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function endpoint(raw) {
|
|
34
|
+
try {
|
|
35
|
+
const parsed = new URL(raw);
|
|
36
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
37
|
+
throw new Error();
|
|
38
|
+
if (parsed.username || parsed.password) {
|
|
39
|
+
return failure("Passport endpoint URLs cannot contain a username or password.", 6, "usage");
|
|
40
|
+
}
|
|
41
|
+
const host = parsed.hostname.toLowerCase();
|
|
42
|
+
const loopback = host === "localhost" || host === "[::1]" || host === "::1" || /^127(?:\.\d{1,3}){3}$/.test(host);
|
|
43
|
+
if (parsed.protocol === "http:" && !loopback) {
|
|
44
|
+
return failure("Passport CLI requires HTTPS for remote servers. Configure HTTPS for your self-hosted Passport deployment; plain HTTP is allowed only on localhost, 127.0.0.0/8, or ::1.", 6, "usage");
|
|
45
|
+
}
|
|
46
|
+
return parsed.toString().replace(/\/$/, "");
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error instanceof CliFailure)
|
|
50
|
+
throw error;
|
|
51
|
+
return failure("Passport endpoint must be an http or https URL.", 6, "usage");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export function cloudOrigin(raw) {
|
|
55
|
+
const normalized = endpoint(raw);
|
|
56
|
+
const parsed = new URL(normalized);
|
|
57
|
+
if (parsed.pathname !== "/" || parsed.search || parsed.hash) {
|
|
58
|
+
return failure("--cloud must be a Passport origin without a path, query, or fragment.", 6, "usage");
|
|
59
|
+
}
|
|
60
|
+
return parsed.origin;
|
|
61
|
+
}
|
|
62
|
+
export function sameOriginWebUrl(raw, trustedOrigin, label) {
|
|
63
|
+
const normalized = endpoint(raw);
|
|
64
|
+
if (new URL(normalized).origin !== trustedOrigin) {
|
|
65
|
+
return failure(`Passport returned ${label} on a different origin; the operation was refused.`, 1, "invalid_server_response");
|
|
66
|
+
}
|
|
67
|
+
return normalized;
|
|
68
|
+
}
|
|
69
|
+
export function resolveCliAuth(args, env) {
|
|
70
|
+
const explicitProfile = value(args, "profile");
|
|
71
|
+
const agentKey = env.PASSPORT_AGENT_KEY ?? "";
|
|
72
|
+
const agentEndpoint = env.PASSPORT_ENDPOINT ?? "";
|
|
73
|
+
if (agentKey || agentEndpoint) {
|
|
74
|
+
if (!agentKey || !agentEndpoint) {
|
|
75
|
+
return failure("PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT must be set together.", 2, "auth", {
|
|
76
|
+
hint: "Set both variables, or run: passport login"
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
if (explicitProfile !== undefined) {
|
|
80
|
+
return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
|
|
81
|
+
}
|
|
82
|
+
return { kind: "agent-key", endpoint: endpoint(agentEndpoint), agentKey };
|
|
83
|
+
}
|
|
84
|
+
const creds = readCreds();
|
|
85
|
+
const names = Object.keys(creds).sort();
|
|
86
|
+
const fallbackProfile = env.PASSPORT_PROFILE || (names.length === 1 ? names[0] : "");
|
|
87
|
+
const profile = explicitProfile !== undefined ? profileName(explicitProfile) : fallbackProfile ? profileName(fallbackProfile) : "";
|
|
88
|
+
if (!profile) {
|
|
89
|
+
const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
|
|
90
|
+
return failure(`No Passport profile selected.${suffix}`, 2, "auth", { hint: "Run: passport login" });
|
|
91
|
+
}
|
|
92
|
+
const saved = creds[profile];
|
|
93
|
+
if (!saved) {
|
|
94
|
+
const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
|
|
95
|
+
return failure(`Passport profile "${profile}" does not exist.${suffix}`, 2, "auth", {
|
|
96
|
+
hint: "Run: passport login"
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return { kind: "profile", endpoint: endpoint(saved.endpoint), profile, refreshToken: saved.refreshToken };
|
|
100
|
+
}
|
|
101
|
+
export function callerFrom(args, env) {
|
|
102
|
+
const explicit = value(args, "caller");
|
|
103
|
+
if (explicit !== undefined) {
|
|
104
|
+
const normalized = explicit.trim().toLowerCase();
|
|
105
|
+
if (!/^[a-z0-9-]{1,24}$/.test(normalized)) {
|
|
106
|
+
return failure("--caller must contain 1-24 lowercase letters, numbers, or hyphens.", 6, "usage");
|
|
107
|
+
}
|
|
108
|
+
return normalized;
|
|
109
|
+
}
|
|
110
|
+
const keys = Object.keys(env);
|
|
111
|
+
if (Object.hasOwn(env, "CLAUDECODE") || keys.some((key) => key.startsWith("CLAUDE_CODE")))
|
|
112
|
+
return "claude-code";
|
|
113
|
+
if (Object.hasOwn(env, "CODEX_SANDBOX") || keys.some((key) => key.startsWith("CODEX_")))
|
|
114
|
+
return "codex";
|
|
115
|
+
if (Object.hasOwn(env, "OPENCODE") || keys.some((key) => key.startsWith("OPENCODE_")))
|
|
116
|
+
return "opencode";
|
|
117
|
+
if (Object.hasOwn(env, "CURSOR_TRACE_ID") || keys.some((key) => key.startsWith("CURSOR_")))
|
|
118
|
+
return "cursor";
|
|
119
|
+
if (Object.hasOwn(env, "GEMINI_CLI"))
|
|
120
|
+
return "gemini";
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
export function sanitize(message) {
|
|
124
|
+
return message
|
|
125
|
+
.slice(0, 2_000)
|
|
126
|
+
.replace(/Bearer\s+\S+/gi, "Bearer [redacted]")
|
|
127
|
+
.replace(/("(?:refreshToken|refresh-token|accessToken|access-token|token|agentKey|agent_key|agent-key|apiKey|api_key|api-key|clientSecret|client_secret|client-secret)"\s*:\s*")[^"]*"/gi, '$1[redacted]"')
|
|
128
|
+
.replace(/((?:refreshToken|refresh-token|accessToken|access-token|token|agentKey|agent_key|agent-key|apiKey|api_key|api-key|agent-key|clientSecret|client_secret|client-secret)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&}]+)/gi, "$1[redacted]")
|
|
129
|
+
.replace(/\b(?:[A-Za-z0-9_-]+~)?(?:pak|ppr|ppa|pp)_[A-Za-z0-9_-]{12,}\b/g, "[redacted]")
|
|
130
|
+
.slice(0, 500);
|
|
131
|
+
}
|
|
132
|
+
export async function timedFetch(input, init, ms, parent) {
|
|
133
|
+
return fetch(input, {
|
|
134
|
+
...init,
|
|
135
|
+
redirect: "error",
|
|
136
|
+
signal: AbortSignal.any([parent, AbortSignal.timeout(ms)])
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
export async function safeApiError(response, fallback) {
|
|
140
|
+
try {
|
|
141
|
+
const body = await readBoundedJson(response, 64 * 1024);
|
|
142
|
+
return typeof body.error === "string" ? sanitize(body.error) : fallback;
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return fallback;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
export function sleep(ms, signal) {
|
|
149
|
+
return new Promise((resolve, reject) => {
|
|
150
|
+
if (signal.aborted) {
|
|
151
|
+
reject(signal.reason);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const timer = setTimeout(done, ms);
|
|
155
|
+
function done() {
|
|
156
|
+
signal.removeEventListener("abort", cancelled);
|
|
157
|
+
resolve();
|
|
158
|
+
}
|
|
159
|
+
function cancelled() {
|
|
160
|
+
clearTimeout(timer);
|
|
161
|
+
signal.removeEventListener("abort", cancelled);
|
|
162
|
+
reject(signal.reason);
|
|
163
|
+
}
|
|
164
|
+
signal.addEventListener("abort", cancelled, { once: true });
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/** Open only a validated web URL. A provider-controlled query string must stay
|
|
168
|
+
* one opaque process argument and never cross a command-shell boundary. */
|
|
169
|
+
export function openUrl(url, platform = process.platform, launch = spawn) {
|
|
170
|
+
try {
|
|
171
|
+
const parsed = new URL(url);
|
|
172
|
+
if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.username || parsed.password) {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
const command = platform === "darwin" ? "open" : platform === "win32" ? "rundll32.exe" : "xdg-open";
|
|
176
|
+
const args = platform === "win32" ? ["url.dll,FileProtocolHandler", parsed.toString()] : [parsed.toString()];
|
|
177
|
+
const child = launch(command, args, { stdio: "ignore", detached: true, shell: false });
|
|
178
|
+
child.on("error", () => { });
|
|
179
|
+
child.unref();
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
/* the printed URL remains usable */
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
export function firstSentence(value) {
|
|
188
|
+
const trimmed = value.trim().replace(/\s+/g, " ");
|
|
189
|
+
const match = trimmed.match(/^.*?[.!?](?:\s|$)/);
|
|
190
|
+
return (match?.[0] ?? trimmed).trim();
|
|
191
|
+
}
|