@gitpagedocs/tools 0.0.14 → 0.0.15

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.
package/README.md CHANGED
@@ -14,7 +14,7 @@ The **shared business-logic core** of the [Git Page Docs](../README.md) monorepo
14
14
  | `config-format/` | Browser-safe `compactSiteIcons` / `expandSiteIcons` and `applyRouteDefaults` / `factorRouteDefaults` for compact configuration and inherited route values |
15
15
  | `logger/` | Level-filtered logger with **secret redaction** |
16
16
  | `errors/` | `AppError` + typed subclasses |
17
- | `filesystem/` | `FileService` (list/read/write/search with lexical root containment; filesystem symlinks/junctions still require trusted deployment boundaries) |
17
+ | `filesystem/` | `FileService` (list/read/write/search with lexical and canonical root containment; validates existing parents before creating files and rejects destination symlinks on writes; concurrent path replacement still requires trusted filesystem boundaries) |
18
18
  | `documentation/` | `DocumentationService`, `patchManagedRegion`, `DocUpdater` |
19
19
  | `i18n/` | Language bundles (`site.languages` toggles in `config.json` + `langs/<lang>.json`): `loadConfigLanguageBundles`, `applyLanguageBundles` (fold into `site.langmenu` / `translations`), `filterEnabledLanguages`, `splitLanguageBundles` (generator side); browser-safe |
20
20
  | `ports/` | Type-only contracts (logger, cache, crypto, security, config, ai) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gitpagedocs/tools",
3
- "version": "0.0.14",
3
+ "version": "0.0.15",
4
4
  "type": "module",
5
5
  "description": "Shared business-logic core for Git Page Docs (consumed by frontend, cli and mcp). Ships TypeScript source; consume via tsx or a TS-aware bundler.",
6
6
  "main": "./src/index.ts",
@@ -39,7 +39,7 @@ export function cliCommandsSection(commands: readonly CommandDoc[]): string {
39
39
  "### User references",
40
40
  "",
41
41
  "The generated documentation includes 35 Markdown pages per language: focused references plus complete configuration recipes, migration/compatibility, troubleshooting, contributing/testing and HTML-container guides. All pages are available in English, Portuguese and Spanish; Markdown filenames stay in English while titles and content preserve UTF-8 accents and special characters.",
42
- "The scaffold registers documentation versions 0.0.14, 0.0.13, 0.0.12, 0.0.11, 0.0.10 and 0.0.9 in descending order with the current examples; the npm package version is 0.0.14. Paths and version badges match each generated documentation version. Existing older version folders are preserved.",
42
+ "The scaffold registers documentation versions 0.0.15, 0.0.14, 0.0.13, 0.0.12, 0.0.11, 0.0.10 and 0.0.9 in descending order with the current examples; the npm package version is 0.0.15. Paths and version badges match each generated documentation version. Existing older version folders are preserved.",
43
43
  "",
44
44
  "The scaffold has real nested sections: Guides → Configure your site / Read and explore / Automate and integrate → documents, plus Operations and development and Git/GitHub groups. Getting Started and Project overview remain the first destinations. Every parent section has its own localized Markdown overview: click its title to read it, or use the separate arrow to expand children. Breadcrumb ancestors such as Guides → Configure your site remain navigable. Recursive `submenus` can extend the hierarchy without a fixed depth limit; `site.nestedMenusEnabled: false` keeps every destination in a flat presentation.",
45
45
  "",
@@ -76,7 +76,7 @@ export function cliCommandsSection(commands: readonly CommandDoc[]): string {
76
76
  "Configure `site.pdf` with `enabled`, `previewEnabled`, `downloadEnabled` and `openInNewTabEnabled` (all default to `true`). The version config uses `routes-pdf`, `pdf.pathPdf` per language and `menus-header-pdf` with `page:23` for the bundled example. Route-level preview/download/new-tab options go inside `pdf`; `hierarchyPage.pdf` and `hierarchyMenu.pdf` order the content and menu sections.",
77
77
  "",
78
78
  "```json",
79
- '{ "id": 23, "pdf": { "pathPdf": { "en": "gitpagedocs/docs/versions/0.0.14/en/gitpagedocs-project-guide.pdf", "pt": "gitpagedocs/docs/versions/0.0.14/en/gitpagedocs-project-guide.pdf", "es": "gitpagedocs/docs/versions/0.0.14/en/gitpagedocs-project-guide.pdf" }, "previewEnabled": true, "downloadEnabled": true, "openInNewTabEnabled": true } }',
79
+ '{ "id": 23, "pdf": { "pathPdf": { "en": "gitpagedocs/docs/versions/0.0.15/en/gitpagedocs-project-guide.pdf", "pt": "gitpagedocs/docs/versions/0.0.15/en/gitpagedocs-project-guide.pdf", "es": "gitpagedocs/docs/versions/0.0.15/en/gitpagedocs-project-guide.pdf" }, "previewEnabled": true, "downloadEnabled": true, "openInNewTabEnabled": true } }',
80
80
  "```",
81
81
  "",
82
82
  "The native browser viewer handles PDF previews and new tabs through validated `application/pdf` Blob URLs. Preview, download and new-tab actions all require CORS permission for external files. Opening a new tab does not navigate to the raw repository URL, so that server's Content-Type/Content-Disposition does not force a download. Browser PDF support and user preferences still apply. With preview disabled, the first download or new-tab action loads the PDF; cached bytes are reused. File/network errors and blocked pop-ups are reported without silently falling back to the raw URL.",
@@ -114,13 +114,13 @@ export function cliCommandsSection(commands: readonly CommandDoc[]): string {
114
114
  ' "title": { "en": "DOOM: HTML example", "pt": "DOOM: exemplo HTML", "es": "DOOM: ejemplo HTML" },',
115
115
  ' "description": { "en": "Load an interactive HTML demo", "pt": "Carregue uma demonstração HTML interativa", "es": "Carga una demostración HTML interactiva" },',
116
116
  ' "titleIsVisible": true, "descriptionIsVisible": true, "container": "full",',
117
- ' "path": { "en": "gitpagedocs/docs/versions/0.0.14/en/doom.html", "pt": "gitpagedocs/docs/versions/0.0.14/pt/doom.html", "es": "gitpagedocs/docs/versions/0.0.14/es/doom.html" }',
117
+ ' "path": { "en": "gitpagedocs/docs/versions/0.0.15/en/doom.html", "pt": "gitpagedocs/docs/versions/0.0.15/pt/doom.html", "es": "gitpagedocs/docs/versions/0.0.15/es/doom.html" }',
118
118
  " }],",
119
119
  ' "menus-header-html": [{',
120
120
  ' "id": 29,',
121
- ' "en": { "title": "DOOM: HTML example", "path-click": "gitpagedocs/docs/versions/0.0.14/en/doom.html" },',
122
- ' "pt": { "title": "DOOM: exemplo HTML", "path-click": "gitpagedocs/docs/versions/0.0.14/pt/doom.html" },',
123
- ' "es": { "title": "DOOM: ejemplo HTML", "path-click": "gitpagedocs/docs/versions/0.0.14/es/doom.html" }',
121
+ ' "en": { "title": "DOOM: HTML example", "path-click": "gitpagedocs/docs/versions/0.0.15/en/doom.html" },',
122
+ ' "pt": { "title": "DOOM: exemplo HTML", "path-click": "gitpagedocs/docs/versions/0.0.15/pt/doom.html" },',
123
+ ' "es": { "title": "DOOM: ejemplo HTML", "path-click": "gitpagedocs/docs/versions/0.0.15/es/doom.html" }',
124
124
  " }]",
125
125
  "}",
126
126
  "```",
@@ -1,5 +1,6 @@
1
1
  import path from "node:path";
2
- import { readFile, writeFile, mkdir, readdir, stat } from "node:fs/promises";
2
+ import type { Stats } from "node:fs";
3
+ import { readFile, writeFile, mkdir, readdir, stat, realpath, lstat } from "node:fs/promises";
3
4
  import { RepositoryError, ValidationError } from "../errors/app-error";
4
5
 
5
6
  const DEFAULT_IGNORE = new Set([
@@ -60,19 +61,41 @@ function compareCodeUnits(a: string, b: string): number {
60
61
  return 0;
61
62
  }
62
63
 
64
+ async function inspectExistingPath(absolute: string): Promise<Stats | undefined> {
65
+ try {
66
+ return await lstat(absolute);
67
+ } catch (cause) {
68
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return undefined;
69
+ throw cause;
70
+ }
71
+ }
72
+
73
+ function assertContained(root: string, absolute: string, requestedPath: string): void {
74
+ const relative = path.relative(root, absolute);
75
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
76
+ throw new ValidationError(`Path escapes the project root: ${requestedPath}`);
77
+ }
78
+ }
79
+
80
+ interface ResolvedPath {
81
+ absolute: string;
82
+ symbolicLink: boolean;
83
+ }
84
+
63
85
  /**
64
86
  * Root-bounded filesystem service. All paths are resolved relative to `root`
65
87
  * and may not escape it — the single safe FS surface for the CLI and MCP.
66
88
  */
67
89
  export class FileService {
68
- constructor(private readonly root: string) {}
90
+ private readonly root: string;
91
+
92
+ constructor(root: string) {
93
+ this.root = path.resolve(root);
94
+ }
69
95
 
70
96
  private resolveInside(relativePath: string): string {
71
97
  const abs = path.resolve(this.root, relativePath);
72
- const rel = path.relative(this.root, abs);
73
- if (rel.startsWith("..") || path.isAbsolute(rel)) {
74
- throw new ValidationError(`Path escapes the project root: ${relativePath}`);
75
- }
98
+ assertContained(this.root, abs, relativePath);
76
99
  return abs;
77
100
  }
78
101
 
@@ -80,6 +103,40 @@ export class FileService {
80
103
  return path.relative(this.root, abs).split(path.sep).join("/");
81
104
  }
82
105
 
106
+ private async resolvePhysicalPath(relativePath: string): Promise<ResolvedPath> {
107
+ const requested = this.resolveInside(relativePath);
108
+ try {
109
+ const root = await realpath(this.root);
110
+ let ancestor = requested;
111
+ const missing: string[] = [];
112
+ let existing = await inspectExistingPath(ancestor);
113
+ while (!existing) {
114
+ const parent = path.dirname(ancestor);
115
+ if (parent === ancestor) throw new RepositoryError(`Cannot resolve path: ${relativePath}`);
116
+ missing.unshift(path.basename(ancestor));
117
+ ancestor = parent;
118
+ existing = await inspectExistingPath(ancestor);
119
+ }
120
+ const resolved = await realpath(ancestor).catch((cause) => {
121
+ if (existing.isSymbolicLink()) {
122
+ throw new ValidationError(`Cannot resolve symbolic link: ${relativePath}`, { cause });
123
+ }
124
+ throw cause;
125
+ });
126
+ assertContained(root, resolved, relativePath);
127
+ return { absolute: path.join(resolved, ...missing), symbolicLink: missing.length === 0 && existing.isSymbolicLink() };
128
+ } catch (cause) {
129
+ if (cause instanceof ValidationError || cause instanceof RepositoryError) throw cause;
130
+ throw new RepositoryError(`Cannot resolve path: ${relativePath}`, { cause });
131
+ }
132
+ }
133
+
134
+ private async resolveWritablePath(relativePath: string): Promise<string> {
135
+ const resolved = await this.resolvePhysicalPath(relativePath);
136
+ if (resolved.symbolicLink) throw new ValidationError(`Cannot write through a symbolic link: ${relativePath}`);
137
+ return resolved.absolute;
138
+ }
139
+
83
140
  async list(relativeDir = ".", options: ListOptions = {}): Promise<string[]> {
84
141
  const { recursive = false, maxEntries = 2000 } = options;
85
142
  const start = this.resolveInside(relativeDir);
@@ -87,9 +144,10 @@ export class FileService {
87
144
 
88
145
  const walk = async (dir: string): Promise<void> => {
89
146
  if (out.length >= maxEntries) return;
147
+ const resolved = await this.resolvePhysicalPath(this.toRel(dir));
90
148
  let entries: import("node:fs").Dirent[];
91
149
  try {
92
- entries = await readdir(dir, { withFileTypes: true });
150
+ entries = await readdir(resolved.absolute, { withFileTypes: true });
93
151
  } catch (cause) {
94
152
  throw new RepositoryError(`Cannot read directory: ${this.toRel(dir)}`, { cause });
95
153
  }
@@ -107,7 +165,7 @@ export class FileService {
107
165
  }
108
166
 
109
167
  async read(relativePath: string, maxBytes = 512_000): Promise<string> {
110
- const abs = this.resolveInside(relativePath);
168
+ const { absolute: abs } = await this.resolvePhysicalPath(relativePath);
111
169
  const info = await stat(abs).catch((cause) => {
112
170
  throw new RepositoryError(`File not found: ${relativePath}`, { cause });
113
171
  });
@@ -118,10 +176,11 @@ export class FileService {
118
176
  }
119
177
 
120
178
  async write(relativePath: string, content: string): Promise<string> {
121
- const abs = this.resolveInside(relativePath);
179
+ const abs = await this.resolveWritablePath(relativePath);
122
180
  await mkdir(path.dirname(abs), { recursive: true });
123
- await writeFile(abs, content, "utf8");
124
- return this.toRel(abs);
181
+ const target = await this.resolveWritablePath(relativePath);
182
+ await writeFile(target, content, "utf8");
183
+ return this.toRel(this.resolveInside(relativePath));
125
184
  }
126
185
 
127
186
  /** Directories are skipped; an explicit extension filter replaces the text-extension default. */