openpencil/packages/cli/tests/commands/export/app.test.ts
Danila Poyarkov e2a3aa3f80
fix: validate parsed JSON at untrusted boundaries with Valibot (#855)
* fix: validate parsed JSON at untrusted boundaries with Valibot

Clipboard HTML, library revisions from shared storage, MCP and automation
WebSocket messages, the MCP discovery file, sidecar output and AI/MCP tool
arguments were JSON.parse'd and cast to their expected types, so a
malformed payload reached the document or crashed paste. They now go
through v.pipe(v.string(), v.parseJson(), Schema), which reports bad JSON
and a wrong shape as the same validation failure.

The path_set tool rejects an invalid VectorNetwork and shares its parser
with create_vector. The CLI library catalog validates its files and runs
revisions through the same size, identity and content-hash checks as the
app; reading image bytes as index-keyed records also stops them coming
back empty. Hand-rolled typeof readers for plugin data, document metadata,
caches and preferences become schemas with their behaviour preserved, and
readCacheJSON takes a schema for its payload.

open-pencil/no-unvalidated-json-parse rejects type assertions on
JSON.parse results other than `as unknown` in src and packages/*/src.

* refactor: validate parsed JSON in tests and tooling

Extend open-pencil/no-unvalidated-json-parse beyond source: tests, helpers and repo tooling now parse JSON through Valibot schemas instead of asserting a type. The shared fixture reader returns a validated object; its old array annotation never matched the fixtures.

* fix: validate clipboard geometry bytes, library images and model catalogs

Clipboard geometry blobs and library image bytes must be bytes at contiguous indexes, so out-of-range or gapped values are rejected instead of silently becoming different geometry or images; serialized library nodes must carry source metadata. The models.dev and OpenRouter responses are validated like their cached copies, and activate-tab rejects a CDP frame it cannot read instead of hanging.

* refactor: extend the JSON validation lint to .json() results

no-unvalidated-json-parse now also rejects type assertions on Response, Bun.file and shell .json() results, the same unchecked parse in another form. MCP server tests read /health through a validated readHealth helper and discovery files through parseDiscoveryInfo; the remaining tooling reads its JSON through schemas.

* test: validate the RPC request body in the CLI app export test

* test: validate CLI JSON output in the tool and app command tests

* test: compare the malformed models.dev fallback with the curated list
2026-10-04 17:01:50 +00:00

124 lines
3.9 KiB
TypeScript

import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'
import { mkdtemp, rm } from 'node:fs/promises'
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { runCommand } from 'citty'
import * as v from 'valibot'
import type { AutomationDocumentSummary } from '@open-pencil/core/rpc'
import { removeDiscoveryFile, writeDiscoveryFile } from '@open-pencil/mcp/discovery'
import exportCommand from '#cli/commands/export'
const RPCRequestJSON = v.pipe(
v.string(),
v.parseJson(),
v.object({ command: v.string(), args: v.record(v.string(), v.unknown()) })
)
type RPCRequest = v.InferOutput<typeof RPCRequestJSON>
const DOCUMENT: AutomationDocumentSummary = {
id: 'tab-1',
name: 'Statements',
active: true,
current_page_id: '0:1',
current_page_name: 'Dashboard',
pages: [
{ id: '0:1', name: 'Dashboard' },
{ id: '0:2', name: 'Worklist' }
]
}
let server: Server
let requests: RPCRequest[] = []
let dir: string
let discoveryDir: string
const savedDiscoveryPath = process.env.OPENPENCIL_MCP_DISCOVERY_PATH
function reply(command: string): unknown {
if (command === 'list_documents') return { documents: [DOCUMENT] }
if (command === 'tool') return { svg: '<svg/>' }
return { base64: 'AQID' }
}
beforeAll(async () => {
// Our own discovery file, so a running app's record is neither replaced nor removed.
discoveryDir = await mkdtemp(join(tmpdir(), 'open-pencil-export-discovery-'))
process.env.OPENPENCIL_MCP_DISCOVERY_PATH = join(discoveryDir, 'mcp.json')
server = createServer((request, response) => {
const chunks: Buffer[] = []
request.on('data', (chunk: Buffer) => chunks.push(chunk))
request.on('end', () => {
const body = v.parse(RPCRequestJSON, Buffer.concat(chunks).toString('utf-8'))
requests.push(body)
response.writeHead(200, { 'Content-Type': 'application/json' })
response.end(JSON.stringify({ ok: true, result: reply(body.command) }))
})
})
await new Promise<void>((resolve) => {
server.listen(0, '127.0.0.1', resolve)
})
await writeDiscoveryFile({
pid: process.pid,
socketPath: null,
httpPort: (server.address() as AddressInfo).port,
authRequired: false,
authToken: null,
version: '0.0.0-test',
startedAt: new Date().toISOString()
})
})
afterAll(async () => {
await new Promise<void>((resolve) => {
server.close(() => resolve())
})
await removeDiscoveryFile()
if (savedDiscoveryPath === undefined) delete process.env.OPENPENCIL_MCP_DISCOVERY_PATH
else process.env.OPENPENCIL_MCP_DISCOVERY_PATH = savedDiscoveryPath
await rm(discoveryDir, { recursive: true, force: true })
})
beforeEach(async () => {
requests = []
dir = await mkdtemp(join(tmpdir(), 'open-pencil-export-app-'))
})
afterEach(async () => {
await rm(dir, { recursive: true, force: true })
})
function lastRequest(command: string): RPCRequest | undefined {
return requests.findLast((request) => request.command === command)
}
describe('export from the running app', () => {
test('--page exports the named page, not the page on screen', async () => {
await runCommand(exportCommand, {
rawArgs: ['--page', 'Worklist', '-o', join(dir, 'worklist.png')]
})
expect(lastRequest('export')?.args).toMatchObject({ page_id: '0:2', scope: 'page' })
})
test('--page-id exports that page rather than the selection', async () => {
await runCommand(exportCommand, {
rawArgs: ['--page-id', '0:2', '-o', join(dir, 'worklist.png')]
})
expect(lastRequest('export')?.args).toMatchObject({ page_id: '0:2', scope: 'page' })
})
test('--page targets the named page for vector formats', async () => {
await runCommand(exportCommand, {
rawArgs: ['--page', 'Worklist', '-f', 'svg', '-o', join(dir, 'worklist.svg')]
})
expect(lastRequest('tool')?.args).toMatchObject({ page_id: '0:2', name: 'export_svg' })
})
})