kritya 0.8.21-beta → 0.8.23-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,15 @@ import { validateBlocks } from "./types.js";
9
9
  // fileURLToPath yields backslash-separated paths — normalize to forward
10
10
  // slashes, which fs.readFile accepts on every platform.
11
11
  const STANDARD_FONT_DATA_URL = fileURLToPath(new URL("../../../node_modules/pdfjs-dist/standard_fonts/", import.meta.url)).replace(/\\/g, "/");
12
+ /**
13
+ * A hostile or corrupt PDF can declare an enormous page count, or pack a
14
+ * huge amount of text into a single page; without a cap, extracting text
15
+ * page-by-page has no upper bound on how long it runs or how much memory the
16
+ * accumulated text consumes. Both caps stop the extraction early rather than
17
+ * failing outright — the caller gets whatever was read so far, plus a note.
18
+ */
19
+ const MAX_PDF_PAGES = 5_000;
20
+ const MAX_PDF_TEXT_CHARS = 5_000_000;
12
21
  export async function readPdf(buf) {
13
22
  const loadingTask = getDocument({
14
23
  data: new Uint8Array(buf),
@@ -16,16 +25,27 @@ export async function readPdf(buf) {
16
25
  });
17
26
  const doc = await loadingTask.promise;
18
27
  const pageTexts = [];
19
- for (let i = 1; i <= doc.numPages; i++) {
28
+ let totalChars = 0;
29
+ let truncated = false;
30
+ const pageCount = Math.min(doc.numPages, MAX_PDF_PAGES);
31
+ for (let i = 1; i <= pageCount; i++) {
20
32
  const page = await doc.getPage(i);
21
33
  const content = await page.getTextContent();
22
34
  const text = content.items
23
35
  .map((item) => ("str" in item ? item.str : ""))
24
36
  .join(" ");
25
37
  pageTexts.push(text);
38
+ totalChars += text.length;
39
+ if (totalChars > MAX_PDF_TEXT_CHARS) {
40
+ truncated = true;
41
+ break;
42
+ }
26
43
  }
27
44
  await loadingTask.destroy();
28
- return pageTexts.join("\n\n");
45
+ if (pageCount < doc.numPages)
46
+ truncated = true;
47
+ return (pageTexts.join("\n\n") +
48
+ (truncated ? `\n\n... [truncated: read ${pageTexts.length} of ${doc.numPages} page(s)]` : ""));
29
49
  }
30
50
  const PAGE_WIDTH = 612; // US Letter, points
31
51
  const PAGE_HEIGHT = 792;
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import JSZip from "jszip";
2
+ import { loadSafeZip } from "./zipSafety.js";
3
3
  // pptxgenjs is CommonJS-only and its bundled types don't resolve cleanly
4
4
  // under NodeNext + esModuleInterop (the default import type-checks as the
5
5
  // module namespace, not the constructor). Load it via require and type the
@@ -9,7 +9,10 @@ const PptxGenJS = require("pptxgenjs");
9
9
  // Matches text runs inside slide XML, e.g. <a:t>Hello</a:t>.
10
10
  const TEXT_RUN_RE = /<a:t>([^<]*)<\/a:t>/g;
11
11
  export async function readPptx(buf) {
12
- const zip = await JSZip.loadAsync(buf);
12
+ // .pptx is a zip container; same decompression-bomb exposure as .xlsx/.docx
13
+ // (see zipSafety.ts) — validate declared uncompressed size before reading
14
+ // any entry's content.
15
+ const zip = await loadSafeZip(buf);
13
16
  const slideFiles = Object.keys(zip.files)
14
17
  .filter((name) => /^ppt\/slides\/slide\d+\.xml$/.test(name))
15
18
  .sort((a, b) => slideNumber(a) - slideNumber(b));
@@ -1,27 +1,12 @@
1
1
  import ExcelJS from "exceljs";
2
- import JSZip from "jszip";
2
+ import { loadSafeZip } from "./zipSafety.js";
3
3
  const CELL_REF_RE = /^[A-Za-z]{1,3}[1-9][0-9]*$/;
4
4
  // exceljs's xlsx loader decompresses every entry of the .xlsx zip with no
5
- // size limit (CVE-2026-78206, unpatched upstream as of this writing) — a
6
- // small file whose declared uncompressed size is huge can exhaust memory
7
- // before exceljs itself ever runs. JSZip.loadAsync only reads the central
8
- // directory (cheap, no inflation), so summing each entry's *declared*
9
- // uncompressed size here rejects a bomb before handing the buffer to exceljs.
10
- const MAX_XLSX_UNCOMPRESSED_BYTES = 200 * 1024 * 1024;
5
+ // size limit (CVE-2026-78206, unpatched upstream as of this writing) — see
6
+ // zipSafety.ts for why checking declared sizes up front (via JSZip, which
7
+ // doesn't inflate) catches this before exceljs itself ever runs.
11
8
  async function assertSafeXlsxSize(buf) {
12
- const zip = await JSZip.loadAsync(buf);
13
- let total = 0;
14
- for (const entry of Object.values(zip.files)) {
15
- // `_data` is JSZip's internal CompressedObject; there is no public API
16
- // for a zip entry's declared (pre-inflation) uncompressed size.
17
- total +=
18
- entry._data?.uncompressedSize ?? 0;
19
- if (total > MAX_XLSX_UNCOMPRESSED_BYTES) {
20
- throw new Error(`This .xlsx file's declared uncompressed size exceeds ` +
21
- `${MAX_XLSX_UNCOMPRESSED_BYTES / (1024 * 1024)}MB and was refused ` +
22
- `as a likely decompression bomb rather than risk exhausting memory.`);
23
- }
24
- }
9
+ await loadSafeZip(buf);
25
10
  }
26
11
  export async function readXlsx(buf) {
27
12
  await assertSafeXlsxSize(buf);
@@ -0,0 +1,34 @@
1
+ import JSZip from "jszip";
2
+ /**
3
+ * .docx, .xlsx, and .pptx are all zip containers, and every library that
4
+ * reads them (exceljs, mammoth, and this codebase's own pptx reader via
5
+ * JSZip directly) decompresses each entry with no size limit — a small file
6
+ * whose declared uncompressed size is huge can exhaust memory before the
7
+ * library that actually parses the format ever runs (see CVE-2026-78206 for
8
+ * exceljs specifically; mammoth uses the same unbounded JSZip decompression
9
+ * path). Loading with JSZip first only reads the central directory (cheap,
10
+ * no inflation) so summing each entry's *declared* uncompressed size rejects
11
+ * a bomb before any real parsing starts.
12
+ */
13
+ const MAX_ZIP_UNCOMPRESSED_BYTES = 200 * 1024 * 1024;
14
+ /** Throws if `zip`'s entries declare more than `maxBytes` of uncompressed data combined. */
15
+ export function assertSafeZipEntries(zip, maxBytes = MAX_ZIP_UNCOMPRESSED_BYTES) {
16
+ let total = 0;
17
+ for (const entry of Object.values(zip.files)) {
18
+ // `_data` is JSZip's internal CompressedObject; there is no public API
19
+ // for a zip entry's declared (pre-inflation) uncompressed size.
20
+ total +=
21
+ entry._data?.uncompressedSize ?? 0;
22
+ if (total > maxBytes) {
23
+ throw new Error(`This file's declared uncompressed size exceeds ` +
24
+ `${maxBytes / (1024 * 1024)}MB and was refused as a likely decompression bomb ` +
25
+ `rather than risk exhausting memory.`);
26
+ }
27
+ }
28
+ }
29
+ /** Loads `buf` as a zip and validates its declared uncompressed size, returning the loaded zip for reuse. */
30
+ export async function loadSafeZip(buf, maxBytes = MAX_ZIP_UNCOMPRESSED_BYTES) {
31
+ const zip = await JSZip.loadAsync(buf);
32
+ assertSafeZipEntries(zip, maxBytes);
33
+ return zip;
34
+ }
@@ -7,6 +7,13 @@ import { readXlsx, writeXlsx, editXlsx } from "./document/xlsx.js";
7
7
  import { readPptx, writePptx } from "./document/pptx.js";
8
8
  import { readPdf, writePdf, editPdf } from "./document/pdf.js";
9
9
  const READABLE_EXTENSIONS = [".docx", ".xlsx", ".pptx", ".pdf"];
10
+ /**
11
+ * Bound the raw file read before it's dispatched to any format-specific
12
+ * reader. Each reader has its own internal limits (zip decompression caps,
13
+ * PDF page/text caps), but those only kick in once parsing has started —
14
+ * this stops an absurdly large file from being buffered into memory at all.
15
+ */
16
+ const MAX_DOCUMENT_FILE_BYTES = 200 * 1024 * 1024;
10
17
  const BLOCK_SCHEMA = {
11
18
  type: "array",
12
19
  description: "Flowed content blocks, in document order.",
@@ -39,6 +46,11 @@ export const readDocumentTool = {
39
46
  const relPath = String(args.path);
40
47
  const abs = resolveSafe(ctx.workspace, relPath);
41
48
  const ext = path.extname(abs).toLowerCase();
49
+ const { size } = await fs.stat(abs);
50
+ if (size > MAX_DOCUMENT_FILE_BYTES) {
51
+ throw new Error(`${relPath} is ${Math.round(size / (1024 * 1024))}MB, over the ` +
52
+ `${MAX_DOCUMENT_FILE_BYTES / (1024 * 1024)}MB limit for read_document.`);
53
+ }
42
54
  const buf = await fs.readFile(abs);
43
55
  switch (ext) {
44
56
  case ".docx":
@@ -1,6 +1,6 @@
1
1
  import { lookup as dnsLookup } from "node:dns/promises";
2
2
  import { truncateResult } from "./common.js";
3
- import { isPrivateOrLoopbackHost } from "../net/urlSafety.js";
3
+ import { isPrivateOrLoopbackHost, pinnedDispatcher, } from "../net/urlSafety.js";
4
4
  /** Cap on how much text a single fetch returns, unless the caller asks for less. */
5
5
  const DEFAULT_MAX_CHARS = 20_000;
6
6
  /** Give up on a slow or hanging server rather than blocking the whole turn. */
@@ -46,10 +46,13 @@ function assertPublicUrl(raw) {
46
46
  /**
47
47
  * Resolve `hostname` and check whether any answer is private/loopback.
48
48
  * assertPublicUrl only checks the literal hostname string, so a
49
- * public-looking name that resolves (now, or on a later request) to an
50
- * internal IP — DNS rebinding, or simply attacker-controlled DNS — slips
51
- * past it. This closes that gap for the initial request; lookupFn is
52
- * injectable for tests, and defaults to a real DNS resolution.
49
+ * public-looking name that resolves to an internal IP — DNS rebinding, or
50
+ * simply attacker-controlled DNS — slips past it. This is only a fast,
51
+ * friendly pre-check (a clear "refusing to fetch" error instead of a raw
52
+ * connection failure); the actual boundary is the pinned lookup on
53
+ * `pinnedDispatcher` below, which validates the one DNS answer that's
54
+ * actually connected to rather than resolving twice. lookupFn is injectable
55
+ * for tests, and defaults to a real DNS resolution.
53
56
  */
54
57
  export async function hostResolvesToPrivateAddress(hostname, lookupFn = dnsLookup) {
55
58
  try {
@@ -65,20 +68,24 @@ export async function hostResolvesToPrivateAddress(hostname, lookupFn = dnsLooku
65
68
  const MAX_REDIRECTS = 5;
66
69
  /**
67
70
  * Fetch `url`, following redirects manually so every hop — not just the
68
- * original URL — is checked against assertPublicUrl. A public URL that
69
- * 302s to 169.254.169.254 or localhost would otherwise sail straight past
70
- * the initial check, since `redirect: "follow"` never re-validates.
71
+ * original URL — is checked against assertPublicUrl before the (DNS-pinned)
72
+ * connection is even attempted. A public URL that 302s to 169.254.169.254
73
+ * or localhost would otherwise sail straight past the initial check, since
74
+ * `redirect: "follow"` never re-validates.
71
75
  */
72
- async function assertNotDnsRebound(url) {
73
- if (await hostResolvesToPrivateAddress(url.hostname)) {
74
- throw new Error(`Refusing to fetch ${url.hostname}: resolves to a private/internal address`);
75
- }
76
- }
77
76
  async function fetchFollowingRedirects(url, signal, headers) {
78
77
  let current = url;
79
- await assertNotDnsRebound(current);
80
78
  for (let hop = 0;; hop++) {
81
- const res = await fetch(current, { redirect: "manual", signal, headers });
79
+ if (await hostResolvesToPrivateAddress(current.hostname)) {
80
+ throw new Error(`Refusing to fetch ${current.hostname}: resolves to a private/internal address`);
81
+ }
82
+ const init = {
83
+ redirect: "manual",
84
+ signal,
85
+ headers,
86
+ dispatcher: pinnedDispatcher,
87
+ };
88
+ const res = await fetch(current, init);
82
89
  const isRedirect = res.status >= 300 && res.status < 400;
83
90
  const location = res.headers.get("location");
84
91
  if (!isRedirect || !location) {
@@ -88,7 +95,6 @@ async function fetchFollowingRedirects(url, signal, headers) {
88
95
  throw new Error(`Too many redirects fetching ${url.href} (stopped at ${current.href})`);
89
96
  }
90
97
  current = assertPublicUrl(new URL(location, current).href);
91
- await assertNotDnsRebound(current);
92
98
  }
93
99
  }
94
100
  /**
@@ -56,7 +56,20 @@ function summarizeOutputs(outputs) {
56
56
  return (text.slice(0, MAX_OUTPUT_CHARS) +
57
57
  `\n... [output truncated, ${text.length - MAX_OUTPUT_CHARS} more characters]`);
58
58
  }
59
+ /**
60
+ * Cell *output* text is already capped post-parse (MAX_OUTPUT_CHARS above),
61
+ * but nothing bounded the input file itself — a pathologically large
62
+ * .ipynb (corrupt, or a runaway export) would otherwise be read and
63
+ * JSON.parse'd whole regardless of size. Real notebooks are nowhere near
64
+ * this large even with heavy output.
65
+ */
66
+ const MAX_NOTEBOOK_FILE_BYTES = 50 * 1024 * 1024;
59
67
  async function loadNotebook(abs) {
68
+ const { size } = await fs.stat(abs);
69
+ if (size > MAX_NOTEBOOK_FILE_BYTES) {
70
+ throw new Error(`Notebook file is ${Math.round(size / (1024 * 1024))}MB, over the ` +
71
+ `${MAX_NOTEBOOK_FILE_BYTES / (1024 * 1024)}MB limit for reading a .ipynb file.`);
72
+ }
60
73
  const text = await fs.readFile(abs, "utf8");
61
74
  let nb;
62
75
  try {
@@ -38,7 +38,12 @@ export const shellTool = {
38
38
  // background command returns immediately. A second, shorter cap from the
39
39
  // agent loop would cut off commands the user explicitly asked to run longer.
40
40
  timeoutMs: 0,
41
- summarize: (args) => `Run${args.background ? " in background" : ""}: ${args.command}`,
41
+ // The summary is what lands in the audit log and telemetry spans (see
42
+ // toolExecutor's `kritya.summary` attribute), so it needs the same
43
+ // redaction as the background-start echo below — otherwise a credential
44
+ // embedded in the command (e.g. a curl Authorization header) gets
45
+ // persisted in plain text on every ordinary foreground call.
46
+ summarize: (args) => `Run${args.background ? " in background" : ""}: ${redactSecrets(String(args.command ?? "")).redacted}`,
42
47
  // A command that printed nothing needs no preview to say so — but every
43
48
  // other command's output is the answer, so keep it (null = show the preview).
44
49
  resultSummary: (output) => (output.trim() === "(no output)" ? "no output" : null),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kritya",
3
- "version": "0.8.21-beta",
3
+ "version": "0.8.23-beta",
4
4
  "description": "Kritya — a lean, provider-agnostic terminal coding agent (NVIDIA, OpenAI, OpenRouter, Groq, Ollama, and more)",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -67,7 +67,8 @@
67
67
  "pdfjs-dist": "^6.3.289",
68
68
  "pptxgenjs": "^4.0.1",
69
69
  "react": "^19.2.8",
70
- "string-width": "^8.2.2"
70
+ "string-width": "^8.2.2",
71
+ "undici": "^7.29.0"
71
72
  },
72
73
  "devDependencies": {
73
74
  "@eslint/js": "^10.0.1",