fix: harden FlowSpeech transport and diagnostic privacy

This commit is contained in:
waeckerlinfederowicz66 committed 2026-10-27 12:58:17 +08:00
1 parent e0340dec1d
commit 481371d83d
11 files changed
+694 -11

No files matched your search

+1
View File
@@ -1,4 +1,5 @@
node_modules/
.release-stage/
dist/
*.js.map
.env
+4
View File
@@ -1,5 +1,9 @@
# FlowSpeech MCP Server
## Unreleased Security Follow-up
Read-only tools and returned job errors reject the configured API key in diagnostic codes. Returned job errors contain only the validated code, not remote messages or extra fields. Recovery IDs and successful result links remain available.
Use [FlowSpeech](https://flowspeech.io) speech generation from an MCP client. Version 0.2.0 uses the public API v1: create a job, wait for completion, download the WAV, and save it locally.
## Requirements
+96
View File
@@ -0,0 +1,96 @@
# Unreleased npm Publication Privacy Guard
The URL-credential follow-up also rejects embedded URL usernames/passwords
(except the conventional password-free SSH Git user), credential-bearing
query fields and parsed hosted-Git authentication. This includes dependency
fields, nested overrides and repository/homepage metadata. Public Git,
password-free SSH, registry aliases and relative dist entrypoints remain valid.
Package files are limited to root-level compiled dist modules and declared
public documents; historical post-release reports are not package contents.
This guard does not remove metadata from versions already published.
This is a local preparation/check workflow, not a publication or a repair of
already published 0.2.0 metadata. Previously retained registry responses contain
a private absolute path in `_resolved`; their original evidence is unchanged.
A maintainer must separately decide whether/how npm can correct those existing
records. Do not overwrite 0.2.0 or describe it as repaired.
## Why the Input Type Matters
The reviewed npm 10.9.8 implementation uses different manifest paths:
`lib/commands/publish.js` prepares a directory with `@npmcli/package-json`, but
loads a tarball with `pacote.manifest`. The latter adds `_resolved`/`_from`.
`libnpmpublish` retains those fields in the registry version document. A clean
tarball alone therefore does not prove clean public registry metadata.
The guard pins npm 10.9.8 and fails on another version. It requires an independently
reviewed tarball SHA-256, reads only allowlisted regular members, rejects private
paths/credentials/internal npm fields, and stages them under a new ignored
`.release-stage/` directory. It never copies node_modules, npmrc, post-release
diagnostics, credentials or arbitrary checkout files. Existing stages are not
overwritten.
Dependency collections and nested npm overrides are checked separately with
the pinned npm installation's `npm-package-arg` parser. Local directory/file
specifications, unsupported link/workspace protocols, local aliases and local
override selectors/references are rejected before staging or reporting success.
Registry versions, ranges, tags and npm aliases remain valid. Package-relative
`main`, `types`, `bin` and `exports` entrypoints are not dependency specifications
and remain allowed. Parser diagnostics never include the rejected value.
It executes the same directory manifest preparation and packing modules with
scripts disabled and offline mode enabled, compares every member byte with the
input, then exercises npm's actual metadata assembler with its sole HTTP
dependency replaced by an in-memory capture. No registry request, login,
credential read, provenance upload or publication occurs. The tests additionally
forbid network socket connections and reproduce the old tarball-metadata leak.
## Local Checks
Use Node 22.23.2 with the verified npm 10.9.8 installation first on PATH. Build
and run the existing source/packed tests before selecting a future release's
reviewed archive. A future version bump remains a separate maintainer decision.
```sh
export FLOWSPEECH_NPM_CLI="$(command -v npm)"
node --test scripts/release-privacy.test.mjs
node scripts/prepare-private-release.mjs \
--archive "$REVIEWED_ARCHIVE" \
--sha256 "$REVIEWED_SHA256" \
--npm-cli "$FLOWSPEECH_NPM_CLI" \
--destination .release-stage/reviewed
```
For tests against a different reviewed version set `FLOWSPEECH_RELEASE_ARCHIVE`.
The report `privacy-audit.json` records input/repacked hashes, member count,
metadata fingerprint, zero network requests and `publishPerformed=false`.
The staged `candidate.tgz` is for inspection/tests, **not** the publish argument.
Local verification on 2026-10-27: 22 privacy regressions passed; preparation of
the retained 0.2.0 archive reproduced its exact tarball hash and verified a
path-free simulated directory-publish payload. The result is retained under
`.release-stage/privacy-review-dependencies/`; the earlier report is retained
separately under `.release-stage/privacy-review/`. The new report includes
`dependencySpecsVerified=true`. Tests include 48 rejected synthetic manifests
through metadata, registry payload and full preparation, plus successful
registry-dependency/relative-entrypoint controls. No runtime source, existing tarball, registry
evidence or version was changed. This verifies only the pinned local toolchain,
not an actual future registry response.
## Coordinator-Only Future Publication
After selecting a new unpublished version, passing its source/consumer tests,
and reviewing the new stage and its hash, publish the **directory**, with
lifecycle scripts disabled so the verified contents cannot be rebuilt by hooks:
```sh
npm publish ./.release-stage/reviewed/package --ignore-scripts --access public
```
This command is documentation only; the guard never runs it. Do not substitute
the `.tgz` path or publish directly from a checkout containing diagnostics.
Do not edit the stage after validation. Preserve both the reviewed artifact and
report, then separately verify the resulting registry version metadata,
tarball integrity and consumer behavior. Only that subsequent read-back can
establish that a future release was actually published without private paths.
+6 -2
View File
@@ -1,5 +1,8 @@
# 0.2.0 hardening handoff (2026-10-26)
Historical runtime handoff. The subsequent local publication-privacy guard is
documented in RELEASE_PRIVACY.md; it does not repair published 0.2.0 metadata.
Base: `7a40afe` on `codex/public-api-v1`. No commits, pushes, publishes,
production requests, real credentials, or Raycast edits were made.
@@ -56,7 +59,8 @@ remain 0.2.0; dependencies were not changed.
## Coordinator release steps
Review the diff, run Node 20/22 CI, then commit/push from the coordinator.
Verify npm 0.2.0 is still unpublished before publishing this exact tarball with
the coordinator's authorized 2FA flow. Do not overwrite an existing release.
For future publication follow RELEASE_PRIVACY.md: select a new unpublished
version, verify its staged directory metadata, and publish that directory rather
than a tarball path. Do not overwrite 0.2.0 or any existing release.
No implementation blocker remains from the six findings; publication and the
new remote CI run remain coordinator actions.
+4 -1
View File
@@ -27,7 +27,10 @@
"mcp-flowspeech-server": "dist/index.js"
},
"files": [
"dist",
"dist/*.js",
"dist/*.d.ts",
"dist/*.js.map",
"dist/*.d.ts.map",
"CHANGELOG.md",
"SKILL.md"
],
+297
View File
@@ -0,0 +1,297 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { createRequire } from 'node:module';
import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
import { mkdir, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
export const VERIFIED_NPM = '10.9.8';
const packages = new Set(['mcp-flowspeech-server', 'tanstack-ai-flowspeech', 'openclaw-flowspeech']);
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
const privatePath = /(?:\/Users\/|\/home\/|\/private\/|\/tmp\/|\/var\/folders\/|(?:^|[\s"'=({])[A-Za-z]:[\\/])/;
const secret = /(?:fs_live_[A-Za-z0-9_-]{43}|sk-[A-Za-z0-9]{32}|npm_[A-Za-z0-9]{30,}|gh[pousr]_[A-Za-z0-9]{30,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)/;
function checkUrlCredentials(value) {
if (typeof value !== 'string') return;
const normalized = value.replace(/^git\+/i, '');
let url;
try { url = new URL(normalized); } catch { return; }
// The conventional SSH Git user is a transport identity, not a password.
const sshGitUser = url.protocol === 'ssh:' && url.username === 'git' && !url.password;
assert.ok((!url.username && !url.password) || sshGitUser, 'Embedded URL credentials are forbidden');
for (const key of url.searchParams.keys()) {
assert.ok(!/^(?:access[_-]?token|api[_-]?key|token|password|authorization)$/i.test(key),
'Credential-bearing URL query is forbidden');
}
}
// Reject rather than silently remove fields that would change reviewed metadata.
function checkPrivateMetadata(value, location = 'manifest') {
if (Array.isArray(value)) return value.forEach((item, index) => checkPrivateMetadata(item, location + '[' + index + ']'));
if (value && typeof value === 'object') {
for (const [key, item] of Object.entries(value)) {
assert.ok(!['_resolved', '_from', '_where', '_integrity'].includes(key),
'Disallowed npm provenance field at ' + location + '.' + key);
checkPrivateMetadata(item, location + '.' + key);
}
} else if (typeof value === 'string') {
checkUrlCredentials(value);
assert.ok(!privatePath.test(value) && !/^(?:\/|file:)/i.test(value),
'Absolute/local path at ' + location);
assert.ok(!secret.test(value), 'Potential credential at ' + location);
}
}
const dependencyFields = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
function checkPackageDependencies(manifest, packageArg) {
if (!manifest || typeof manifest !== 'object') return;
if (![...dependencyFields, 'overrides'].some(field => Object.hasOwn(manifest, field))) return;
assert.equal(typeof packageArg?.resolve, 'function', 'Pinned npm dependency parser is required');
const reject = () => assert.fail('Local or unsupported dependency specification');
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const checkParsed = parsed => {
if (parsed.type === 'alias') return checkParsed(parsed.subSpec);
if (['version', 'range', 'tag'].includes(parsed.type)) return;
if (parsed.type === 'git' && parsed.hosted) {
assert.ok(!parsed.hosted.auth, 'Embedded URL credentials are forbidden');
checkUrlCredentials(parsed.fetchSpec);
return;
}
if (['git', 'remote'].includes(parsed.type)) {
let url;
try { url = new URL(parsed.fetchSpec); } catch { reject(); }
checkUrlCredentials(url.href);
if (url.hostname && ['https:', 'http:', 'ssh:', 'git:'].includes(url.protocol)) return;
}
reject();
};
const checkSpec = (name, value) => {
if (typeof value !== 'string') reject();
let parsed;
try { parsed = packageArg.resolve(name, value); } catch { reject(); }
checkParsed(parsed);
};
const dependencies = new Map();
for (const field of dependencyFields) {
if (!Object.hasOwn(manifest, field)) continue;
if (!object(manifest[field])) reject();
for (const [name, spec] of Object.entries(manifest[field])) {
checkSpec(name, spec);
dependencies.set(name, spec);
}
}
const checkOverride = (value, name) => {
if (typeof value === 'string') {
if (value.startsWith('$')) {
const reference = value.slice(1);
if (!dependencies.has(reference)) reject();
return checkSpec(reference, dependencies.get(reference));
}
return checkSpec(name, value);
}
if (!object(value)) reject();
for (const [selector, spec] of Object.entries(value)) {
if (selector === '.') {
if (!name) reject();
checkOverride(spec, name);
continue;
}
let parsed;
try { parsed = packageArg(selector); } catch { reject(); }
if (!parsed.name || !['version', 'range', 'tag'].includes(parsed.type)) reject();
checkOverride(spec, parsed.name);
}
};
if (Object.hasOwn(manifest, 'overrides')) {
if (!object(manifest.overrides)) reject();
checkOverride(manifest.overrides);
}
}
export function checkMetadata(value, tools) {
checkPrivateMetadata(value);
checkPackageDependencies(value, tools?.packageArg);
// Registry version documents contain manifests; entrypoint maps do not.
if (value?.versions && typeof value.versions === 'object') {
for (const manifest of Object.values(value.versions)) checkPackageDependencies(manifest, tools?.packageArg);
}
}
export function npmTools(cli) {
assert.ok(cli, 'Supply --npm-cli for the verified local npm installation');
const filename = realpathSync(cli);
const root = path.resolve(path.dirname(filename), '..');
const manifest = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
assert.equal(manifest.name, 'npm', 'Expected an npm CLI installation');
assert.equal(manifest.version, VERIFIED_NPM, 'Unverified npm version; rerun the offline metadata review before upgrading');
const require = createRequire(path.join(root, 'package.json'));
return { require, tar: require('tar'), packageArg: require('npm-package-arg'),
packageJson: require('@npmcli/package-json'), pack: require('libnpmpack') };
}
export async function archiveFiles(filename, tools) {
const { tar } = tools;
assert.ok(lstatSync(filename).isFile(), 'Archive must be a regular file, not a symlink');
assert.ok(lstatSync(filename).size <= 20 * 1024 * 1024, 'Archive exceeds the local audit limit');
const files = new Map();
const modes = new Map();
const seen = new Set();
let total = 0;
let failure;
await tar.t({ file: filename, strict: true, onReadEntry(entry) {
if (failure) { entry.resume(); return; }
try {
const name = entry.path;
assert.ok(!seen.has(name), 'Duplicate archive member');
seen.add(name);
assert.ok(seen.size <= 100, 'Too many archive members');
if (entry.type === 'Directory') {
assert.ok(/^package(?:\/dist)?\/?$/.test(name), 'Unexpected archive directory');
return;
}
assert.equal(entry.type, 'File', 'Links and special files are forbidden');
assert.equal(entry.mode & 0o7000, 0, 'Special permission bits are forbidden');
modes.set(name.slice(8), entry.mode & 0o777);
assert.ok(/^package\/(?:package\.json|README\.md|CHANGELOG\.md|LICENSE|SKILL\.md|openclaw\.plugin\.json|dist\/[\w-]+(?:\.d)?\.(?:js|ts)(?:\.map)?)$/.test(name),
'Unexpected archive member');
total += entry.size;
assert.ok(Number.isSafeInteger(entry.size) && entry.size >= 0 && total <= 20 * 1024 * 1024,
'Unpacked archive exceeds the local audit limit');
const chunks = [];
entry.on('data', chunk => chunks.push(chunk));
entry.on('end', () => files.set(name.slice(8), Buffer.concat(chunks)));
} catch (error) {
failure = error;
entry.resume();
}
} });
if (failure) throw failure;
const manifest = JSON.parse(files.get('package.json')?.toString() ?? 'null');
assert.ok(manifest && packages.has(manifest.name), 'Unexpected package identity');
for (const required of ['package.json', 'README.md', 'LICENSE', 'CHANGELOG.md', 'dist/index.js', 'dist/index.d.ts']) {
assert.ok(files.has(required), 'Missing required package member: ' + required);
}
for (const [name, bytes] of files) {
assert.ok(name !== 'SKILL.md' || manifest.name === 'mcp-flowspeech-server', 'Unexpected SKILL.md');
assert.ok(name !== 'openclaw.plugin.json' || manifest.name === 'openclaw-flowspeech', 'Unexpected plugin manifest');
assert.ok(!privatePath.test(bytes.toString()) && !secret.test(bytes.toString()),
'Private path or credential pattern in ' + name);
}
checkMetadata(manifest, tools);
return { files, modes, manifest };
}
// Exercise npm's real metadata assembler with its sole HTTP dependency replaced.
// This function never sends a request, reads npm credentials, or calls npm publish.
export async function registryPayload(manifest, tarball, tools) {
checkMetadata(manifest, tools);
const require = tools.require;
const fetchId = require.resolve('npm-registry-fetch');
const publishId = require.resolve('libnpmpublish/lib/publish.js');
require(fetchId);
const savedFetch = require.cache[fetchId].exports;
const savedPublish = require.cache[publishId];
let payload;
let calls = 0;
const capture = async (name, options) => {
assert.equal(name, manifest.name);
assert.equal(options.method, 'PUT');
assert.equal(options.registry, 'https://registry.example.invalid/');
payload = options.body;
calls++;
return {};
};
capture.pickRegistry = () => 'https://registry.example.invalid/';
require.cache[fetchId].exports = capture;
delete require.cache[publishId];
try {
await require(publishId)(manifest, tarball, {
registry: 'https://registry.example.invalid/', npmVersion: VERIFIED_NPM,
access: 'public', provenance: false, defaultTag: 'latest',
});
} finally {
require.cache[fetchId].exports = savedFetch;
delete require.cache[publishId];
if (savedPublish) require.cache[publishId] = savedPublish;
}
assert.equal(calls, 1, 'Expected one intercepted metadata assembly');
const attachment = Object.values(payload._attachments);
assert.equal(attachment.length, 1);
assert.deepEqual(Buffer.from(attachment[0].data, 'base64'), Buffer.from(tarball));
const { _attachments, ...metadata } = payload;
checkMetadata(metadata, tools);
return metadata;
}
export async function prepareRelease({ archive, expectedSha256, destination, npmCli }) {
assert.match(expectedSha256 ?? '', /^[a-f0-9]{64}$/, 'Supply the independently reviewed archive SHA-256');
const bytes = readFileSync(archive);
assert.equal(sha256(bytes), expectedSha256, 'Reviewed archive hash mismatch');
const tools = npmTools(npmCli);
const { files, modes, manifest } = await archiveFiles(archive, tools);
const parent = path.resolve('.release-stage');
const target = path.resolve(destination ?? path.join(parent, 'candidate'));
assert.ok(target.startsWith(parent + path.sep) && target !== parent, 'Destination must be inside .release-stage');
assert.ok(!existsSync(parent) || !lstatSync(parent).isSymbolicLink(), 'Stage root must not be a symlink');
assert.equal(path.dirname(target), parent, 'Use a direct child of .release-stage');
await mkdir(parent, { recursive: true });
await mkdir(target); // Never overwrite a prior candidate.
try {
const pkg = path.join(target, 'package');
await mkdir(pkg);
// Only the audited regular members are written; no checkout, cache or npmrc is copied.
for (const [name, content] of files) {
await mkdir(path.dirname(path.join(pkg, name)), { recursive: true });
await writeFile(path.join(pkg, name), content, { flag: 'wx', mode: modes.get(name) });
}
const { content: directoryManifest } = await (await tools.packageJson.fix(pkg)).prepare();
checkMetadata(directoryManifest, tools);
const packed = await tools.pack(pkg, {
ignoreScripts: true, offline: true, dryRun: true, cache: path.join(target, 'cache'),
});
const repacked = path.join(target, 'candidate.tgz');
await writeFile(repacked, packed, { flag: 'wx' });
const inspected = await archiveFiles(repacked, tools);
assert.deepEqual([...inspected.files.keys()].sort(), [...files.keys()].sort(), 'Directory packing changed the member list');
for (const [name, original] of files) {
assert.deepEqual(inspected.files.get(name), original, 'Directory packing changed reviewed content: ' + name);
assert.deepEqual(readFileSync(path.join(pkg, name)), original, 'Directory manifest preparation modified: ' + name);
}
const metadata = await registryPayload(directoryManifest, packed, tools);
const report = {
package: manifest.name, version: manifest.version, npmVersion: VERIFIED_NPM,
inputSha256: expectedSha256, directoryPackSha256: sha256(packed), members: files.size,
reviewedMembersUnchanged: true, metadataSha256: sha256(JSON.stringify(metadata)),
privatePathFields: 0, dependencySpecsVerified: true,
registryPayloadVerifiedOffline: true, networkRequests: 0,
publishPerformed: false, existingRegistryMetadataChanged: false,
publishSource: 'package directory, never the input .tgz',
};
await writeFile(path.join(target, 'privacy-audit.json'), JSON.stringify(report, null, 2) + '\n', { flag: 'wx' });
return report;
} catch (error) {
await rm(target, { recursive: true, force: true });
throw error;
}
}
if (process.argv[1] && existsSync(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
try {
const args = process.argv.slice(2);
assert.equal(args.length % 2, 0, 'Expected option/value pairs');
const options = {};
const names = { '--archive': 'archive', '--sha256': 'expectedSha256', '--destination': 'destination', '--npm-cli': 'npmCli' };
for (let i = 0; i < args.length; i += 2) {
assert.ok(names[args[i]] && options[names[args[i]]] === undefined, 'Unknown or duplicate option');
options[names[args[i]]] = args[i + 1];
}
console.log(JSON.stringify(await prepareRelease(options), null, 2));
} catch (error) {
// Do not print raw filesystem/library error details or a local path.
console.error('Release privacy preparation failed; no publication was attempted. ' +
(error instanceof assert.AssertionError ? error.message.split('\n')[0] : 'Check local inputs and pinned npm installation.'));
process.exitCode = 1;
}
}
+213
View File
@@ -0,0 +1,213 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { mkdtemp, mkdir, readFile, rm, writeFile, symlink } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import net from 'node:net';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { archiveFiles, checkMetadata, npmTools, prepareRelease, registryPayload } from './prepare-private-release.mjs';
const root = fileURLToPath(new URL('..', import.meta.url));
const pkg = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));
const archive = path.resolve(process.env.FLOWSPEECH_RELEASE_ARCHIVE ?? path.join(root, pkg.name + '-' + pkg.version + '.tgz'));
const npmCli = process.env.FLOWSPEECH_NPM_CLI ?? process.env.npm_execpath;
const tools = npmTools(npmCli);
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
const bytes = await readFile(archive);
const expectedSha256 = digest(bytes);
const fixtureRoot = path.join(root, '.release-stage');
await mkdir(fixtureRoot, { recursive: true });
const connect = net.Socket.prototype.connect;
const fetch = globalThis.fetch;
net.Socket.prototype.connect = function () { throw new Error('Network forbidden in release privacy tests'); };
globalThis.fetch = async () => { throw new Error('Network forbidden in release privacy tests'); };
test.after(() => { net.Socket.prototype.connect = connect; globalThis.fetch = fetch; });
for (const field of ['_resolved', '_from', '_where', '_integrity']) {
test('rejects npm-injected ' + field + ' rather than deleting evidence', () => {
const value = { name: pkg.name, version: pkg.version, [field]: '/private/fixture/release.tgz' };
assert.throws(() => checkMetadata(value, tools), /Disallowed npm provenance field/);
assert.ok(value[field], 'Validation must not erase the original metadata');
});
}
for (const value of ['/Users/fixture/package', '/home/fixture/package', '/opt/fixture/package', 'file:../candidate.tgz', 'C:\\fixture\\package']) {
test('rejects a private/local manifest path form', () => {
assert.throws(() => checkMetadata({ dependencies: { fixture: value } }, tools), /Absolute\/local path/);
});
}
test('HTTPS URLs and relative published entrypoints are not mistaken for filesystem paths', () => {
checkMetadata({ repository: 'https://github.com/example/package.git', main: './dist/index.js' }, tools);
});
test('reproduces tarball metadata leakage and blocks its offline registry payload', async () => {
const manifest = await tools.require('pacote').manifest(archive, {
offline: true, fullmetadata: true, fullReadJson: true, cache: path.join(fixtureRoot, 'cache'),
});
assert.equal(typeof manifest._resolved, 'string');
assert.ok(path.isAbsolute(manifest._resolved));
await assert.rejects(registryPayload(manifest, bytes, tools), /Disallowed npm provenance field/);
});
test('stages exact reviewed bytes, assembles path-free directory metadata and never overwrites a candidate', async () => {
const target = path.join(fixtureRoot, 'success-' + process.pid);
try {
const result = await prepareRelease({ archive, expectedSha256, destination: target, npmCli });
assert.equal(result.inputSha256, expectedSha256);
assert.equal(result.directoryPackSha256, expectedSha256);
assert.equal(result.networkRequests, 0);
assert.equal(result.publishPerformed, false);
assert.equal(result.existingRegistryMetadataChanged, false);
const before = await archiveFiles(archive, tools);
const after = await archiveFiles(path.join(target, 'candidate.tgz'), tools);
assert.deepEqual(after.files, before.files);
assert.deepEqual(await readFile(archive), bytes);
await assert.rejects(prepareRelease({ archive, expectedSha256, destination: target, npmCli }));
assert.ok(existsSync(path.join(target, 'privacy-audit.json')), 'Prior evidence must survive a collision');
} finally { await rm(target, { recursive: true, force: true }); }
});
test('fails closed on a wrong digest or unverified npm toolchain', async () => {
await assert.rejects(prepareRelease({ archive, expectedSha256: '0'.repeat(64), npmCli }), /hash mismatch/);
const tmp = await mkdtemp(path.join(fixtureRoot, 'npm-fixture-'));
try {
await mkdir(path.join(tmp, 'bin'));
await writeFile(path.join(tmp, 'bin/npm-cli.js'), '');
await writeFile(path.join(tmp, 'package.json'), JSON.stringify({ name: 'npm', version: '99.0.0' }));
assert.throws(() => npmTools(path.join(tmp, 'bin/npm-cli.js')), /Unverified npm version/);
} finally { await rm(tmp, { recursive: true, force: true }); }
});
test('rejects diagnostics, local metadata and links in the candidate archive', async () => {
const tmp = await mkdtemp(path.join(fixtureRoot, 'archive-fixture-'));
try {
await tools.tar.x({ file: archive, cwd: tmp });
const filename = path.join(tmp, 'bad.tgz');
const packageRoot = path.join(tmp, 'package');
await mkdir(path.join(packageRoot, 'dist/post-release'));
await writeFile(path.join(packageRoot, 'dist/post-release/registry.json'), '{}');
await tools.tar.c({ gzip: true, portable: true, file: filename, cwd: tmp }, ['package']);
await assert.rejects(archiveFiles(filename, tools));
await rm(path.join(packageRoot, 'dist/post-release'), { recursive: true });
await symlink('index.js', path.join(packageRoot, 'dist/link.js'));
await tools.tar.c({ gzip: true, portable: true, file: filename, cwd: tmp }, ['package']);
await assert.rejects(archiveFiles(filename, tools));
} finally { await rm(tmp, { recursive: true, force: true }); }
});
async function withManifest(changes, run) {
const tmp = await mkdtemp(path.join(fixtureRoot, 'dependency-fixture-'));
const destination = tmp + '-stage';
try {
await tools.tar.x({ file: archive, cwd: tmp });
const filename = path.join(tmp, 'candidate.tgz');
const manifestFile = path.join(tmp, 'package/package.json');
const manifest = { ...JSON.parse(await readFile(manifestFile, 'utf8')), ...changes };
await writeFile(manifestFile, JSON.stringify(manifest, null, 2) + '\n');
await tools.tar.c({ gzip: true, portable: true, file: filename, cwd: tmp }, ['package']);
await run({ archive: filename, expectedSha256: digest(await readFile(filename)), destination, npmCli }, manifest);
} finally {
await rm(tmp, { recursive: true, force: true });
await rm(destination, { recursive: true, force: true });
}
}
async function rejectsManifest(changes) {
await withManifest(changes, async (options, manifest) => {
assert.throws(() => checkMetadata(manifest, tools));
await assert.rejects(registryPayload(manifest, bytes, tools));
await assert.rejects(prepareRelease(options));
assert.ok(!existsSync(options.destination), 'Rejected dependency must never receive a clean audit report');
});
}
const localSpecs = ['../private-project', './private-project', '~/private-project',
'link:../private-project', 'workspace:*', 'file:../private-project', 'git+file:///opt/private-project'];
for (const field of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
test('rejects parsed local specs in ' + field + ' before metadata or a full preparation report', async () => {
for (const spec of localSpecs) await rejectsManifest({ [field]: { fixture: spec } });
});
}
test('rejects local aliases without echoing parser errors or dependency paths', async () => {
for (const spec of ['npm:fixture@file:../private-project', 'npm:fixture@link:../private-project', 'npm:fixture@workspace:*']) {
assert.throws(() => checkMetadata({ dependencies: { fixture: spec } }, tools), error =>
error.message === 'Local or unsupported dependency specification' && !error.message.includes(spec));
await rejectsManifest({ dependencies: { fixture: spec } });
}
});
test('checks nested overrides, package selectors and dependency references structurally', async () => {
for (const spec of localSpecs) {
await rejectsManifest({ overrides: { fixture: spec } });
await rejectsManifest({ overrides: { 'parent@^1': { fixture: { '.': spec } } } });
}
await rejectsManifest({ overrides: { 'fixture@file:../private-project': { other: '^1' } } });
await rejectsManifest({ dependencies: { fixture: '../private-project' }, overrides: { fixture: '$fixture' } });
await rejectsManifest({ overrides: { fixture: '$missing' } });
});
test('accepts registry versions, ranges, tags, aliases and relative published entrypoints end to end', async () => {
const manifest = {
main: './dist/index.js', types: './dist/index.d.ts', bin: { fixture: './dist/index.js' },
exports: { '.': { types: './dist/index.d.ts', default: './dist/index.js' } },
dependencies: { fixture: '^1.2.3', exact: '1.2.3', tagged: 'latest', alias: 'npm:other@^2' },
devDependencies: { scoped: 'npm:@example/package@next' },
optionalDependencies: { optional: '~1.0.0' }, peerDependencies: { peer: '>=1 <3' },
overrides: { fixture: '$fixture', 'parent@^1': { '.': '1.2.3', alias: 'npm:other@^2' } },
};
checkMetadata(manifest, tools);
await withManifest(manifest, async (options, candidate) => {
const payload = await registryPayload(candidate, bytes, tools);
assert.equal(payload.versions[candidate.version].dependencies.alias, 'npm:other@^2');
const report = await prepareRelease(options);
assert.equal(report.dependencySpecsVerified, true);
assert.equal(report.networkRequests, 0);
assert.equal(report.privatePathFields, 0);
const after = await archiveFiles(path.join(options.destination, 'candidate.tgz'), tools);
assert.deepEqual(after.manifest.exports, manifest.exports);
assert.deepEqual(after.manifest.bin, manifest.bin);
});
});
test('fails closed without the pinned parser and rejects malformed dependency collections', () => {
assert.throws(() => checkMetadata({ dependencies: { fixture: '^1' } }), /Pinned npm dependency parser/);
for (const value of [null, [], 'fixture', { fixture: null }]) {
assert.throws(() => checkMetadata({ dependencies: value }, tools));
}
});
test('rejects credential-bearing URL metadata end to end without echoing credentials', async () => {
const canary = 'review-credential-canary-only';
for (const spec of [
'git+https://review-user:' + canary + '@github.com/example/package.git',
'https://review-user:' + canary + '@example.test/package.tgz',
'git+https://' + canary + '@github.com/example/package.git',
'git+ssh://git:' + canary + '@example.test/package.git',
'https://example.test/package.tgz?access_token=' + canary,
]) {
for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies', 'devDependencies']) {
await rejectsManifest({ [field]: { fixture: spec } });
}
await rejectsManifest({ overrides: { 'parent@^1': { fixture: spec } } });
await rejectsManifest({ repository: { type: 'git', url: spec } });
await rejectsManifest({ homepage: spec });
assert.throws(() => checkMetadata({ dependencies: { fixture: spec } }, tools), error =>
!error.message.includes(canary) && !error.message.includes('review-user'));
}
});
test('public Git, conventional SSH and tarball dependencies remain supported', async () => {
const dependencies = {
publicgit: 'git+https://github.com/example/package.git',
shortcut: 'github:example/package',
ssh: 'git+ssh://git@github.com/example/package.git',
archive: 'https://example.test/package.tgz',
};
await withManifest({ dependencies }, async (options, candidate) => {
const report = await prepareRelease(options);
assert.equal(report.networkRequests, 0);
assert.deepEqual((await registryPayload(candidate, bytes, tools)).versions[candidate.version].dependencies, dependencies);
});
});
+5 -3
View File
@@ -9,10 +9,12 @@ const root = fileURLToPath(new URL('..', import.meta.url));
const env = { ...process.env, npm_config_cache: path.join(root, '.npm-cache'), LC_ALL: 'C' };
const npmCli = process.env.npm_execpath;
assert.ok(npmCli, 'Run this check through npm run test:packed');
const packed = JSON.parse(execFileSync(process.execPath, [npmCli, 'pack', '--ignore-scripts', '--json'], { cwd: root, env, encoding: 'utf8' }));
const destination = path.resolve(process.env.FLOWSPEECH_PACK_DESTINATION ?? root);
await mkdir(destination, { recursive: true });
const packed = JSON.parse(execFileSync(process.execPath, [npmCli, 'pack', '--ignore-scripts', '--json', '--pack-destination', destination], { cwd: root, env, encoding: 'utf8' }));
assert.equal(packed.length, 1);
assert.equal(packed[0].version, '0.2.0');
const archive = path.join(root, packed[0].filename);
const archive = path.join(destination, packed[0].filename);
const expected = [
'LICENSE', 'dist/client.js', 'dist/index.js', 'package.json', 'CHANGELOG.md',
'README.md', 'SKILL.md', 'dist/client.d.ts', 'dist/index.d.ts',
@@ -39,7 +41,7 @@ try {
assert.ok((await readFile(path.join(target, manifest.bin['mcp-flowspeech-server']), 'utf8')).startsWith('#!/usr/bin/env node'));
// Dependencies resolve from the existing workspace install; implementation imports
// and the child stdio process both use only the extracted package's dist files.
const result = spawnSync(process.execPath, ['--test', 'test/client.test.mjs', 'test/stdio.test.mjs'], {
const result = spawnSync(process.execPath, ['--test', 'test/client.test.mjs', 'test/error-privacy.test.mjs', 'test/stdio.test.mjs'], {
cwd: root, env: { ...env, FLOWSPEECH_TEST_PACKAGE: target }, stdio: 'inherit',
});
assert.equal(result.status, 0, 'Packed client/stdio regression suite failed');
+21 -2
View File
@@ -241,11 +241,15 @@ export class FlowSpeechClient {
await this.pause(retryDelay(response.headers, fallback), context);
continue;
}
const code = typeof error.code === 'string' && /^[a-zA-Z0-9_]{1,100}$/.test(error.code) ? error.code : 'api_error';
const code = this.errorCode(error.code);
throw new Error(`FlowSpeech HTTP ${response.status}: ${code}`);
}
throw new Error('API retry budget exhausted');
}
private errorCode(value: unknown): string {
return typeof value === 'string' && value.length > 0 && value.length <= 100 && !/[^a-zA-Z0-9_]/.test(value) &&
!value.includes(this.options.apiKey) ? value : 'api_error';
}
private job(data: Record<string, unknown>, expected: { jobId?: string; requestId?: string }): Job {
const id = validateId(data.id), requestId = validateId(data.requestId);
if (expected.jobId && id !== expected.jobId) throw new InvalidResponse('Status response changed the job ID');
@@ -270,7 +274,22 @@ export class FlowSpeechClient {
const error = object(data.error);
if (typeof error.code !== 'string' || !/^[a-zA-Z0-9_]{1,100}$/.test(error.code)) throw new InvalidResponse('Invalid job error code');
}
return { ...data, id, requestId } as unknown as Job;
const metadata: Record<string, unknown> = {};
for (const name of ['createdAt', 'updatedAt', 'deadlineAt']) {
const value = data[name];
if (typeof value === 'string' && value.length === 24 && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value) && Number.isFinite(Date.parse(value))) metadata[name] = value;
}
if (data.progress && typeof data.progress === 'object') {
const progress = data.progress as Record<string, unknown>;
if (counter(progress.completed) && counter(progress.total)) metadata.progress = { completed: progress.completed, total: progress.total };
}
return {
...metadata,
id, requestId, status: data.status, usage,
...(data.result !== undefined ? { result: data.result } : {}),
...(data.resultDeleted !== undefined ? { resultDeleted: data.resultDeleted } : {}),
...(data.error !== undefined ? { error: { code: this.errorCode(object(data.error).code) } } : {}),
} as unknown as Job;
}
async quota(signal?: AbortSignal): Promise<Record<string, unknown>> {
const data = (await this.api('/api/v1/quota', this.context(signal))).data;
+28
View File
@@ -0,0 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { FlowSpeechClient, id, requestId, job, json } from './fixtures.mjs';
const key = 'review_secret_canary';
for (const method of ['quota', 'voices', 'getJob', 'findJob']) {
test(method + ' never reflects an API key in an HTTP error code', async () => {
let calls = 0;
const client = new FlowSpeechClient({ apiKey: key, fetch: async () => {
calls++;
return json({ error: { code: key, message: key, retryable: false } }, 403);
} });
await assert.rejects(client[method](method === 'findJob' ? requestId : method === 'getJob' ? id : undefined), error =>
error.message === 'FlowSpeech HTTP 403: api_error' && !String(error).includes(key));
assert.equal(calls, 1);
});
}
test('returned job errors include only a safe code and preserve recovery IDs', async () => {
const privateUrl = 'https://storage.example.test/private.wav?signature=review-only';
const client = new FlowSpeechClient({ apiKey: key, fetch: async () =>
json(job('failed', { error: { code: key, message: privateUrl }, traceId: privateUrl })) });
const value = await client.getJob(id);
assert.deepEqual(value.error, { code: 'api_error' });
assert.equal(value.id, id);
assert.equal(value.requestId, requestId);
assert.deepEqual(value.progress, job('failed').progress);
assert.equal(value.createdAt, job('failed').createdAt);
assert.ok(!JSON.stringify(value).includes(key) && !JSON.stringify(value).includes(privateUrl));
});
+19 -3
View File
@@ -11,7 +11,7 @@ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
import { id, requestId, wav, job, packageRoot } from './fixtures.mjs';
const workspace = fileURLToPath(new URL('..', import.meta.url));
async function setup(t, { queued = false, noKey = false, audio = wav, onCreate } = {}) {
async function setup(t, { queued = false, noKey = false, audio = wav, onCreate, reflectedError = false, apiKey = 'fake-test-key' } = {}) {
const scratch = path.join(workspace, '.test-tmp');
await mkdir(scratch, { recursive: true });
const directory = await mkdtemp(path.join(scratch, 'stdio-'));
@@ -23,8 +23,12 @@ async function setup(t, { queued = false, noKey = false, audio = wav, onCreate }
for await (const chunk of req) body += chunk;
requests.push({ path: req.url, method: req.method, auth: req.headers.authorization, key: req.headers['idempotency-key'], body });
if (req.url === '/audio.wav') { res.end(audio); return; }
assert.equal(req.headers.authorization, 'Bearer fake-test-key');
assert.equal(req.headers.authorization, 'Bearer ' + apiKey);
res.setHeader('Content-Type', 'application/json');
if (reflectedError) {
res.writeHead(403).end(JSON.stringify({ error: { code: apiKey, message: apiKey, retryable: false } }));
return;
}
if (req.url === '/api/v1/voices') {
res.end(JSON.stringify({ voices: [{ name: 'Kore', gender: 'female', description: 'Firm' }] })); return;
}
@@ -74,13 +78,25 @@ async function setup(t, { queued = false, noKey = false, audio = wav, onCreate }
});
await client.connect(new StdioClientTransport({
command: process.execPath, args: [path.join(packageRoot, 'dist/index.js')],
env: { FLOWSPEECH_API_KEY: noKey ? '' : 'fake-test-key', FLOWSPEECH_BASE_URL: baseUrl, FLOWSPEECH_OUTPUT_DIR: directory },
env: { FLOWSPEECH_API_KEY: noKey ? '' : apiKey, FLOWSPEECH_BASE_URL: baseUrl, FLOWSPEECH_OUTPUT_DIR: directory },
}));
return { client, directory, requests, jobs, events, baseUrl };
}
const call = (client, name, args = {}, options) => client.callTool({ name, arguments: args }, undefined, options);
const content = response => response.content[0].text;
test('read-only tool error output excludes reflected credentials', async t => {
const { client } = await setup(t, { reflectedError: true, apiKey: 'fake_test_key' });
for (const [name, args] of [
['flowspeech_quota', {}], ['flowspeech_list_voices', {}],
['flowspeech_get_job', { jobId: id }],
]) {
const response = await call(client, name, args);
assert.equal(response.isError, true);
assert.ok(!JSON.stringify(response).includes('fake_test_key'));
}
});
test('six strict tool schemas retain the existing names and require generation UUIDs', async t => {
const { client } = await setup(t);
const tools = (await client.listTools()).tools;