@blackbelt-technology/pi-dashboard-document-converter 0.8.0 → 0.9.0

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.
@@ -24,7 +24,11 @@ Call the facade; never invoke Python, docling, or pdftotext directly.
24
24
 
25
25
  ```ts
26
26
  import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-document-converter";
27
- const dc = createDocumentConverter({ image: "pi-doc-engine:0.1.0", stagingDir: "/abs/staging" });
27
+ const dc = createDocumentConverter({
28
+ image: "pi-doc-engine:0.1.0",
29
+ stagingDir: "/abs/staging",
30
+ mounts: ["/docs"], // files outside cwd need a root (mounts or workspaceRoot), else PATH_NOT_ALLOWED
31
+ });
28
32
 
29
33
  const { output } = await dc.convertToMarkdown("<file_path>"); // digital PDF/DOCX/…
30
34
  // scanned PDF: pass OCR explicitly
@@ -33,7 +37,7 @@ await dc.convertToMarkdown("<file_path>", { ocr: { mode: "force", lang: ["englis
33
37
 
34
38
  The result is a provenance-stamped `.md` in `stagingDir`. Read that file to get
35
39
  the document text. On failure the call rejects with `DocConverterError`
36
- (`.code`, `.stderr`) — surface `UNSUPPORTED_FORMAT`, `OCR_LANG_UNSUPPORTED`,
40
+ (`.code`, `.stderr`) — surface `UNSUPPORTED_FORMAT`, `PATH_NOT_ALLOWED`, `OCR_LANG_UNSUPPORTED`,
37
41
  `INGEST_FAILED`, `DOCKER_UNAVAILABLE` rather than retrying blindly.
38
42
 
39
43
  ## Step 2 — Decide direct vs. chunked
@@ -17,6 +17,10 @@ Do NOT read the vendored Python under `engine/document_converter/`.
17
17
  ## Prerequisites
18
18
 
19
19
  - Docker available; image built: `cd packages/document-converter && npm run build:image`.
20
+ The `pi.tools` manifest (package root) declares `pi-doc-engine` as a
21
+ `docker-image` probe — `pi-dashboard-ensure <package-root>/package.json`
22
+ reports image presence and the first-party build hint (confirm-gated) via
23
+ the registry's Settings → Tools row.
20
24
  - Styled diagrams (nano-banana) need `GEMINI_API_KEY` at run time; absent or on
21
25
  failure, rendering falls back to mmdc (never hard-fails).
22
26
 
@@ -26,7 +30,11 @@ Do NOT read the vendored Python under `engine/document_converter/`.
26
30
 
27
31
  ```ts
28
32
  import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-document-converter";
29
- const dc = createDocumentConverter({ image: "pi-doc-engine:0.1.0", stagingDir: "/abs/kb-staging" });
33
+ const dc = createDocumentConverter({
34
+ image: "pi-doc-engine:0.1.0",
35
+ stagingDir: "/abs/kb-staging",
36
+ mounts: ["/docs"], // files outside cwd need a root (mounts or workspaceRoot), else PATH_NOT_ALLOWED
37
+ });
30
38
 
31
39
  await dc.convertToMarkdown("/docs/report.pdf"); // digital PDF (auto: native-first)
32
40
  await dc.convertToMarkdown("/docs/scan.pdf", { // scanned HU PDF
@@ -75,5 +83,5 @@ All stages read/write one unified schema (`./schema`): template vars ·
75
83
  ## Errors
76
84
 
77
85
  Every method rejects with `DocConverterError` (`.code`, `.stderr`, `.exitCode`):
78
- `UNSUPPORTED_FORMAT`, `OCR_LANG_UNSUPPORTED`, `INGEST_FAILED`, `PRODUCE_FAILED`,
86
+ `UNSUPPORTED_FORMAT`, `PATH_NOT_ALLOWED`, `OCR_LANG_UNSUPPORTED`, `INGEST_FAILED`, `PRODUCE_FAILED`,
79
87
  `DOCKER_UNAVAILABLE`, … Surface `.code` + `.stderr`; do not retry blindly.
package/README.md CHANGED
@@ -16,6 +16,8 @@ import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-docu
16
16
  const dc = createDocumentConverter({
17
17
  image: "pi-doc-engine:0.1.0",
18
18
  stagingDir: "/abs/kb-staging",
19
+ // Files outside process.cwd() must sit under a configured root:
20
+ mounts: ["/docs", "/out"], // or workspaceRoot: "/abs/project"
19
21
  });
20
22
 
21
23
  // Ingest -> Markdown with provenance frontmatter (written into stagingDir).
@@ -68,10 +70,23 @@ The `provenance` frontmatter (`source_path`, `sha256`, `doc_type`,
68
70
  originating file. Re-ingesting an unchanged file yields the same `sha256`, so
69
71
  staging output is byte-stable (idempotent by hash).
70
72
 
73
+ ## Path confinement
74
+
75
+ Every absolute path in a request must lie under a configured root:
76
+ `stagingDir` (mounted read-write), `mounts`, or `workspaceRoot` (default
77
+ `process.cwd()`). Comparison uses real paths, so a symlink cannot escape a root.
78
+ Sensitive dirs (`/etc`, `/root`, `/var/run`, `/proc`, `/sys`, `/dev`, `~/.ssh`,
79
+ `~/.aws`, `~/.gnupg`, `~/.config`, `~/.pi`, `~/.docker`, `~/.kube`) are refused
80
+ unless a root containing the path is itself inside that dir. A root of `/` is
81
+ refused. Violations reject with `DocConverterError` code `PATH_NOT_ALLOWED`
82
+ before docker runs. Inputs of `convertToMarkdown`, `renderPdf`, and
83
+ `fillFrontmatter`/`profileTables` with `apply:false` mount read-only.
84
+
71
85
  ## Templates (runtime-mounted, not baked)
72
86
 
73
87
  DOCX templates are NOT baked into the image — pass `templatesDir` (an absolute
74
- host dir containing `<template>/template.docx`); the facade bind-mounts it. Keeps
88
+ host dir containing `<template>/template.docx`, under a configured root — add it
89
+ to `mounts`); the facade bind-mounts it. Keeps
75
90
  branded/template assets out of the image and the repo.
76
91
 
77
92
  ## Engine image
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-document-converter",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "TypeScript facade over a Dockerized Python document engine (pi-doc-engine). Bidirectional: ingest any format to provenance-stamped Markdown for kb, produce templated DOCX/PDF with diagrams. Engine quarantined in Docker; TS is the only call surface.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -16,6 +16,12 @@
16
16
  "skills": [
17
17
  ".pi/skills/document-converter",
18
18
  ".pi/skills/doc-summarizer"
19
+ ],
20
+ "tools": [
21
+ {
22
+ "id": "pi-doc-engine",
23
+ "probe": "docker-image"
24
+ }
19
25
  ]
20
26
  },
21
27
  "exports": {
@@ -30,7 +36,7 @@
30
36
  "test": "vitest run"
31
37
  },
32
38
  "dependencies": {
33
- "@blackbelt-technology/pi-dashboard-shared": "^0.8.0"
39
+ "@blackbelt-technology/pi-dashboard-shared": "^0.9.0"
34
40
  },
35
41
  "files": [
36
42
  "dist",
package/src/engine.ts CHANGED
@@ -3,14 +3,22 @@
3
3
  *
4
4
  * Spawns `docker run -i pi-doc-engine`, pipes one JSON request to stdin, reads
5
5
  * one JSON response from stdout, and maps exit codes + the response envelope to
6
- * typed errors. Mounts are **path-identical** (`-v dir:dir -w dir`) so host
7
- * paths equal container paths — no path rewriting needed.
6
+ * typed errors. Mount *targets* keep the lexical request path so container
7
+ * paths equal request paths — no path rewriting needed; mount *sources* are the
8
+ * realpath'd host dir that is actually exposed.
9
+ *
10
+ * Confinement (change: harden-untrusted-content-ingestion, D1): every absolute
11
+ * request path must lie under a configured root (`writable` ∪ `mounts` ∪
12
+ * `workspaceRoot`), outside the sensitive denylist, before docker is spawned.
8
13
  *
9
14
  * The raw runner is injectable so unit tests can mock the Docker boundary
10
15
  * without a container.
11
16
  */
17
+
18
+ import { mkdir, realpath, stat } from "node:fs/promises";
19
+ import { homedir } from "node:os";
20
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
12
21
  import { spawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
13
- import { dirname } from "node:path";
14
22
  import { DocConverterError } from "./errors.js";
15
23
 
16
24
  /** One JSON request to the engine. `command` selects the handler. */
@@ -49,8 +57,12 @@ export type EngineRunner = (argv: string[], stdin: string) => Promise<RunnerResu
49
57
  export interface EngineConfig {
50
58
  /** Image tag, e.g. `pi-doc-engine:0.1.0`. */
51
59
  image: string;
52
- /** Host dirs to bind-mount path-identically (parents of all referenced files). */
60
+ /** Roots always mounted read-write (the facade puts `stagingDir` here). Created on demand. */
61
+ writable?: string[];
62
+ /** Extra caller-configured roots. Request paths under them are admitted. */
53
63
  mounts?: string[];
64
+ /** Workspace root admitting request paths (default `process.cwd()`). */
65
+ workspaceRoot?: string;
54
66
  /** Passed through to `docker run -e GEMINI_API_KEY` when set in env. */
55
67
  passEnv?: string[];
56
68
  /** Override the process runner (tests). */
@@ -88,10 +100,18 @@ const defaultRunner: EngineRunner = (argv, stdin) =>
88
100
  child.stdin.end(stdin);
89
101
  });
90
102
 
103
+ /** One planned bind mount, keyed by its (lexical) container target. */
104
+ interface PlannedMount {
105
+ source: string;
106
+ mode: "ro" | "rw";
107
+ }
108
+
91
109
  /** Build the `docker run` argv for a request. */
92
- function buildArgv(cfg: EngineConfig, mounts: Set<string>): string[] {
110
+ function buildArgv(cfg: EngineConfig, mounts: Map<string, PlannedMount>): string[] {
93
111
  const argv = [cfg.dockerBin ?? "docker", "run", "--rm", "-i"];
94
- for (const m of mounts) argv.push("-v", `${m}:${m}`);
112
+ for (const [target, { source, mode }] of mounts) {
113
+ argv.push("-v", mode === "ro" ? `${source}:${target}:ro` : `${source}:${target}`);
114
+ }
95
115
  for (const key of cfg.passEnv ?? ["GEMINI_API_KEY"]) {
96
116
  if (process.env[key] !== undefined) argv.push("-e", key);
97
117
  }
@@ -99,18 +119,136 @@ function buildArgv(cfg: EngineConfig, mounts: Set<string>): string[] {
99
119
  return argv;
100
120
  }
101
121
 
102
- /** Collect every filesystem path referenced by a request so we can mount its dir. */
103
- function collectMountDirs(cfg: EngineConfig, req: EngineRequest): Set<string> {
104
- const dirs = new Set<string>(cfg.mounts ?? []);
105
- const add = (p: unknown) => {
106
- if (typeof p === "string" && p.startsWith("/")) dirs.add(dirname(p));
122
+ /** Sensitive host dirs never mounted unless a containing root opts in. `~` = homedir at call time. */
123
+ const DENYLIST = ["/etc", "/root", "/var/run", "/proc", "/sys", "/dev"];
124
+ const HOME_DENYLIST = [".ssh", ".aws", ".gnupg", ".config", ".pi", ".docker", ".kube"];
125
+
126
+ /**
127
+ * Write keys per command (mounted rw), and whether the command's other paths
128
+ * are verified read-only. Unknown commands mount everything rw (within
129
+ * confinement). Engine write sites: design D1 table.
130
+ */
131
+ function modeFor(req: EngineRequest): { writeKeys: Set<string>; othersRo: boolean } {
132
+ const apply = req.apply !== false;
133
+ switch (req.command) {
134
+ case "convertToMarkdown":
135
+ return { writeKeys: new Set(), othersRo: true };
136
+ case "renderPdf":
137
+ return { writeKeys: new Set(["output"]), othersRo: true };
138
+ case "renderDocx":
139
+ return { writeKeys: new Set(["output", "cacheDir"]), othersRo: false };
140
+ case "extractForEdit":
141
+ case "mergeBack":
142
+ return { writeKeys: new Set(["output"]), othersRo: false };
143
+ case "fillFrontmatter":
144
+ case "profileTables":
145
+ return apply ? { writeKeys: new Set(["paths"]), othersRo: false } : { writeKeys: new Set(), othersRo: true };
146
+ default:
147
+ return { writeKeys: new Set(), othersRo: false };
148
+ }
149
+ }
150
+
151
+ const isUnder = (p: string, root: string) => p === root || p.startsWith(root.endsWith(sep) ? root : root + sep);
152
+
153
+ /** realpath of the nearest existing ancestor, with the non-existent remainder re-appended. */
154
+ async function realpathLoose(p: string): Promise<string> {
155
+ let cur = resolve(p);
156
+ const rest: string[] = [];
157
+ for (;;) {
158
+ try {
159
+ return join(await realpath(cur), ...rest.reverse());
160
+ } catch {
161
+ const parent = dirname(cur);
162
+ if (parent === cur) return resolve(p);
163
+ rest.push(basename(cur));
164
+ cur = parent;
165
+ }
166
+ }
167
+ }
168
+
169
+ async function isDir(p: string): Promise<boolean> {
170
+ try {
171
+ return (await stat(p)).isDirectory();
172
+ } catch {
173
+ return false;
174
+ }
175
+ }
176
+
177
+ function notAllowed(path: string, why: string, roots: string[]): DocConverterError {
178
+ return new DocConverterError({
179
+ code: "PATH_NOT_ALLOWED",
180
+ message:
181
+ `path not allowed: ${path} (${why}). Configured roots: ${roots.join(", ") || "(none)"}. ` +
182
+ `Pass \`mounts:[dir]\` or \`workspaceRoot\` to admit files outside the workspace.`,
183
+ });
184
+ }
185
+
186
+ /**
187
+ * Plan the bind mounts for a request, enforcing confinement + denylist.
188
+ * Throws `PATH_NOT_ALLOWED` before anything is spawned.
189
+ */
190
+ async function planMounts(cfg: EngineConfig, req: EngineRequest): Promise<Map<string, PlannedMount>> {
191
+ const configured = [...(cfg.writable ?? []), ...(cfg.mounts ?? []), cfg.workspaceRoot ?? process.cwd()];
192
+ // Materialise roots: create writable ones, then realpath every root.
193
+ for (const w of cfg.writable ?? []) await mkdir(w, { recursive: true });
194
+ const roots: string[] = [];
195
+ for (const r of configured) {
196
+ const real = await realpathLoose(r);
197
+ if (real === sep || resolve(r) === sep) throw notAllowed(r, "`/` cannot be a root", configured);
198
+ roots.push(real);
199
+ }
200
+
201
+ // Denylist entries, lexical + realpath (e.g. /var/run → /run, symlinked ~/.pi).
202
+ const home = homedir();
203
+ const deny: string[][] = [];
204
+ for (const d of [...DENYLIST, ...HOME_DENYLIST.map((h) => join(home, h))]) {
205
+ deny.push([...new Set([d, await realpathLoose(d)])]);
206
+ }
207
+
208
+ const plan = new Map<string, PlannedMount>();
209
+ const addMount = (target: string, source: string, mode: "ro" | "rw") => {
210
+ const prev = plan.get(target);
211
+ plan.set(target, { source, mode: prev?.mode === "rw" ? "rw" : mode });
107
212
  };
213
+ for (const w of cfg.writable ?? []) addMount(resolve(w), await realpathLoose(w), "rw");
214
+
215
+ const { writeKeys, othersRo } = modeFor(req);
216
+ const check = async (p: string, mode: "ro" | "rw") => {
217
+ if (!isAbsolute(p)) return; // engine has no host cwd: relative paths never hit host files
218
+ if (p.split(/[\\/]/).includes("..")) throw notAllowed(p, "`..` segment", configured);
219
+ if (p.includes(":")) throw notAllowed(p, "`:` breaks the bind-mount spec", configured);
220
+ const lexical = resolve(p);
221
+ const globAt = lexical.search(/[*?[]/);
222
+ let target: string;
223
+ if (globAt >= 0) target = dirname(lexical.slice(0, globAt + 1));
224
+ else if (await isDir(lexical)) target = lexical;
225
+ else target = dirname(lexical);
226
+ const realPath = await realpathLoose(lexical.slice(0, globAt >= 0 ? globAt : undefined));
227
+ const source = await realpathLoose(target);
228
+
229
+ const containing = roots.filter((r) => isUnder(realPath, r) && isUnder(source, r));
230
+ if (containing.length === 0) throw notAllowed(p, "outside every configured root", configured);
231
+ for (const variants of deny) {
232
+ const hit = variants.some((d) => isUnder(source, d) || isUnder(realPath, d) || (globAt >= 0 && isUnder(d, source)));
233
+ if (!hit) continue;
234
+ const optedIn = containing.some((r) => variants.some((d) => isUnder(r, d)));
235
+ if (!optedIn) throw notAllowed(p, `sensitive directory ${variants[0]}`, configured);
236
+ }
237
+ addMount(target, source, mode);
238
+ };
239
+
108
240
  for (const [k, v] of Object.entries(req)) {
109
241
  if (k === "command") continue;
110
- if (Array.isArray(v)) v.forEach(add);
111
- else add(v);
242
+ const mode = writeKeys.has(k) || !othersRo ? "rw" : "ro";
243
+ for (const item of Array.isArray(v) ? v : [v]) {
244
+ if (typeof item === "string") await check(item, mode);
245
+ }
246
+ }
247
+ // Only after every path passed: create missing rw dirs (else docker creates them as root).
248
+ for (const { source, mode } of plan.values()) {
249
+ if (mode === "rw" && !(await isDir(source))) await mkdir(source, { recursive: true });
112
250
  }
113
- return dirs;
251
+ return plan;
114
252
  }
115
253
 
116
254
  /**
@@ -122,7 +260,7 @@ export async function runEngine<T = Record<string, unknown>>(
122
260
  req: EngineRequest,
123
261
  ): Promise<T> {
124
262
  const runner = cfg.runner ?? defaultRunner;
125
- const argv = buildArgv(cfg, collectMountDirs(cfg, req));
263
+ const argv = buildArgv(cfg, await planMounts(cfg, req));
126
264
  const { stdout, stderr, exitCode } = await runner(argv, JSON.stringify(req));
127
265
 
128
266
  let parsed: EngineResponse | undefined;
package/src/errors.ts CHANGED
@@ -12,6 +12,7 @@ export type DocConverterErrorCode =
12
12
  | "OCR_LANG_UNSUPPORTED" // canonical lang not supported by chosen engine
13
13
  | "OCR_ENGINE_UNKNOWN" // unknown OCR engine
14
14
  | "UNSUPPORTED_FORMAT" // extension not routable to a command
15
+ | "PATH_NOT_ALLOWED" // request path outside configured roots or in a sensitive dir
15
16
  | "INGEST_FAILED"
16
17
  | "PRODUCE_FAILED"
17
18
  | "FILL_FAILED"
package/src/index.ts CHANGED
@@ -7,14 +7,14 @@
7
7
  */
8
8
  import { mkdir, writeFile } from "node:fs/promises";
9
9
  import { basename, join } from "node:path";
10
- import { runEngine, type EngineConfig } from "./engine.js";
10
+ import { type EngineConfig, runEngine } from "./engine.js";
11
11
  import { mapOcrCodes } from "./ocr.js";
12
- import { ingestDocType } from "./routing.js";
13
12
  import {
14
13
  buildProvenance,
15
14
  sha256File,
16
15
  stampProvenance,
17
16
  } from "./provenance.js";
17
+ import { ingestDocType } from "./routing.js";
18
18
  import type {
19
19
  ConvertToMarkdownOptions,
20
20
  ConvertToMarkdownResult,
@@ -32,8 +32,10 @@ export interface DocumentConverterConfig {
32
32
  image: string;
33
33
  /** Staging dir where ingest writes `.md` for kb. Created on demand. */
34
34
  stagingDir: string;
35
- /** Extra host dirs to bind-mount path-identically. */
35
+ /** Extra host roots: request paths under them are admitted (mounted on demand). */
36
36
  mounts?: string[];
37
+ /** Workspace root admitting request paths (default `process.cwd()`). */
38
+ workspaceRoot?: string;
37
39
  /** Test hook: inject the engine config (e.g. a fake runner). */
38
40
  engine?: Partial<EngineConfig>;
39
41
  }
@@ -42,7 +44,9 @@ export interface DocumentConverterConfig {
42
44
  export function createDocumentConverter(config: DocumentConverterConfig) {
43
45
  const engineCfg = (extraMounts: string[] = []): EngineConfig => ({
44
46
  image: config.image,
45
- mounts: [config.stagingDir, ...(config.mounts ?? []), ...extraMounts],
47
+ writable: [config.stagingDir],
48
+ mounts: [...(config.mounts ?? []), ...extraMounts],
49
+ workspaceRoot: config.workspaceRoot,
46
50
  ...config.engine,
47
51
  });
48
52
 
@@ -164,16 +168,16 @@ function replaceExt(name: string, ext: string): string {
164
168
  return name.replace(/\.[^.]+$/, "") + ext;
165
169
  }
166
170
 
167
- export { DocConverterError } from "./errors.js";
168
171
  export type { DocConverterErrorCode } from "./errors.js";
169
- export * from "./types.js";
172
+ export { DocConverterError } from "./errors.js";
173
+ export { mapOcrCodes, SUPPORTED_LANGUAGES } from "./ocr.js";
174
+ export { buildProvenance, provenanceFrontmatter, sha256File, stampProvenance } from "./provenance.js";
175
+ export { docTypeOf, ingestDocType, isIngestable } from "./routing.js";
170
176
  export type {
171
177
  DocumentFrontmatter,
172
- Provenance,
173
178
  NanoBananaConfig,
174
- TableProfiles,
179
+ Provenance,
175
180
  TableProfile,
181
+ TableProfiles,
176
182
  } from "./schema.js";
177
- export { mapOcrCodes, SUPPORTED_LANGUAGES } from "./ocr.js";
178
- export { docTypeOf, isIngestable, ingestDocType } from "./routing.js";
179
- export { buildProvenance, stampProvenance, provenanceFrontmatter, sha256File } from "./provenance.js";
183
+ export * from "./types.js";