Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(connectors): a credential read from stdin never recommends argv; bounded size and stall

garrytan407663dab863
diff --git a/src/commands/connectors/auth.ts b/src/commands/connectors/auth.ts
index 4fded38f62..16f5fb44a1 100644
--- a/src/commands/connectors/auth.ts
+++ b/src/commands/connectors/auth.ts
@@ -44,13 +44,18 @@ function parseFlags(args: string[]): { provider: string; flags: AuthFlags } {
return { provider, flags };
}
+/** A pasted credential is a header or key, never megabytes; more is refused, not truncated. */
+export const CREDENTIAL_MAX_BYTES = 64 * 1024;
+/** A credential arrives in one paste or pipe write; a stream that stalls mid-credential is discarded after 10 s. */
+export const CREDENTIAL_INACTIVITY_MS = 10_000;
+
/** A person pasting a cookie at the terminal gets 5 minutes for the first byte. */
const PASTE_WAIT_MS = 300_000;
/** Bounded credential read (C5): an open-but-silent stdin times out with a message instead of hanging. */
async function readStdin(firstByteMs?: number): Promise<string | null> {
const read = await readStdinPayload("printf '%s' \"$COOKIE\" | gbrain connectors auth <provider> --cookie -",
- firstByteMs !== undefined ? { firstByteMs } : {});
+ { credential: true, maxBytes: CREDENTIAL_MAX_BYTES, inactivityMs: CREDENTIAL_INACTIVITY_MS, ...(firstByteMs !== undefined ? { firstByteMs } : {}) });
if (read.ok) return read.text.trim();
console.error(read.message);
return null;
diff --git a/src/core/stdin-read.ts b/src/core/stdin-read.ts
index 3b101858bb..6f4d0b0d92 100644
--- a/src/core/stdin-read.ts
+++ b/src/core/stdin-read.ts
@@ -10,8 +10,13 @@ import { readStdinBounded, type StdinRead, type StdinReadOptions } from './inter
export type StdinPayload = { ok: true; text: string; raw: Buffer } | { ok: false; reason: 'timeout' | 'cancelled' | 'error'; message: string };
-/** The message for a read that produced no usable payload; `example` is a working pipe for this command. */
-export function stdinFailureMessage(read: Exclude<StdinRead, { kind: 'data' } | { kind: 'empty' }>, example: string): string {
+/**
+ * The message for a read that produced no usable payload; `example` is a working pipe for this command.
+ * `credential`: the payload is a secret (cookie, API key), so the recovery names only the stdin pipe and never
+ * suggests passing it as an argument, where it would land in `ps` and shell history.
+ */
+export function stdinFailureMessage(read: Exclude<StdinRead, { kind: 'data' } | { kind: 'empty' }>, example: string, opts: { credential?: boolean } = {}): string {
+ if (opts.credential) return credentialStdinFailureMessage(read, example);
if (read.kind === 'timeout' && read.phase === 'first_byte') {
return 'stdin was open but silent: no input arrived, so nothing was read or written. '
+ `Pipe the content (${example}), redirect stdin from a file or </dev/null, or pass it as an argument. `
@@ -25,10 +30,25 @@ export function stdinFailureMessage(read: Exclude<StdinRead, { kind: 'data' } |
return `Could not read stdin (${read.error.message}); nothing was written.`;
}
+function credentialStdinFailureMessage(read: Exclude<StdinRead, { kind: 'data' } | { kind: 'empty' }>, example: string): string {
+ const never = 'Never put the credential on the command line; it would be visible in the process list and shell history.';
+ if (read.kind === 'timeout' && read.phase === 'first_byte') {
+ return 'stdin was open but silent: no credential arrived, so nothing was read or saved. '
+ + `Pipe it on stdin (${example}). ${never} Set GBRAIN_STDIN_TIMEOUT_MS=<ms> to wait longer for the first byte.`;
+ }
+ if (read.kind === 'timeout') {
+ return `stdin went silent after ${read.bytes} byte(s) without closing, so the partial credential was discarded and nothing was saved. `
+ + `Close stdin when the credential is complete (${example}). ${never}`;
+ }
+ if (read.kind === 'cancelled') return `Reading the credential from stdin was cancelled after ${read.bytes} byte(s); nothing was saved.`;
+ return `Could not read the credential from stdin (${read.error.message}); nothing was saved. Pipe it on stdin (${example}). ${never}`;
+}
+
/** Read the whole payload, or explain why there is none. `empty` (clean EOF, zero bytes) is ok with ''. */
-export async function readStdinPayload(example: string, opts: StdinReadOptions = {}): Promise<StdinPayload> {
- const read = await readStdinBounded({ ...opts, raw: true });
+export async function readStdinPayload(example: string, opts: StdinReadOptions & { credential?: boolean } = {}): Promise<StdinPayload> {
+ const { credential, ...readOpts } = opts;
+ const read = await readStdinBounded({ ...readOpts, raw: true });
if (read.kind === 'data') return { ok: true, text: read.text, raw: read.raw ?? Buffer.from(read.text, 'utf8') };
if (read.kind === 'empty') return { ok: true, text: '', raw: Buffer.alloc(0) };
- return { ok: false, reason: read.kind, message: stdinFailureMessage(read, example) };
+ return { ok: false, reason: read.kind, message: stdinFailureMessage(read, example, { credential }) };
}
diff --git a/test/connectors-credential-stdin.test.ts b/test/connectors-credential-stdin.test.ts
new file mode 100644
index 0000000000..4bd650f4d1
--- /dev/null
+++ b/test/connectors-credential-stdin.test.ts
@@ -0,0 +1,81 @@
+/**
+ * A credential read from stdin never tells the user to put the secret in argv.
+ *
+ * The generic stdin recovery says "pass it as an argument", which is right for
+ * a page body and wrong for a cookie or API key (argv shows up in ps and shell
+ * history). Credential callers get a recovery that names only the stdin pipe.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { stdinFailureMessage } from '../src/core/stdin-read.ts';
+
+const REPO = fileURLToPath(new URL('..', import.meta.url)).replace(/\/$/, '');
+const ARGV_HINT = /as an argument|on the command line instead|--cookie [^-\s]|--token [^-\s]/;
+let home: string;
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-cred-stdin-'));
+ const init = await runCli(['init', '--pglite', '--no-embedding'], 'devnull');
+ expect(init.exitCode).toBe(0);
+}, 60_000);
+afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+async function runCli(args: string[], stdin: 'silent' | 'partial' | 'devnull') {
+ const base = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith('GBRAIN_'))) as Record<string, string>;
+ const proc = Bun.spawn(['bun', 'run', `${REPO}/src/cli.ts`, ...args], {
+ cwd: home,
+ env: { ...base, GBRAIN_HOME: home, HOME: home, GBRAIN_STDIN_TIMEOUT_MS: '1500', GBRAIN_NON_INTERACTIVE: '1' },
+ stdin: stdin === 'devnull' ? Bun.file('/dev/null') : 'pipe',
+ stdout: 'pipe',
+ stderr: 'pipe',
+ });
+ if (stdin === 'partial') { (proc.stdin as { write: (s: string) => void; flush?: () => void }).write('sk-partial'); (proc.stdin as { flush?: () => void }).flush?.(); }
+ const killer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* gone */ } }, 25_000);
+ try {
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { exitCode, stdout, stderr };
+ } finally {
+ clearTimeout(killer);
+ if (stdin !== 'devnull') try { (proc.stdin as { end?: () => void }).end?.(); } catch { /* closed */ }
+ }
+}
+
+describe('credential stdin recovery', () => {
+ test('the credential message for a silent pipe names only the stdin pipe', () => {
+ const msg = stdinFailureMessage({ kind: 'timeout', phase: 'first_byte', bytes: 0 }, "printf '%s' \"$KEY\" | gbrain connectors auth fireflies --token -", { credential: true });
+ expect(msg).toContain('stdin was open but silent');
+ expect(msg).not.toMatch(ARGV_HINT);
+ expect(msg).toContain('Never put the credential on the command line');
+ });
+
+ test('the credential message for a partial read discards it and names only the pipe', () => {
+ const msg = stdinFailureMessage({ kind: 'timeout', phase: 'inactivity', bytes: 10 }, 'x', { credential: true });
+ expect(msg).toContain('discarded');
+ expect(msg).not.toMatch(ARGV_HINT);
+ });
+
+ test('the credential message for an oversize or failed read never suggests argv', () => {
+ const msg = stdinFailureMessage({ kind: 'error', error: new Error('stdin exceeds 65536 bytes'), bytes: 70000 }, 'x', { credential: true });
+ expect(msg).not.toMatch(ARGV_HINT);
+ expect(msg).toContain('nothing was saved');
+ });
+
+ test('connectors auth --cookie - on a silent pipe: exit 1, no argv advice, nothing saved', async () => {
+ const r = await runCli(['connectors', 'auth', 'chatgpt', '--cookie', '-'], 'silent');
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toContain('stdin was open but silent');
+ expect(r.stderr).not.toMatch(ARGV_HINT);
+ expect(existsSync(join(home, '.gbrain', 'connectors', 'chatgpt.json'))).toBe(false);
+ }, 30_000);
+
+ test('connectors auth --cookie - with a partial read that never closes: exit 1, discarded, nothing saved', async () => {
+ const r = await runCli(['connectors', 'auth', 'chatgpt', '--cookie', '-'], 'partial');
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).not.toMatch(ARGV_HINT);
+ expect(r.stderr).not.toContain('sk-partial');
+ expect(existsSync(join(home, '.gbrain', 'connectors', 'chatgpt.json'))).toBe(false);
+ }, 30_000);
+});