passwd-sso-cli 0.4.72 → 0.4.74

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.
@@ -31,3 +31,11 @@ export interface DecryptAgentOptions {
31
31
  eval?: boolean;
32
32
  }
33
33
  export declare function decryptAgentCommand(opts: DecryptAgentOptions): Promise<void>;
34
+ /**
35
+ * Foreground-mode copy-paste hint lines for setting PSSO_AGENT_SOCK by hand.
36
+ * Pure — extracted because the caller (`server.listen`'s callback, followed
37
+ * by a keep-alive promise that never resolves) is otherwise unreachable from
38
+ * a test that awaits the command (mirrors C1's split of browserLaunchCommand
39
+ * from openBrowser).
40
+ */
41
+ export declare function foregroundHintLines(socketPath: string): [string];
@@ -15,6 +15,7 @@ import { decryptData, hexEncode } from "../lib/crypto.js";
15
15
  import { buildPersonalEntryAAD, VAULT_TYPE } from "../lib/crypto-aad.js";
16
16
  import { getEncryptionKey, getUserId, getSecretKeyBytes, setEncryptionKey } from "../lib/vault-state.js";
17
17
  import { readPassphrase, unlockWithPassphrase } from "./unlock.js";
18
+ import { shellQuote } from "../lib/shell-quote.js";
18
19
  import * as output from "../lib/output.js";
19
20
  import { AGENT_CHILD_TIMEOUT_MS } from "../lib/time.js";
20
21
  // ─── Input Validation Schema ───────────────────────────────────
@@ -244,9 +245,14 @@ async function forkDaemon(socketPath) {
244
245
  child.send({ secretHex, userId });
245
246
  // Wait briefly for child to acknowledge, then output eval commands
246
247
  child.on("message", () => {
247
- console.log(`PSSO_AGENT_SOCK='${socketPath}'; export PSSO_AGENT_SOCK;`);
248
- console.log(`PSSO_AGENT_PID='${child.pid}'; export PSSO_AGENT_PID;`);
249
- console.log(`trap 'kill ${child.pid} 2>/dev/null; rm -f ${socketPath}' EXIT;`);
248
+ console.log(`PSSO_AGENT_SOCK=${shellQuote(socketPath)}; export PSSO_AGENT_SOCK;`);
249
+ console.log(`PSSO_AGENT_PID=${shellQuote(String(child.pid))}; export PSSO_AGENT_PID;`);
250
+ // Quoted twice, deliberately: once for the path inside the composed
251
+ // inner command, and once for the whole trap body — the body is parsed
252
+ // by two shells (the one running `eval`, and the one that runs it when
253
+ // the trap fires), each of which must read the path as one word.
254
+ const inner = `kill ${shellQuote(String(child.pid))} 2>/dev/null; rm -f ${shellQuote(socketPath)}`;
255
+ console.log(`trap ${shellQuote(inner)} EXIT;`);
250
256
  child.unref();
251
257
  child.disconnect();
252
258
  process.exit(0);
@@ -295,6 +301,16 @@ function runDaemonChild() {
295
301
  });
296
302
  });
297
303
  }
304
+ /**
305
+ * Foreground-mode copy-paste hint lines for setting PSSO_AGENT_SOCK by hand.
306
+ * Pure — extracted because the caller (`server.listen`'s callback, followed
307
+ * by a keep-alive promise that never resolves) is otherwise unreachable from
308
+ * a test that awaits the command (mirrors C1's split of browserLaunchCommand
309
+ * from openBrowser).
310
+ */
311
+ export function foregroundHintLines(socketPath) {
312
+ return [` export PSSO_AGENT_SOCK=${shellQuote(socketPath)}`];
313
+ }
298
314
  /**
299
315
  * Start the agent in foreground mode (used by both direct and daemon child).
300
316
  */
@@ -307,7 +323,7 @@ async function startForegroundAgent(socketPath) {
307
323
  output.success("Decrypt agent started.");
308
324
  output.info(`Socket: ${socketPath}`);
309
325
  output.info("In another terminal, run:");
310
- console.log(` export PSSO_AGENT_SOCK='${socketPath}'`);
326
+ console.log(foregroundHintLines(socketPath)[0]);
311
327
  output.info("Press Ctrl+C to stop the agent.");
312
328
  });
313
329
  server.on("error", (err) => {
@@ -15,4 +15,11 @@ export interface AgentOptions {
15
15
  eval?: boolean;
16
16
  decrypt?: boolean;
17
17
  }
18
+ /**
19
+ * Foreground-mode copy-paste hint lines for setting SSH_AUTH_SOCK by hand.
20
+ * Pure — extracted so the shell-quoted socket path is assertable without
21
+ * the surrounding process staying alive forever (mirrors C1's split of
22
+ * browserLaunchCommand from openBrowser).
23
+ */
24
+ export declare function foregroundHintLines(socketPath: string): [string, string];
18
25
  export declare function agentCommand(opts: AgentOptions): Promise<void>;
@@ -22,6 +22,7 @@ import { startAgent, stopAgent, setAgentDeps } from "../lib/ssh-agent-socket.js"
22
22
  import { authorizeSign } from "../lib/ssh-sign-authorizer.js";
23
23
  import { confirmSign } from "../lib/ssh-confirm.js";
24
24
  import { decryptAgentCommand } from "./agent-decrypt.js";
25
+ import { shellQuote } from "../lib/shell-quote.js";
25
26
  import * as output from "../lib/output.js";
26
27
  import { AGENT_CHILD_TIMEOUT_MS, VAULT_LOCK_POLL_INTERVAL_MS } from "../lib/time.js";
27
28
  import { CLI_API_PATH } from "../lib/api-paths.js";
@@ -89,6 +90,18 @@ async function loadSshKeys() {
89
90
  }
90
91
  return loadedCount;
91
92
  }
93
+ /**
94
+ * Foreground-mode copy-paste hint lines for setting SSH_AUTH_SOCK by hand.
95
+ * Pure — extracted so the shell-quoted socket path is assertable without
96
+ * the surrounding process staying alive forever (mirrors C1's split of
97
+ * browserLaunchCommand from openBrowser).
98
+ */
99
+ export function foregroundHintLines(socketPath) {
100
+ return [
101
+ ` export SSH_AUTH_SOCK=${shellQuote(socketPath)}`,
102
+ ` eval $(passwd-sso agent --eval)`,
103
+ ];
104
+ }
92
105
  export async function agentCommand(opts) {
93
106
  if (opts.decrypt) {
94
107
  return decryptAgentCommand({ eval: opts.eval });
@@ -121,12 +134,13 @@ export async function agentCommand(opts) {
121
134
  const loadedCount = await loadSshKeys();
122
135
  setAgentDeps({ authorizeSign, confirmSign });
123
136
  const socketPath = startAgent();
137
+ const [exportHint, evalHint] = foregroundHintLines(socketPath);
124
138
  output.success(`SSH agent started with ${loadedCount} key(s).`);
125
139
  output.info(`Socket: ${socketPath}`);
126
140
  output.info("Set SSH_AUTH_SOCK:");
127
- console.log(` export SSH_AUTH_SOCK=${socketPath}`);
141
+ console.log(exportHint);
128
142
  output.info("Or use:");
129
- console.log(` eval $(passwd-sso agent --eval)`);
143
+ console.log(evalHint);
130
144
  output.info("Press Ctrl+C to stop the agent.");
131
145
  // Handle vault lock → clear keys
132
146
  const checkLock = setInterval(() => {
@@ -172,9 +186,14 @@ async function forkDaemon() {
172
186
  child.send({ secretHex, userId });
173
187
  // Child reports the socket path once it is serving keys.
174
188
  child.on("message", (msg) => {
175
- console.log(`SSH_AUTH_SOCK='${msg.socketPath}'; export SSH_AUTH_SOCK;`);
176
- console.log(`SSH_AGENT_PID='${child.pid}'; export SSH_AGENT_PID;`);
177
- console.log(`trap 'kill ${child.pid} 2>/dev/null; rm -f ${msg.socketPath}' EXIT;`);
189
+ console.log(`SSH_AUTH_SOCK=${shellQuote(msg.socketPath)}; export SSH_AUTH_SOCK;`);
190
+ console.log(`SSH_AGENT_PID=${shellQuote(String(child.pid))}; export SSH_AGENT_PID;`);
191
+ // Quoted twice, deliberately: once for the path inside the composed
192
+ // inner command, and once for the whole trap body — the body is parsed
193
+ // by two shells (the one running `eval`, and the one that runs it when
194
+ // the trap fires), each of which must read the path as one word.
195
+ const inner = `kill ${shellQuote(String(child.pid))} 2>/dev/null; rm -f ${shellQuote(msg.socketPath)}`;
196
+ console.log(`trap ${shellQuote(inner)} EXIT;`);
178
197
  child.unref();
179
198
  child.disconnect();
180
199
  process.exit(0);
@@ -14,6 +14,7 @@ import { getToken } from "../lib/api-client.js";
14
14
  import { decryptData } from "../lib/crypto.js";
15
15
  import { buildPersonalEntryAAD, VAULT_TYPE } from "../lib/crypto-aad.js";
16
16
  import { BLOCKED_KEYS } from "../lib/blocked-keys.js";
17
+ import { shellQuote } from "../lib/shell-quote.js";
17
18
  import * as output from "../lib/output.js";
18
19
  export async function envCommand(opts) {
19
20
  let config;
@@ -90,20 +91,15 @@ export async function envCommand(opts) {
90
91
  break;
91
92
  case "dotenv":
92
93
  for (const [k, v] of Object.entries(result)) {
93
- console.log(`${k}=${shellEscape(v)}`);
94
+ console.log(`${k}=${shellQuote(v)}`);
94
95
  }
95
96
  break;
96
97
  case "shell":
97
98
  default:
98
99
  for (const [k, v] of Object.entries(result)) {
99
- console.log(`export ${k}=${shellEscape(v)}`);
100
+ console.log(`export ${k}=${shellQuote(v)}`);
100
101
  }
101
102
  break;
102
103
  }
103
104
  }
104
- function shellEscape(s) {
105
- if (/^[a-zA-Z0-9._\-/:@]+$/.test(s))
106
- return s;
107
- return `'${s.replace(/'/g, "'\\''")}'`;
108
- }
109
105
  //# sourceMappingURL=env.js.map
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `passwd-sso run` — Inject vault secrets into a command's environment.
3
3
  *
4
- * Uses child_process.execFile (NOT shell) for security.
4
+ * Uses child_process.spawn (NOT shell) for security.
5
5
  * Blocks certain dangerous env var names from being overwritten.
6
6
  */
7
7
  interface RunOptions {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `passwd-sso run` — Inject vault secrets into a command's environment.
3
3
  *
4
- * Uses child_process.execFile (NOT shell) for security.
4
+ * Uses child_process.spawn (NOT shell) for security.
5
5
  * Blocks certain dangerous env var names from being overwritten.
6
6
  */
7
7
  import { spawn } from "node:child_process";
@@ -49,12 +49,23 @@ export declare function exchangeCode(serverUrl: string, params: {
49
49
  export declare function refreshTokenGrant(serverUrl: string, refreshToken: string, clientId: string): Promise<TokenResponse | null>;
50
50
  /** Revoke a token via the server's revocation endpoint. Best-effort — does not throw. */
51
51
  export declare function revokeTokenRequest(serverUrl: string, token: string, clientId: string, tokenTypeHint?: "access_token" | "refresh_token"): Promise<void>;
52
+ export type BrowserLaunch = {
53
+ cmd: string;
54
+ args: string[];
55
+ };
56
+ /**
57
+ * Pure: decide the argv vector for opening `url` on `platform`. No command
58
+ * interpreter parses the result — `rundll32 url.dll,FileProtocolHandler` is
59
+ * the shell-free way to hand a URL to the Windows default handler, unlike
60
+ * `cmd /c start` which re-parses `&` as a command separator (F1).
61
+ */
62
+ export declare function browserLaunchCommand(url: string, platform: NodeJS.Platform): BrowserLaunch | null;
52
63
  /**
53
64
  * Attempt to open the URL in the system browser.
54
65
  * Returns false when running in a headless environment (no display server).
55
66
  */
56
67
  export declare function openBrowser(url: string): boolean;
57
- /** Reject non-HTTPS URLs except for loopback development. */
68
+ /** Reject non-HTTPS URLs except for loopback development, and narrow what a server URL may otherwise be. */
58
69
  export declare function validateServerUrl(url: string): void;
59
70
  export declare function runOAuthFlow(serverUrl: string): Promise<OAuthResult>;
60
71
  export {};
package/dist/lib/oauth.js CHANGED
@@ -235,7 +235,30 @@ export async function revokeTokenRequest(serverUrl, token, clientId, tokenTypeHi
235
235
  // Best-effort — network errors are silently ignored
236
236
  }
237
237
  }
238
- // ─── Browser launcher ─────────────────────────────────────────────────────────
238
+ /**
239
+ * Pure: decide the argv vector for opening `url` on `platform`. No command
240
+ * interpreter parses the result — `rundll32 url.dll,FileProtocolHandler` is
241
+ * the shell-free way to hand a URL to the Windows default handler, unlike
242
+ * `cmd /c start` which re-parses `&` as a command separator (F1).
243
+ */
244
+ export function browserLaunchCommand(url, platform) {
245
+ let parsed;
246
+ try {
247
+ parsed = new URL(url);
248
+ }
249
+ catch {
250
+ return null;
251
+ }
252
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
253
+ return null;
254
+ if (platform === "darwin") {
255
+ return { cmd: "open", args: [url] };
256
+ }
257
+ if (platform === "win32") {
258
+ return { cmd: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url] };
259
+ }
260
+ return { cmd: "xdg-open", args: [url] };
261
+ }
239
262
  /**
240
263
  * Attempt to open the URL in the system browser.
241
264
  * Returns false when running in a headless environment (no display server).
@@ -249,22 +272,11 @@ export function openBrowser(url) {
249
272
  if (!hasDisplay)
250
273
  return false;
251
274
  }
252
- let cmd;
253
- let args;
254
- if (platform === "darwin") {
255
- cmd = "open";
256
- args = [url];
257
- }
258
- else if (platform === "win32") {
259
- cmd = "cmd";
260
- args = ["/c", "start", "", url];
261
- }
262
- else {
263
- cmd = "xdg-open";
264
- args = [url];
265
- }
275
+ const launch = browserLaunchCommand(url, platform);
276
+ if (!launch)
277
+ return false;
266
278
  try {
267
- spawn(cmd, args, { detached: true, stdio: "ignore" }).unref();
279
+ spawn(launch.cmd, launch.args, { detached: true, stdio: "ignore" }).unref();
268
280
  return true;
269
281
  }
270
282
  catch {
@@ -272,7 +284,13 @@ export function openBrowser(url) {
272
284
  }
273
285
  }
274
286
  // ─── URL validation ───────────────────────────────────────────────────────────
275
- /** Reject non-HTTPS URLs except for loopback development. */
287
+ // Narrower than the WHATWG URL parser: `new URL()` tolerates raw `&`/`,` in
288
+ // the host and path, and the composed authorization URL is built by string
289
+ // concatenation (`${serverUrl}${MCP_AUTHORIZE_ENDPOINT}`), so anything the
290
+ // parser lets through here is carried into it verbatim (I2.4).
291
+ const SERVER_HOSTNAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
292
+ const SERVER_PATHNAME_RE = /^(\/[A-Za-z0-9._~-]+)*\/?$/;
293
+ /** Reject non-HTTPS URLs except for loopback development, and narrow what a server URL may otherwise be. */
276
294
  export function validateServerUrl(url) {
277
295
  let parsed;
278
296
  try {
@@ -292,6 +310,22 @@ export function validateServerUrl(url) {
292
310
  throw new Error("Server URL must use HTTPS (http is only allowed for localhost/127.0.0.1/::1)");
293
311
  }
294
312
  }
313
+ if (parsed.username || parsed.password) {
314
+ throw new Error("Server URL must not contain a username or password");
315
+ }
316
+ if (parsed.search || parsed.hash) {
317
+ throw new Error("Server URL must not contain a query string or fragment");
318
+ }
319
+ // A hostname beginning with "[" is a syntactically valid IPv6 literal —
320
+ // that is the only form the URL host parser produces for it, and `new
321
+ // URL()` would already have thrown otherwise — so no further pattern
322
+ // matching is needed for that branch.
323
+ if (!parsed.hostname.startsWith("[") && !SERVER_HOSTNAME_RE.test(parsed.hostname)) {
324
+ throw new Error(`Server URL has an invalid hostname: ${parsed.hostname}`);
325
+ }
326
+ if (!SERVER_PATHNAME_RE.test(parsed.pathname)) {
327
+ throw new Error(`Server URL has an invalid path: ${parsed.pathname}`);
328
+ }
295
329
  }
296
330
  // ─── Main OAuth flow ──────────────────────────────────────────────────────────
297
331
  export async function runOAuthFlow(serverUrl) {
@@ -0,0 +1,9 @@
1
+ /**
2
+ * POSIX shell quoting for values interpolated into `console.log`-emitted
3
+ * shell syntax (`export`, `eval`-able assignments, `trap` bodies).
4
+ *
5
+ * Promoted from `commands/env.ts`'s private `shellEscape` — this is the
6
+ * single quoting helper for the CLI; do not write a second one.
7
+ */
8
+ /** Quote `s` so that a POSIX shell reads it back as exactly one word equal to `s`. */
9
+ export declare function shellQuote(s: string): string;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * POSIX shell quoting for values interpolated into `console.log`-emitted
3
+ * shell syntax (`export`, `eval`-able assignments, `trap` bodies).
4
+ *
5
+ * Promoted from `commands/env.ts`'s private `shellEscape` — this is the
6
+ * single quoting helper for the CLI; do not write a second one.
7
+ */
8
+ /** Quote `s` so that a POSIX shell reads it back as exactly one word equal to `s`. */
9
+ export function shellQuote(s) {
10
+ if (/^[a-zA-Z0-9._\-/:@]+$/.test(s))
11
+ return s;
12
+ return `'${s.replace(/'/g, "'\\''")}'`;
13
+ }
14
+ //# sourceMappingURL=shell-quote.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passwd-sso-cli",
3
- "version": "0.4.72",
3
+ "version": "0.4.74",
4
4
  "description": "CLI for passwd-sso password manager",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -54,7 +54,8 @@
54
54
  "vitest": "^4.1.8"
55
55
  },
56
56
  "overrides": {
57
- "postcss": ">=8.5.10",
57
+ "postcss": ">=8.5.23",
58
+ "nanoid": "^3.3.18",
58
59
  "esbuild": ">=0.28.1"
59
60
  }
60
61
  }