passport-bridge 0.5.0 → 0.6.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.
@@ -0,0 +1,162 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
+ import { TokenManager } from "./bridge.js";
4
+ import { getProfile, withProfileLock, writeProfile } from "./credentials.js";
5
+ import { VERSION } from "./version.js";
6
+ import { SERVER_TOO_OLD } from "./cliProtocol.js";
7
+ export { SERVER_TOO_OLD } from "./cliProtocol.js";
8
+ const MIN_CLI_SERVER = [0, 5, 0];
9
+ export const MIN_CLI_SERVER_VERSION = MIN_CLI_SERVER.join(".");
10
+ export const CLI_PROTOCOL_TOOLS = ["passport_search_tools", "passport_call", "passport_manage_connections", "passport_wait_for_connection"];
11
+ export function supportsCliServerInfo(info) {
12
+ if (info?.name !== "passport" || typeof info.version !== "string")
13
+ return false;
14
+ const match = info.version.match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);
15
+ if (!match)
16
+ return false;
17
+ const version = match.slice(1, 4).map(Number);
18
+ for (let index = 0; index < MIN_CLI_SERVER.length; index += 1) {
19
+ if (version[index] !== MIN_CLI_SERVER[index])
20
+ return version[index] > MIN_CLI_SERVER[index];
21
+ }
22
+ return true;
23
+ }
24
+ function decorateFetch(base, headersToAdd) {
25
+ return (async (input, init) => {
26
+ const headers = new Headers(input instanceof Request ? input.headers : undefined);
27
+ new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
28
+ for (const [name, value] of Object.entries(headersToAdd))
29
+ headers.set(name, value);
30
+ return base(input, { ...init, headers });
31
+ });
32
+ }
33
+ async function deadline(promise, ms, onTimeout) {
34
+ let timer;
35
+ const expired = new Promise((_, reject) => {
36
+ timer = setTimeout(() => {
37
+ onTimeout();
38
+ const error = new Error(`Request timed out after ${Math.ceil(ms / 1000)} seconds.`);
39
+ error.name = "TimeoutError";
40
+ reject(error);
41
+ }, ms);
42
+ timer.unref?.();
43
+ });
44
+ try {
45
+ return await Promise.race([promise, expired]);
46
+ }
47
+ finally {
48
+ if (timer)
49
+ clearTimeout(timer);
50
+ }
51
+ }
52
+ /** One authenticated MCP session for one CLI invocation. */
53
+ export class CliGateway {
54
+ client = new Client({ name: "passport-cli", version: VERSION });
55
+ transport;
56
+ timeoutMs;
57
+ signal;
58
+ closed = false;
59
+ constructor(options) {
60
+ this.timeoutMs = options.timeoutMs;
61
+ this.signal = options.signal;
62
+ let authedFetch;
63
+ if (options.auth.kind === "agent-key") {
64
+ authedFetch = decorateFetch(fetch, {
65
+ authorization: `Bearer ${options.auth.agentKey}`,
66
+ "x-passport-surface": "cli",
67
+ ...(options.caller ? { "x-passport-caller": options.caller } : {})
68
+ });
69
+ }
70
+ else {
71
+ const { endpoint, profile } = options.auth;
72
+ const manager = new TokenManager(endpoint, options.auth.refreshToken, (next) => writeProfile(profile, { refreshToken: next, endpoint }), {
73
+ reload: () => getProfile(profile)?.refreshToken,
74
+ lock: (fn) => withProfileLock(profile, fn)
75
+ }, options.timeoutMs, options.signal);
76
+ authedFetch = options.caller
77
+ ? decorateFetch(manager.authedFetch, { "x-passport-caller": options.caller })
78
+ : manager.authedFetch;
79
+ }
80
+ this.transport = new StreamableHTTPClientTransport(new URL(options.auth.endpoint), { fetch: authedFetch });
81
+ }
82
+ static async connect(options) {
83
+ const gateway = new CliGateway(options);
84
+ try {
85
+ await deadline(gateway.client.connect(gateway.transport), options.timeoutMs, () => {
86
+ void gateway.transport.close().catch(() => { });
87
+ });
88
+ return gateway;
89
+ }
90
+ catch (error) {
91
+ await gateway.close();
92
+ throw error;
93
+ }
94
+ }
95
+ /** A CLI-surface credential must always receive all four stable meta-tools. */
96
+ async assertCliProtocol() {
97
+ // serverInfo arrives during MCP initialization and has no side effects.
98
+ // Check it before even listing tools so an older compact server cannot turn
99
+ // an approval-pending result without structured cause into false success.
100
+ const diagnostic = await this.protocolDiagnostics();
101
+ if (!diagnostic.serverCompatible || !diagnostic.toolsExact)
102
+ throw new Error(SERVER_TOO_OLD);
103
+ }
104
+ /** Side-effect-free serverInfo + tools/list detail for `passport doctor`. */
105
+ async protocolDiagnostics() {
106
+ const info = this.client.getServerVersion();
107
+ const tools = (await this.client.listTools({}, this.requestOptions())).tools.map((tool) => tool.name).sort();
108
+ const required = [...CLI_PROTOCOL_TOOLS].sort();
109
+ return {
110
+ server: info ? { name: info.name, version: info.version } : undefined,
111
+ serverCompatible: supportsCliServerInfo(info),
112
+ tools,
113
+ toolsExact: tools.length === required.length && required.every((name, index) => tools[index] === name)
114
+ };
115
+ }
116
+ callTool(name, args, timeoutMs = this.timeoutMs) {
117
+ return this.client.callTool({ name, arguments: args }, undefined, this.requestOptions(timeoutMs));
118
+ }
119
+ async listResources() {
120
+ const resources = [];
121
+ let cursor;
122
+ let last;
123
+ do {
124
+ last = await this.client.listResources(cursor ? { cursor } : {}, this.requestOptions());
125
+ resources.push(...last.resources);
126
+ cursor = last.nextCursor;
127
+ } while (cursor);
128
+ return { ...(last ?? { resources: [] }), resources, nextCursor: undefined };
129
+ }
130
+ readResource(uri) {
131
+ return this.client.readResource({ uri }, this.requestOptions());
132
+ }
133
+ async listPrompts() {
134
+ const prompts = [];
135
+ let cursor;
136
+ let last;
137
+ do {
138
+ last = await this.client.listPrompts(cursor ? { cursor } : {}, this.requestOptions());
139
+ prompts.push(...last.prompts);
140
+ cursor = last.nextCursor;
141
+ } while (cursor);
142
+ return { ...(last ?? { prompts: [] }), prompts, nextCursor: undefined };
143
+ }
144
+ getPrompt(name, args) {
145
+ return this.client.getPrompt({ name, arguments: args }, this.requestOptions());
146
+ }
147
+ async close() {
148
+ if (this.closed)
149
+ return;
150
+ this.closed = true;
151
+ try {
152
+ await this.client.close();
153
+ }
154
+ catch {
155
+ /* transport close below is authoritative */
156
+ }
157
+ await this.transport.close().catch(() => { });
158
+ }
159
+ requestOptions(timeoutMs = this.timeoutMs) {
160
+ return { timeout: timeoutMs, maxTotalTimeout: timeoutMs, ...(this.signal ? { signal: this.signal } : {}) };
161
+ }
162
+ }
@@ -0,0 +1,4 @@
1
+ /** Dependency-free protocol messages shared by the CLI entrypoint and MCP
2
+ * client. Keeping this separate lets `passport version` run directly from an
3
+ * extracted tarball without loading the MCP SDK or touching the network. */
4
+ export const SERVER_TOO_OLD = "This Passport server is too old for the CLI. Ask your admin to deploy the CLI-compatible server release first.";
@@ -0,0 +1,132 @@
1
+ import { COMMANDS } from "./cliArgs.js";
2
+ const DESCRIPTIONS = {
3
+ login: "Sign in with the device flow",
4
+ logout: "Revoke and remove a profile",
5
+ status: "Show identity and MCP connection state",
6
+ doctor: "Diagnose local configuration and server compatibility",
7
+ search: "Find permitted tools",
8
+ describe: "Show one exact tool definition",
9
+ run: "Run a governed tool",
10
+ connect: "Connect member MCP accounts",
11
+ resources: "List or read MCP resources",
12
+ prompts: "List or get MCP prompts",
13
+ completion: "Generate shell completion",
14
+ help: "Show command help",
15
+ version: "Show CLI version and local context"
16
+ };
17
+ const GLOBAL = ["--profile", "--json", "--timeout", "--quiet", "--caller", "--help"];
18
+ const COMMAND_FLAGS = {
19
+ login: ["--cloud", "--workspace", "--client"],
20
+ search: ["--app"],
21
+ run: ["--args", "--set", "--set-json", "--wait"],
22
+ connect: ["--alias", "--open", "--wait"],
23
+ resources: ["--out"],
24
+ prompts: ["--set", "--out"]
25
+ };
26
+ const VALUE_FLAGS = new Set([
27
+ "--profile", "--timeout", "--caller", "--cloud", "--workspace", "--client",
28
+ "--app", "--args", "--set", "--set-json", "--wait", "--alias", "--out"
29
+ ]);
30
+ function flagsFor(command) {
31
+ return [...GLOBAL, ...(command ? COMMAND_FLAGS[command] ?? [] : [])];
32
+ }
33
+ function bash() {
34
+ const commandWords = COMMANDS.join(" ");
35
+ const cases = COMMANDS.map((command) => ` ${command}) opts="${flagsFor(command).join(" ")}" ;;`).join("\n");
36
+ const valueFlags = [...VALUE_FLAGS].join("|");
37
+ return `# bash completion for Passport CLI
38
+ _passport_completion() {
39
+ local cur command opts
40
+ COMPREPLY=()
41
+ cur="\${COMP_WORDS[COMP_CWORD]}"
42
+ command="\${COMP_WORDS[1]}"
43
+ if (( COMP_CWORD == 1 )); then
44
+ COMPREPLY=( $(compgen -W "${commandWords}" -- "$cur") )
45
+ return
46
+ fi
47
+ if [[ "$command" == "completion" && $COMP_CWORD -eq 2 ]]; then
48
+ COMPREPLY=( $(compgen -W "bash zsh fish" -- "$cur") )
49
+ return
50
+ fi
51
+ case "\${COMP_WORDS[COMP_CWORD-1]}" in
52
+ ${valueFlags}) return ;;
53
+ esac
54
+ case "$command" in
55
+ ${cases}
56
+ *) opts="${GLOBAL.join(" ")}" ;;
57
+ esac
58
+ [[ "$cur" == -* ]] && COMPREPLY=( $(compgen -W "$opts" -- "$cur") )
59
+ }
60
+ complete -F _passport_completion passport
61
+ `;
62
+ }
63
+ function zsh() {
64
+ const commands = COMMANDS.map((command) => ` '${command}:${DESCRIPTIONS[command]}'`).join("\n");
65
+ const cases = COMMANDS.map((command) => {
66
+ const flags = (COMMAND_FLAGS[command] ?? []).map((flag) => ` '${flag}[${flag.slice(2).replaceAll("-", " ")}]${VALUE_FLAGS.has(flag) ? ":value:" : ""}'`).join("");
67
+ return flags ? ` ${command}) opts+=(${flags.trimStart()}) ;;` : "";
68
+ }).filter(Boolean).join("\n");
69
+ return `#compdef passport
70
+ _passport() {
71
+ local -a commands opts
72
+ commands=(
73
+ ${commands}
74
+ )
75
+ if (( CURRENT == 2 )); then
76
+ _describe 'command' commands
77
+ return
78
+ fi
79
+ if [[ "$words[2]" == completion && CURRENT == 3 ]]; then
80
+ _values 'shell' bash zsh fish
81
+ return
82
+ fi
83
+ opts=(
84
+ '--profile[select a stored profile]:profile:'
85
+ '--json[emit one JSON value]'
86
+ '--timeout[request timeout in seconds]:seconds:'
87
+ '--quiet[suppress nonessential hints]'
88
+ '--caller[set cooperative caller attribution]:caller:'
89
+ '--help[show command help]'
90
+ )
91
+ case "$words[2]" in
92
+ ${cases}
93
+ esac
94
+ _arguments -s $opts '*:argument:'
95
+ }
96
+ compdef _passport passport
97
+ `;
98
+ }
99
+ function fish() {
100
+ const lines = [
101
+ "# fish completion for Passport CLI",
102
+ "complete -c passport -f"
103
+ ];
104
+ for (const command of COMMANDS) {
105
+ lines.push(`complete -c passport -n '__fish_use_subcommand' -a ${command} -d '${DESCRIPTIONS[command]}'`);
106
+ }
107
+ const global = [
108
+ ["profile", "Select a stored profile", true],
109
+ ["json", "Emit one JSON value", false],
110
+ ["timeout", "Request timeout in seconds", true],
111
+ ["quiet", "Suppress nonessential hints", false],
112
+ ["caller", "Set cooperative caller attribution", true],
113
+ ["help", "Show command help", false]
114
+ ];
115
+ for (const [flag, description, required] of global) {
116
+ lines.push(`complete -c passport -l ${flag}${required ? " -r" : ""} -d '${description}'`);
117
+ }
118
+ for (const [command, flags] of Object.entries(COMMAND_FLAGS)) {
119
+ for (const flag of flags) {
120
+ lines.push(`complete -c passport -n '__fish_seen_subcommand_from ${command}' -l ${flag.slice(2)}${VALUE_FLAGS.has(flag) ? " -r" : ""}`);
121
+ }
122
+ }
123
+ lines.push("complete -c passport -n '__fish_seen_subcommand_from completion' -a 'bash zsh fish'");
124
+ return `${lines.join("\n")}\n`;
125
+ }
126
+ export function completionScript(shell) {
127
+ if (shell === "bash")
128
+ return bash();
129
+ if (shell === "zsh")
130
+ return zsh();
131
+ return fish();
132
+ }
@@ -1,6 +1,15 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
- import { mkdirSync, readFileSync, writeFileSync, existsSync, chmodSync, rmSync, statSync } from "node:fs";
3
+ import { mkdirSync, readFileSync, writeFileSync, chmodSync, rmSync, statSync, renameSync } from "node:fs";
4
+ import { randomBytes } from "node:crypto";
5
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,79}$/;
6
+ const UNSAFE_PROFILE_KEYS = new Set(["__proto__", "prototype", "constructor"]);
7
+ /** Profile names become both JSON keys and mkdir-based lock names. */
8
+ export function assertProfileName(name) {
9
+ if (!PROFILE_NAME.test(name) || UNSAFE_PROFILE_KEYS.has(name)) {
10
+ throw new Error("Profile names must be 1-80 letters, numbers, dots, underscores, @ signs, or hyphens, starting with a letter or number.");
11
+ }
12
+ }
4
13
  function dir() {
5
14
  return process.env.PASSPORT_HOME || join(homedir(), ".passport");
6
15
  }
@@ -9,45 +18,37 @@ function file() {
9
18
  }
10
19
  export function readCreds() {
11
20
  try {
12
- return JSON.parse(readFileSync(file(), "utf8"));
21
+ const parsed = JSON.parse(readFileSync(file(), "utf8"));
22
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
23
+ return Object.create(null);
24
+ // A null prototype makes even a hand-edited legacy `__proto__` slot inert.
25
+ return Object.assign(Object.create(null), parsed);
13
26
  }
14
27
  catch {
15
- return {};
28
+ return Object.create(null);
16
29
  }
17
30
  }
18
31
  export function getProfile(name) {
32
+ assertProfileName(name);
19
33
  return readCreds()[name];
20
34
  }
21
35
  export function writeProfile(name, profile) {
22
- mkdirSync(dir(), { recursive: true });
23
- const creds = readCreds();
24
- creds[name] = profile;
25
- const tmp = `${file()}.tmp`;
26
- writeFileSync(tmp, JSON.stringify(creds, null, 2), { mode: 0o600 });
27
- writeFileSync(file(), JSON.stringify(creds, null, 2), { mode: 0o600 });
28
- try {
29
- chmodSync(file(), 0o600);
30
- }
31
- catch {
32
- /* best effort on platforms without chmod */
33
- }
34
- if (existsSync(tmp)) {
35
- try {
36
- // tmp was a belt-and-suspenders write; remove it
37
- writeFileSync(tmp, "");
38
- }
39
- catch {
40
- /* ignore */
41
- }
42
- }
36
+ assertProfileName(name);
37
+ withStoreWriteLock(() => {
38
+ const creds = readCreds();
39
+ creds[name] = profile;
40
+ writeCredsAtomic(creds);
41
+ });
43
42
  }
44
43
  export function removeProfile(name) {
45
- const creds = readCreds();
46
- const existing = creds[name];
47
- delete creds[name];
48
- mkdirSync(dir(), { recursive: true });
49
- writeFileSync(file(), JSON.stringify(creds, null, 2), { mode: 0o600 });
50
- return existing;
44
+ assertProfileName(name);
45
+ return withStoreWriteLock(() => {
46
+ const creds = readCreds();
47
+ const existing = creds[name];
48
+ delete creds[name];
49
+ writeCredsAtomic(creds);
50
+ return existing;
51
+ });
51
52
  }
52
53
  export function credsPath() {
53
54
  return file();
@@ -58,19 +59,72 @@ export function credsPath() {
58
59
  * live bridge processes at once — Cursor spawns one MCP process per window —
59
60
  * so exchanges must serialize ACROSS processes, not just within one. mkdir is
60
61
  * atomic on every platform; a lock older than STALE_MS belongs to a dead
61
- * process and is stolen. Waiting longer than the patience window proceeds
62
- * anyway — a missed lock at worst recreates today's race; a deadlock would
63
- * take the client's tools away entirely.
62
+ * process and is stolen. A caller that cannot acquire the lock within the
63
+ * patience window fails closed instead of risking refresh-token replay.
64
64
  */
65
65
  const LOCK_STALE_MS = 30_000;
66
66
  const LOCK_PATIENCE_MS = 15_000;
67
+ /** The JSON document is shared by every profile. This short global mutation
68
+ * lock prevents simultaneous rotations for different profiles from losing one
69
+ * another even though token exchanges use separate per-profile locks. */
70
+ function withStoreWriteLock(fn) {
71
+ const lockDir = join(dir(), ".credentials-write.lock");
72
+ mkdirSync(dir(), { recursive: true, mode: 0o700 });
73
+ const started = Date.now();
74
+ for (;;) {
75
+ try {
76
+ mkdirSync(lockDir);
77
+ break;
78
+ }
79
+ catch {
80
+ try {
81
+ if (Date.now() - statSync(lockDir).mtimeMs > LOCK_STALE_MS) {
82
+ rmSync(lockDir, { recursive: true, force: true });
83
+ continue;
84
+ }
85
+ }
86
+ catch {
87
+ continue;
88
+ }
89
+ if (Date.now() - started > LOCK_PATIENCE_MS)
90
+ throw new Error("Timed out waiting to update Passport credentials.");
91
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25 + Math.floor(Math.random() * 25));
92
+ }
93
+ }
94
+ try {
95
+ return fn();
96
+ }
97
+ finally {
98
+ rmSync(lockDir, { recursive: true, force: true });
99
+ }
100
+ }
101
+ function writeCredsAtomic(creds) {
102
+ mkdirSync(dir(), { recursive: true, mode: 0o700 });
103
+ const tmp = join(dir(), `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
104
+ try {
105
+ writeFileSync(tmp, JSON.stringify(creds, null, 2), { mode: 0o600 });
106
+ renameSync(tmp, file());
107
+ try {
108
+ chmodSync(file(), 0o600);
109
+ }
110
+ catch {
111
+ /* best effort on platforms without chmod */
112
+ }
113
+ }
114
+ finally {
115
+ rmSync(tmp, { force: true });
116
+ }
117
+ }
67
118
  export async function withProfileLock(name, fn) {
119
+ assertProfileName(name);
68
120
  const lockDir = join(dir(), `${name}.lock`);
69
121
  mkdirSync(dir(), { recursive: true });
70
122
  const started = Date.now();
123
+ let acquired = false;
71
124
  for (;;) {
72
125
  try {
73
126
  mkdirSync(lockDir);
127
+ acquired = true;
74
128
  break; // acquired
75
129
  }
76
130
  catch {
@@ -85,7 +139,7 @@ export async function withProfileLock(name, fn) {
85
139
  continue; // lock vanished between attempts — retry immediately
86
140
  }
87
141
  if (Date.now() - started > LOCK_PATIENCE_MS)
88
- break; // proceed unlocked
142
+ throw new Error(`Timed out waiting for Passport profile "${name}".`);
89
143
  await new Promise((r) => setTimeout(r, 100 + Math.floor(Math.random() * 100)));
90
144
  }
91
145
  }
@@ -93,6 +147,7 @@ export async function withProfileLock(name, fn) {
93
147
  return await fn();
94
148
  }
95
149
  finally {
96
- rmSync(lockDir, { recursive: true, force: true });
150
+ if (acquired)
151
+ rmSync(lockDir, { recursive: true, force: true });
97
152
  }
98
153
  }