Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/cli/src/acp/prompt-content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ export async function publishAcpPromptAttachments(
}
const bytes = await readPromptAttachment(attachment.ref.absolutePath, options.assertActive);
options.assertActive();

const mimeType = resolveAttachmentMimeType(bytes, attachment.mimeType, attachment.name);

const uploadId = randomUUID();
const identity = { sessionId: options.sessionId, uploadId };
let opened = false;
Expand All @@ -129,7 +132,7 @@ export async function publishAcpPromptAttachments(
kind: 'begin',
...identity,
name: attachment.name,
mimeType: resolveAttachmentMimeType(bytes, attachment.mimeType, attachment.name),
mimeType,
totalBytes: bytes.length,
contentSha256: `sha256:${createHash('sha256').update(bytes).digest('hex')}`,
});
Expand Down
1 change: 1 addition & 0 deletions packages/runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"./background-task-health-tool": "./dist/background-task-health-tool.js",
"./durable-tool-result-projection": "./dist/durable-tool-result-projection.js",
"./tool-artifacts": "./dist/tool-artifacts.js",
"./pdf-preflight": "./dist/pdf-preflight.js",
Comment thread
jhaabhijeet864 marked this conversation as resolved.
"./model-factory": "./dist/model-factory.js",
"./model-runtime": "./dist/model-runtime.js",
"./context-budget": "./dist/context-budget.js",
Expand Down
80 changes: 80 additions & 0 deletions packages/runtime/src/__tests__/pdf-preflight.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { Buffer } from 'node:buffer';
import { validatePdfBytes } from '../pdf-preflight.js';

describe('pdf-preflight', () => {
test('rejects files without %PDF- magic bytes', () => {
const bytes = Buffer.from('just a random string without magic bytes');
const result = validatePdfBytes(bytes);
assert.deepEqual(result, { ok: false, reason: 'not_a_pdf' });
});

test('accepts files with %PDF- magic bytes', () => {
const bytes = Buffer.from('%PDF-1.4\n%EOF');
const result = validatePdfBytes(bytes);
assert.deepEqual(result, { ok: true, pages: undefined });
});

test('rejects encrypted PDFs with indirect object reference', () => {
const bytes = Buffer.from('%PDF-1.4\n/Encrypt 1 0 R\n%EOF');
const result = validatePdfBytes(bytes);
assert.deepEqual(result, { ok: false, reason: 'encrypted' });
});

test('rejects encrypted PDFs with inline dictionary', () => {
const bytes = Buffer.from('%PDF-1.4\n/Encrypt <<\n/Filter /Standard\n>>\n%EOF');
const result = validatePdfBytes(bytes);
assert.deepEqual(result, { ok: false, reason: 'encrypted' });
});

test('does not false-positive on a document that merely mentions /Encrypt in text', () => {
const bytes = Buffer.from(
'%PDF-1.4\nstream\nThis paper discusses /Encrypt ion in PDF files\nendstream\n%EOF',
);
const result = validatePdfBytes(bytes);
assert.deepEqual(result, { ok: true, pages: undefined });
});

test('extracts page count as advisory hint (never rejects)', () => {
const bytes = Buffer.from('%PDF-1.4\n<< /Type /Pages /Count 150 >>\n%EOF');
const result = validatePdfBytes(bytes);
// Page count is reported but never used for rejection — callers decide policy.
assert.deepEqual(result, { ok: true, pages: 150 });
});

test('does not reject a valid one-page PDF with /Count mentioned in content stream', () => {
// Counterexample from review: a valid 1-page PDF whose content stream has a
// comment that contains /Type /Pages /Count 101 before the real page-tree object.
// The validator must NOT reject this document.
const bytes = Buffer.from(
'%PDF-1.4\n' +
'stream\n% /Type /Pages /Count 101\nendstream\n' +
'<< /Type /Pages /Count 1 >>\n' +
'%EOF',
);
const result = validatePdfBytes(bytes);
// The regex may capture either 101 or 1 depending on match order, but
// critically: the result must be ok:true — no rejection on page count.
assert.equal(result.ok, true);
});
});
116 changes: 116 additions & 0 deletions packages/runtime/src/pdf-preflight.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { PDF_HEADER_SCAN_BYTES } from '@maka/core/attachments';
import { Buffer } from 'node:buffer';

export type PdfPreflightResult =
| { ok: true; pages?: number }
| { ok: false; reason: 'encrypted' | 'not_a_pdf' | 'malformed' };

/**
* Deterministic, bounded, best-effort PDF preflight validator.
*
* Designed to filter out incompatible documents before LLM provider dispatch
* without the CPU, memory, and security overhead of full PDF object-graph
* evaluation, rendering, or OCR.
*
* **Fast-path heuristics**:
*
* - **Header**: Verifies presence of `%PDF-` within the canonical
* {@link PDF_HEADER_SCAN_BYTES} window defined in `@maka/core/attachments`.
*
* - **Encryption**: Searches for an active `/Encrypt` dictionary definition
* (`/Encrypt <<` or `/Encrypt N N R`). This is a best-effort text-level scan
* and may falsely match uncompressed stream content containing those exact
* sequences.
*
* - **Page count**: Best-effort bounded regex scan for
* `/Type /Pages ... /Count N`. The regex only matches outside of stream
* content by requiring the `/Type /Pages` dictionary key context, but it
* does not decompress object streams so the result is advisory. On success
* the `pages` field is populated for informational use by callers; the
* validator itself does **not** reject based on page count because a
* text-level scan cannot authoritatively distinguish a root page-tree
* `/Count` from an intermediate node or a content-stream comment.
*
* **Non-goals**: Does not parse fonts, decompress streams, render raster
* content, or extract text.
*/
export function validatePdfBytes(bytes: Uint8Array): PdfPreflightResult {
// 1. Structural check — reuse the canonical scan window from @maka/core.
const scanWindow = Math.min(bytes.length, PDF_HEADER_SCAN_BYTES);
const prefix = bytes.subarray(0, scanWindow);
const prefixStr = Buffer.from(prefix).toString('ascii');
if (!prefixStr.includes('%PDF-')) {
return { ok: false, reason: 'not_a_pdf' };
}

// 2. Build a bounded ASCII view for dictionary scanning.
// For files ≤ 5 MB convert the whole buffer; for larger files inspect only
// the first and last 1 MB where PDF trailers and catalog roots reside.
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);

const scanBuffers: string[] = [];
if (buffer.length <= 5 * 1024 * 1024) {
scanBuffers.push(buffer.toString('ascii'));
} else {
// Scan head and tail independently to avoid synthetic matches across a concatenated seam.
scanBuffers.push(buffer.subarray(0, 1024 * 1024).toString('ascii'));
scanBuffers.push(buffer.subarray(buffer.length - 1024 * 1024).toString('ascii'));
}

// 3. Encryption check — match an active /Encrypt dictionary definition.
// Note: This is a best-effort text-level scan. Because it searches the entire
// extracted text buffer(s) rather than parsing the PDF object graph, it may
// falsely match uncompressed stream content containing the exact /Encrypt sequence.
const encryptRegex = /\/Encrypt\s*(?:<<|\d+\s+\d+\s+R)/;
Comment thread
jhaabhijeet864 marked this conversation as resolved.

const isEncrypted = scanBuffers.some((buf) => encryptRegex.test(buf));

if (isEncrypted) {
return { ok: false, reason: 'encrypted' };
}

// 4. Page count extraction (advisory, never used as a rejection gate).
// A text-level scan cannot reliably distinguish the root /Pages /Count from
// an intermediate page-tree node or a content-stream comment, so we report
// the value but leave enforcement to the caller's discretion.
// Note: The captured count may be any page-tree node's count, not necessarily the root.
const pagesRegex = /\/Type\s*\/Pages[\s\S]{0,100}?\/Count\s+(\d+)/;
const alternatePagesRegex = /\/Count\s+(\d+)[\s\S]{0,100}?\/Type\s*\/Pages/;
let pages: number | undefined = undefined;

for (const buf of scanBuffers) {
const match = buf.match(pagesRegex);
if (match && match[1]) {
pages = parseInt(match[1], 10);
if (isNaN(pages)) pages = undefined;
break;
}
const alternateMatch = buf.match(alternatePagesRegex);
if (alternateMatch && alternateMatch[1]) {
pages = parseInt(alternateMatch[1], 10);
if (isNaN(pages)) pages = undefined;
break;
}
}

return { ok: true, pages };
}