From 0ebd616e434d1ee364cb80b690e258e81d793ee8 Mon Sep 17 00:00:00 2001 From: Danny Mitchell <170748958+dannymitchelldev@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:39:31 -0600 Subject: [PATCH] fix: validate credential headers and preserve finish metadata --- CHANGELOG.md | 6 +++++ README.md | 8 ++++--- docs/engineering-log.md | 15 +++++++++++- docs/testing-runbook.md | 51 +++++++++++++++++++++++++++++++++++++++-- package-lock.json | 4 ++-- package.json | 2 +- src/cli.ts | 2 +- src/runner.ts | 11 +++++++-- tests/cli.test.ts | 20 +++++++++++++--- tests/offline-cli.mjs | 2 ++ tests/runner.test.ts | 49 +++++++++++++++++++++++++++++++++++++++ 11 files changed, 155 insertions(+), 15 deletions(-) create mode 100644 tests/offline-cli.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1def99b..ba5e1d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 0.1.1 — 2026-11-12 + +- Reject malformed API-key header values as input diagnostics before transport, with CLI exit 2 and no credential disclosure. Fixes [#1](https://github.com/dannymitchelldev/streamcheck/issues/1). +- Preserve the first observed finish reason when `onText` throws or synchronously cancels on a combined text/finish frame, while retaining text and terminal-outcome precedence. Fixes [#2](https://github.com/dannymitchelldev/streamcheck/issues/2). +- Add regression and normalization-control coverage, and block provider network access in CLI test subprocesses. + ## 0.1.0 — 2026-11-12 Initial release. diff --git a/README.md b/README.md index c62c965..96bbf8e 100644 --- a/README.md +++ b/README.md @@ -55,10 +55,10 @@ Human mode sends exact received text to stdout and its summary to stderr. JSON m ## Library -From another ESM project, install the [GitHub release](https://github.com/dannymitchelldev/streamcheck/releases/tag/v0.1.0): +From another ESM project, install the [GitHub release](https://github.com/dannymitchelldev/streamcheck/releases/tag/v0.1.1): ```sh -npm install --ignore-scripts https://github.com/dannymitchelldev/streamcheck/releases/download/v0.1.0/streamcheck-0.1.0.tgz +npm install --ignore-scripts https://github.com/dannymitchelldev/streamcheck/releases/download/v0.1.1/streamcheck-0.1.1.tgz ``` ```typescript @@ -86,6 +86,8 @@ runDemo(options?: DemoOptions): Promise Live options require `apiKey`, `model`, and `prompt`; both operations accept `signal`, `timeoutMs`, and synchronous `onText`. Defaults are a 30,000 ms overall deadline and, for live runs, 256 maximum output tokens. No retries or automatic continuation occur. +An API key that cannot form a valid HTTP authorization header returns an input diagnostic before any request is sent. + ## Why these decisions? | Decision | Reason | @@ -124,7 +126,7 @@ Every input/configuration diagnostic exits **2**. Timeout exits **124**, includi - **Partial output:** true exactly when text is nonempty and normal completion was not accepted. Successful `length` and `content_filter` results set it false and carry `token_limit` / `content_filter` warnings. The flag does not judge answer quality. - **Completion:** a normal finish reason is provisional while accounting frames drain. A later observable error, conflict, cancellation, or deadline can still win. Identical repeated reasons are harmless. Tool calls are unsupported. - **Cancellation:** first accepted terminal outcome wins. Deadline and caller-abort handlers record their cause before aborting transport. A pre-aborted signal sends no request. Accepted success survives later cancellation. -- **Callbacks:** each text delta is accumulated before synchronous `onText`. A thrown callback preserves its triggering delta. Do not pass async callbacks; promises and asynchronous rejections are outside this contract. +- **Callbacks:** each text delta is accumulated before synchronous `onText`. A thrown callback preserves its triggering delta. The first observed finish reason is retained even when a callback throws or cancels on the same frame. Do not pass async callbacks; promises and asynchronous rejections are outside this contract. - **Timing:** first-token time means time to the first nonempty text delta. It excludes initial module loading and is not a tokenizer measurement. Elapsed time ends when a terminal outcome is accepted, before final cleanup. ## Troubleshooting and limits diff --git a/docs/engineering-log.md b/docs/engineering-log.md index 9549ce6..e1f8232 100644 --- a/docs/engineering-log.md +++ b/docs/engineering-log.md @@ -1,6 +1,6 @@ # Implementation and review record -## Implementation +## v0.1.0 implementation AI-assisted implementation from an explicitly reviewed, bounded design. Product code is TypeScript; one package contains the library and CLI. The initial build was local; the first public release adds packaging and distribution checks without changing the library contract. @@ -60,3 +60,16 @@ Release regression tests were observed failing before these changes. The checksu Independent publication review (2026-11-12): completed by a separate AI reviewer over the 37-file public inventory, release scripts, metadata, workflow, tests, examples, and documentation. No Critical, Important, or Minor release defects were found. Core runtime correctness was outside this publication pass and remains covered by the earlier implementation review. Local publication validation passed on Windows / Node 24.18.0 / npm 11.16.0 with a newly populated npm cache: type checks, build, **95/95 tests** (55.69 seconds), and archive/fresh-consumer checks. Locked dependency versions were unchanged. Two release tests were observed failing before implementation and passing afterward. The public release notes provide the exact-commit CI and downloaded-artifact receipts; this local result alone is not cross-platform evidence. + +## v0.1.1 patch + +The final public-release review reproduced two minor runtime defects, tracked as [#1](https://github.com/dannymitchelldev/streamcheck/issues/1) and [#2](https://github.com/dannymitchelldev/streamcheck/issues/2). Eight initial regression cases were observed failing against the v0.1.0 implementation before either fix. + +- Validate the authorization-header value before SDK construction. Invalid embedded control characters and non-ByteString characters now return input/setup diagnostics without invoking transport or exposing the key. A genuine connection TypeError retains its network classification; a built-CLI regression checks JSON and exit 2. +- Record the first observed finish reason before invoking onText. Callback throw, synchronous caller abort, and abort-then-throw now retain the same frame's finish metadata and exact text. Finish reasons remain provisional; this does not accept success earlier or change which terminal outcome wins. + +CLI test subprocesses now preload a provider-fetch guard. The patch changes no locked dependency versions and adds no public API fields. + +Independent patch review caught a gap in Headers-only validation: SOH, vertical tab, and DEL are accepted by Headers but rejected by the Node transport. Four additional library/CLI cases were observed failing before adding Node's HTTP field-value validation after header normalization. A separate control preserves the SDK's existing trailing-whitespace normalization. The reviewer also caught a missing fetch guard on the SIGINT subprocess; it now uses the same preload as the other CLI tests. + +All 14 targeted regression/control checks passed after these corrections. Final local `npm run check` passed type checks, build, **108/108 tests**, and the fresh packed-consumer check on Windows / Node 24.18.0. Independent AI patch re-review confirmed both review findings resolved, with no remaining runtime findings; additional offline probes covered malformed headers, normalization, genuine connection failure, callback races, and built-CLI JSON/exit codes. Release notes identify the final exact-commit CI run and archive verification. Human implementation review, live providers, macOS, and physical console Ctrl+C remain unverified. diff --git a/docs/testing-runbook.md b/docs/testing-runbook.md index 33c64a3..fbde17a 100644 --- a/docs/testing-runbook.md +++ b/docs/testing-runbook.md @@ -88,8 +88,8 @@ Packing writes the archive; checksum generation writes SHA256SUMS beside it. The ### Verification Commands ```sh -npm run test:package -- -npm run checksum -- +npm run test:package -- +npm run checksum -- npm run checksum -- --check ``` @@ -105,6 +105,53 @@ Keep published artifacts/checksums as release evidence. Remove only task-owned t Explicit LF compiler output removes host newline ambiguity. Archive source-map paths must resolve to shipped src files. A raw .cast source is linked, not expected to render inline. MacOS and physical console Ctrl+C are not established by the four-job matrix. +## Patch regressions (v0.1.1) + +Last verified: 2026-11-12. Eight initial cases reproduced the two defects against v0.1.0. Independent review added four failing control-character library/CLI cases and a previously passing header-normalization control. All 14 targeted regression/control checks and the full 108-test check passed after correction, including type checks, build, and the fresh package consumer. + +### Purpose + +Check malformed credential classification and retention of finish metadata when a synchronous text callback terminates a run. + +### Setup / Seed Data + +Use the locked dependencies and synthetic credentials only. Library cases inject HTTP/SSE fixtures; CLI subprocesses preload a fetch guard that forbids provider network access. + +### Safe Actions + +The regression commands below send no provider requests. Valid-credential connection failures must remain network diagnostics. + +### Destructive / Mutating Actions + +The build writes ignored dist files. A full check also creates and cleans up its own isolated package consumer. Neither command publishes a release. + +### Steps + +1. Build the CLI so subprocess tests use the current runner. +2. Run the targeted regressions and the genuine-connection-failure control. +3. Run the full check; the expected suite is 108 tests. + +### Verification Commands + +```sh +npm run build +npm exec --offline -- vitest run tests/runner.test.ts tests/cli.test.ts -t 'API key containing|malformed credential headers|finish reason from the triggering frame|authorization-header normalization|returns null HTTP status' +npm run check +``` + +Expected: the targeted command passes 14 cases. Malformed header values produce input/setup diagnostics before transport, and the built CLI returns one JSON result with exit 2. Callback throw, caller abort, and abort-then-throw retain the same frame's finish reason and text while preserving the accepted outcome. + +### Cleanup + +No service, credentials, or persistent output is created. Generated build and check artifacts remain ignored. + +### Troubleshooting Notes + +- Cover embedded LF, CR, NUL, SOH, vertical tab, DEL, and a character outside the HTTP header ByteString range; do not use a real credential in a fixture or test name. +- Headers alone accepts some characters that the Node transport rejects. Validate the normalized HTTP field value too, while retaining the SDK's trailing-whitespace normalization. +- Use a combined text/finish frame. A later finish frame does not reproduce the callback metadata defect. +- Keep finish metadata separate from accepting normal completion: later observable failures while draining must still win. + ## Recording Last verified: 2026-11-11. diff --git a/package-lock.json b/package-lock.json index 1ff86cb..af0328d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "streamcheck", - "version": "0.1.0", + "version": "0.1.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "streamcheck", - "version": "0.1.0", + "version": "0.1.1", "license": "MIT", "dependencies": { "@openrouter/sdk": "1.5.91" diff --git a/package.json b/package.json index 029a096..e765e6d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "streamcheck", - "version": "0.1.0", + "version": "0.1.1", "description": "Diagnose OpenRouter streaming failures without losing partial output.", "private": true, "type": "module", diff --git a/src/cli.ts b/src/cli.ts index d82ee89..27d5e08 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -98,7 +98,7 @@ export async function main(args: string[] = process.argv.slice(2)): Promise (command === 'run' ? 1 : 2)) return await invalid('Unexpected positional arguments; see --help'); if (command === 'demo' && (values.model !== undefined || values.prompt !== undefined || values['max-tokens'] !== undefined)) return await invalid('--model, --prompt, and --max-tokens apply only to run'); diff --git a/src/runner.ts b/src/runner.ts index 327bb59..0946234 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -1,5 +1,6 @@ import type { Fetcher } from '@openrouter/sdk/lib/http.js'; import type { ChatStreamChunk } from '@openrouter/sdk/models'; +import { validateHeaderValue } from 'node:http'; import { createSdk } from './sdk.js'; import type { Diagnostic, FailureResult, LiveOptions, ResultBase, RunResult, RunSource, WarningCode } from './types.js'; @@ -18,6 +19,11 @@ export function inputFailure(message: string, source: RunSource | null = null, m function validate(options: LiveOptions): string | null { if (!options || typeof options !== 'object') return 'Run options are required'; if (typeof options.apiKey !== 'string' || !options.apiKey.trim()) return 'An OpenRouter API key is required'; + try { + const headers = new Headers({ authorization: `Bearer ${options.apiKey}` }); + validateHeaderValue('authorization', headers.get('authorization') ?? ''); + } + catch { return 'The OpenRouter API key contains invalid HTTP header characters'; } if (typeof options.model !== 'string' || !options.model.trim()) return 'A nonempty model is required'; if (typeof options.prompt !== 'string' || !options.prompt.trim()) return 'A nonempty prompt is required'; if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > MAX_TIMEOUT)) return 'Timeout must be an integer from 1 to 2147483647 milliseconds'; @@ -112,6 +118,9 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher, break; } const selected = value.choices[0]; + // Keep observed metadata even if the text callback ends this run. + const observedReason = selected?.finishReason; + if (finishReason === null && observedReason) finishReason = observedReason; const delta = selected?.delta.content; if (typeof delta === 'string' && delta.length > 0) { if (firstTokenMs === null) firstTokenMs = performance.now() - startedAt; @@ -120,8 +129,6 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher, catch { fail('consumer', 'The synchronous onText callback failed'); } } if (terminal) break; - const observedReason = selected?.finishReason; - if (finishReason === null && observedReason) finishReason = observedReason; if (value.error) { fail('provider', 'Provider error during streaming', value.error.code); break; diff --git a/tests/cli.test.ts b/tests/cli.test.ts index dc17923..9f76d3b 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -1,13 +1,15 @@ import { spawn, fork } from 'node:child_process'; +import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { expect, it } from 'vitest'; import { exitCodeFor } from '../src/cli.js'; import { inputFailure } from '../src/runner.js'; const bin = fileURLToPath(new URL('../dist/bin.js', import.meta.url)); +const offlinePreload = new URL('./offline-cli.mjs', import.meta.url).href; function invoke(args: string[], envOverrides: NodeJS.ProcessEnv = {}) { return new Promise<{ code: number | null; out: string; err: string }>((resolve, reject) => { - const child = spawn(process.execPath, [bin, ...args], { + const child = spawn(process.execPath, ['--import', offlinePreload, bin, ...args], { env: { ...process.env, OPENROUTER_API_KEY: 'synthetic-key-never-log', OPENROUTER_DEBUG: 'true', ...envOverrides }, stdio: ['ignore', 'pipe', 'pipe'], }); @@ -85,6 +87,17 @@ it('reports missing credentials as a JSON input diagnostic with exit 2', async ( expect(JSON.parse(actual.out)).toMatchObject({ source: 'live', httpStatus: null, error: { kind: 'input', phase: 'setup' } }); }); +it.each([ + ['line feed', 'synthetic-invalid\nkey'], + ['DEL', 'synthetic-invalid\u007fkey'], +] as const)('reports malformed credential headers (%s) as a JSON input diagnostic with exit 2', async (_label, apiKey) => { + const actual = await invoke(['run', '--model', 'offline/model', '--prompt', 'hello', '--json'], { OPENROUTER_API_KEY: apiKey }); + expect(actual.code).toBe(2); + expect(actual.err).toBe(''); + expect(JSON.parse(actual.out)).toMatchObject({ source: 'live', outcome: 'failed', httpStatus: null, error: { kind: 'input', phase: 'setup' } }); + expect(actual.out).not.toContain('synthetic-invalid'); +}); + it.each(['1', '150'])('uses timeout exit 124 with one JSON result at %s ms', async timeout => { const actual = await invoke(['demo', 'interrupted', '--timeout', timeout, '--json']); expect(actual.code).toBe(124); @@ -103,12 +116,13 @@ it.each([[], ['--help'], ['run', '--help']])('prints help without requiring cred }); it('prints the package version', async () => { - expect(await invoke(['--version'])).toEqual({ code: 0, out: '0.1.0\n', err: '' }); + const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')); + expect(await invoke(['--version'])).toEqual({ code: 0, out: `${version}\n`, err: '' }); }); it.each([true, false])('maps the SIGINT handler to cancellation and exit 130 (json=%s)', async json => { const actual = await new Promise<{ code: number | null; out: string; err: string }>((resolve, reject) => { - const child = fork(fileURLToPath(new URL('./interrupt-child.mjs', import.meta.url)), ['demo', 'interrupted', ...(json ? ['--json'] : [])], { silent: true }); + const child = fork(fileURLToPath(new URL('./interrupt-child.mjs', import.meta.url)), ['demo', 'interrupted', ...(json ? ['--json'] : [])], { silent: true, execArgv: ['--import', offlinePreload] }); let out = ''; let err = ''; let interrupted = false; const interrupt = () => { if (!interrupted) { interrupted = true; child.send('interrupt'); } }; child.on('message', message => { if (json && message === 'running') interrupt(); }); diff --git a/tests/offline-cli.mjs b/tests/offline-cli.mjs new file mode 100644 index 0000000..4d5b7d8 --- /dev/null +++ b/tests/offline-cli.mjs @@ -0,0 +1,2 @@ +// CLI regressions must fail closed if validation accidentally reaches transport. +globalThis.fetch = () => { throw new Error('Provider network forbidden in CLI tests'); }; diff --git a/tests/runner.test.ts b/tests/runner.test.ts index 835ed91..063e979 100644 --- a/tests/runner.test.ts +++ b/tests/runner.test.ts @@ -119,6 +119,25 @@ describe('result and stream boundaries', () => { expect(JSON.stringify(result)).not.toContain('PRIVATE-CONSUMER-DETAIL'); }); + it.each(['throw', 'abort', 'abort-and-throw'] as const)('retains the finish reason from the triggering frame when onText terminates with %s', async action => { + const abort = new AbortController(); + const result = await runWithTransport({ + ...valid, + signal: abort.signal, + onText() { + if (action !== 'throw') abort.abort(); + if (action !== 'abort') throw new Error('PRIVATE-CALLBACK-DETAIL'); + }, + }, fixedFetcher(sse(chunk('Last text', 'stop'), '[DONE]'))); + expect(result).toMatchObject({ + outcome: action === 'throw' ? 'interrupted' : 'cancelled', + text: 'Last text', partialOutput: true, httpStatus: 200, finishReason: 'stop', + }); + if (action === 'throw') expect(result).toMatchObject({ error: { kind: 'consumer', phase: 'stream' } }); + else expect(result).toMatchObject({ reason: 'caller' }); + expect(JSON.stringify(result)).not.toContain('PRIVATE-CALLBACK-DETAIL'); + }); + it('reports a network reset after preserving text', async () => { const fixture = controlledResponse(); let first!: () => void; @@ -146,6 +165,36 @@ describe('result and stream boundaries', () => { }); describe('validation and cancellation lifecycle', () => { + it.each([ + ['line feed', 'synthetic-invalid\nkey'], + ['carriage return', 'synthetic-invalid\rkey'], + ['NUL', 'synthetic-invalid\0key'], + ['non-ByteString character', 'synthetic-invalid\u0100key'], + ['SOH control', 'synthetic-invalid\u0001key'], + ['vertical tab', 'synthetic-invalid\u000bkey'], + ['DEL', 'synthetic-invalid\u007fkey'], + ] as const)('rejects an API key containing %s as input before transport', async (_label, apiKey) => { + const fetcher = vi.fn(fixedFetcher(sse(chunk('Unexpected request', 'stop'), '[DONE]'))); + const result = await runWithTransport({ ...valid, apiKey }, fetcher); + expect(result).toMatchObject({ + outcome: 'failed', text: '', partialOutput: false, firstTokenMs: null, + httpStatus: null, error: { kind: 'input', phase: 'setup' }, + }); + expect(fetcher).not.toHaveBeenCalled(); + expect(JSON.stringify(result)).not.toContain('synthetic-invalid'); + }); + + it('preserves SDK authorization-header normalization for an otherwise valid credential', async () => { + const fixture = fixedFetcher(sse(chunk('Done', 'stop'), '[DONE]')); + const fetcher = vi.fn(async (input: RequestInfo | URL) => { + expect((input as Request).headers.get('authorization')).toBe('Bearer synthetic-normalized'); + return fixture(input); + }); + const result = await runWithTransport({ ...valid, apiKey: 'synthetic-normalized \r\n\t' }, fetcher); + expect(result).toMatchObject({ outcome: 'success', text: 'Done', httpStatus: 200 }); + expect(fetcher).toHaveBeenCalledOnce(); + }); + it.each([ { apiKey: '' }, { model: ' ' }, { prompt: '' }, { timeoutMs: 0 }, { timeoutMs: -1 }, { timeoutMs: 2_147_483_648 }, { timeoutMs: NaN }, { maxTokens: 0 }, { maxTokens: 1.5 },