@jini-ai/platform 0.7.2 → 0.7.3-next.1

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.
Files changed (169) hide show
  1. package/CHANGELOG.md +2 -8
  2. package/README.md +16 -4
  3. package/dist/asset-cache.d.ts +13 -3
  4. package/dist/asset-cache.js +163 -154
  5. package/dist/blob-storage.d.ts +3 -32
  6. package/dist/blob-storage.js +1 -9
  7. package/dist/child-environment.d.ts +0 -16
  8. package/dist/child-environment.js +0 -25
  9. package/dist/command.d.ts +6 -11
  10. package/dist/command.js +8 -54
  11. package/dist/download-lock.d.ts +4 -0
  12. package/dist/download-lock.js +82 -0
  13. package/dist/download-maintenance.d.ts +5 -0
  14. package/dist/download-maintenance.js +82 -0
  15. package/dist/download-state.d.ts +8 -0
  16. package/dist/download-state.js +126 -0
  17. package/dist/download-store.d.ts +22 -0
  18. package/dist/download-store.js +174 -0
  19. package/dist/download-target.d.ts +10 -0
  20. package/dist/download-target.js +102 -0
  21. package/dist/download-transfer.d.ts +12 -0
  22. package/dist/download-transfer.js +174 -0
  23. package/dist/download-types.d.ts +162 -0
  24. package/dist/download-types.js +31 -0
  25. package/dist/download.d.ts +1 -89
  26. package/dist/download.js +8 -738
  27. package/dist/fetch-with-timeout.d.ts +7 -32
  28. package/dist/fetch-with-timeout.js +1 -77
  29. package/dist/fs/app-data-root.d.ts +28 -0
  30. package/dist/fs/app-data-root.js +35 -0
  31. package/dist/fs/atomic-write.js +1 -1
  32. package/dist/fs/boot-identity.d.ts +1 -4
  33. package/dist/fs/directory-delete-guard.d.ts +93 -0
  34. package/dist/fs/directory-delete-guard.js +148 -0
  35. package/dist/fs/directory-registry.js +45 -35
  36. package/dist/fs/directory-relocation.d.ts +82 -0
  37. package/dist/fs/directory-relocation.js +99 -0
  38. package/dist/fs/directory-running-lock.d.ts +1 -1
  39. package/dist/fs/directory-running-lock.js +24 -21
  40. package/dist/fs/directory-sync.js +1 -1
  41. package/dist/fs/directory-user-config.js +30 -3
  42. package/dist/fs/directory-workspace.d.ts +34 -30
  43. package/dist/fs/directory-workspace.js +70 -29
  44. package/dist/fs/durable-json.d.ts +6 -15
  45. package/dist/fs/durable-json.js +38 -35
  46. package/dist/fs/errno.d.ts +12 -3
  47. package/dist/fs/errno.js +5 -3
  48. package/dist/fs/file-lock.d.ts +3 -87
  49. package/dist/fs/file-lock.js +16 -30
  50. package/dist/fs/guarded-reader.js +335 -315
  51. package/dist/fs/index.d.ts +5 -0
  52. package/dist/fs/index.js +5 -0
  53. package/dist/fs/recent-directories.d.ts +46 -0
  54. package/dist/fs/recent-directories.js +68 -0
  55. package/dist/fs/remove-directory-tree.d.ts +20 -0
  56. package/dist/fs/remove-directory-tree.js +28 -0
  57. package/dist/fs/user-data-directories.js +2 -2
  58. package/dist/fs/workspace-directory.js +2 -1
  59. package/dist/fs.d.ts +16 -4
  60. package/dist/fs.js +4 -4
  61. package/dist/home-expansion.d.ts +7 -2
  62. package/dist/home-expansion.js +3 -3
  63. package/dist/http/guarded/client.d.ts +1 -2
  64. package/dist/http/guarded/client.js +2 -1
  65. package/dist/http/guarded/index.d.ts +0 -3
  66. package/dist/http/guarded/node-ports.d.ts +1 -1
  67. package/dist/http/guarded/transport.fetch.d.ts +2 -3
  68. package/dist/http/guarded/transport.fetch.js +64 -58
  69. package/dist/http.d.ts +3 -1
  70. package/dist/http.js +2 -2
  71. package/dist/index.d.ts +10 -11
  72. package/dist/index.js +7 -6
  73. package/dist/mail/activity/activity.d.ts +136 -0
  74. package/dist/mail/activity/activity.js +172 -0
  75. package/dist/mail/activity/ports.d.ts +113 -0
  76. package/dist/mail/activity/suppressions.d.ts +82 -0
  77. package/dist/mail/activity/suppressions.js +119 -0
  78. package/dist/mail/activity/vocabulary.d.ts +10 -0
  79. package/dist/mail/activity/vocabulary.js +8 -0
  80. package/dist/mail/builtin-providers.d.ts +12 -6
  81. package/dist/mail/builtin-providers.js +14 -11
  82. package/dist/mail/delivery-wrapper.js +2 -1
  83. package/dist/mail/email-sender-registry.d.ts +1 -1
  84. package/dist/mail/email-sender-registry.js +1 -1
  85. package/dist/mail/email-template-operations.d.ts +186 -0
  86. package/dist/mail/email-template-operations.js +226 -0
  87. package/dist/mail/email-template.d.ts +120 -0
  88. package/dist/mail/email-template.js +243 -0
  89. package/dist/mail/index.d.ts +4 -0
  90. package/dist/mail/index.js +3 -0
  91. package/dist/mail/prepare-sender-email.d.ts +1 -10
  92. package/dist/mail/prepare-sender-email.js +1 -11
  93. package/dist/mail/resolve-mailer.d.ts +2 -1
  94. package/dist/mail/resolve-mailer.js +5 -2
  95. package/dist/mail/senders.d.ts +0 -1
  96. package/dist/mail/senders.js +0 -1
  97. package/dist/mail/smtp.d.ts +1 -31
  98. package/dist/net/address.d.ts +1 -8
  99. package/dist/net/address.js +1 -18
  100. package/dist/net/index.d.ts +1 -1
  101. package/dist/net/index.js +1 -1
  102. package/dist/net/local-http-probe.js +1 -1
  103. package/dist/net/local-http-request.js +1 -1
  104. package/dist/process-probes.d.ts +36 -0
  105. package/dist/process-probes.js +151 -0
  106. package/dist/process-top-footprint.d.ts +7 -0
  107. package/dist/process-top-footprint.js +30 -0
  108. package/dist/process.d.ts +29 -31
  109. package/dist/process.js +18 -196
  110. package/dist/proxy-env.d.ts +12 -3
  111. package/dist/proxy-env.js +9 -8
  112. package/dist/resource-paths.d.ts +15 -3
  113. package/dist/resource-paths.js +7 -5
  114. package/dist/sandbox-env.d.ts +26 -5
  115. package/dist/sandbox-env.js +7 -7
  116. package/dist/secrets/credential-sets/contracts.d.ts +0 -1
  117. package/dist/secrets/credential-sets/contracts.js +0 -1
  118. package/dist/secrets/credential-sets/index.d.ts +2 -3
  119. package/dist/secrets/credential-sets/index.js +1 -1
  120. package/dist/secrets/credential-sets/provider-matches.d.ts +1 -1
  121. package/dist/secrets/credential-sets/provider-matches.js +1 -1
  122. package/dist/secrets/credential-sets/vault-archive.d.ts +1 -1
  123. package/dist/secrets/credential-sets/vault-archive.js +14 -8
  124. package/dist/secrets/credential-sets/vault.aad.d.ts +1 -1
  125. package/dist/secrets/credential-sets/vault.meta.d.ts +1 -1
  126. package/dist/secrets/credential-sets/vault.meta.js +1 -1
  127. package/dist/secrets/credential-sets/vault.repo.memory.d.ts +1 -1
  128. package/dist/secrets/credential-sets/vault.repo.memory.js +1 -1
  129. package/dist/secrets/credential-sets/vault.reseal-refused.d.ts +23 -0
  130. package/dist/secrets/credential-sets/vault.reseal-refused.js +36 -0
  131. package/dist/secrets/credential-sets/vault.service.d.ts +25 -5
  132. package/dist/secrets/credential-sets/vault.service.js +42 -8
  133. package/dist/secrets/index.d.ts +0 -3
  134. package/dist/secrets/index.js +5 -0
  135. package/dist/secrets/keyring.env.d.ts +1 -1
  136. package/dist/secrets/legacy-owner.d.ts +61 -0
  137. package/dist/secrets/legacy-owner.js +196 -0
  138. package/dist/secrets/root-key/decide.d.ts +89 -0
  139. package/dist/secrets/root-key/decide.js +60 -0
  140. package/dist/secrets/sealer-contract.d.ts +19 -0
  141. package/dist/secrets/sealer-contract.js +37 -0
  142. package/dist/secrets/secret-sealer.aesgcm.d.ts +1 -1
  143. package/dist/secrets/testing.d.ts +1 -0
  144. package/dist/secrets/testing.js +1 -0
  145. package/dist/shell.d.ts +4 -1
  146. package/dist/shell.js +1 -1
  147. package/dist/system.d.ts +6 -0
  148. package/dist/system.js +9 -0
  149. package/dist/terminal.d.ts +11 -96
  150. package/dist/terminal.js +80 -56
  151. package/dist/web/agent-tools.d.ts +107 -0
  152. package/dist/web/agent-tools.js +49 -0
  153. package/dist/web/index.d.ts +1 -0
  154. package/dist/web/index.js +1 -0
  155. package/package.json +38 -12
  156. package/dist/http/guarded/ports.d.ts +0 -56
  157. package/dist/http/guarded/types.d.ts +0 -8
  158. package/dist/http/guarded/types.js +0 -2
  159. package/dist/mail/email-sender.d.ts +0 -109
  160. package/dist/mail/email-sender.js +0 -10
  161. package/dist/net/endpoint-policy.d.ts +0 -39
  162. package/dist/net/endpoint-policy.js +0 -218
  163. package/dist/secrets/credential-sets/aad.d.ts +0 -7
  164. package/dist/secrets/credential-sets/aad.js +0 -7
  165. package/dist/secrets/credential-sets/repo.memory.d.ts +0 -44
  166. package/dist/secrets/credential-sets/repo.memory.js +0 -80
  167. package/dist/secrets/credential-sets/vault.types.d.ts +0 -27
  168. package/dist/secrets/credential-sets/vault.types.js +0 -49
  169. /package/dist/{http/guarded → mail/activity}/ports.js +0 -0
@@ -25,350 +25,370 @@ export function createGuardedFileReader({ rootPath, denyRules, limits, filesyste
25
25
  // Listing exclusions reduce noise; they never grant or deny a known file read. Security comes
26
26
  // from denyRules, applied to both the caller spelling and the effective target.
27
27
  const EXCLUDED_LISTING_DIR_NAMES = excludedListingDirs;
28
- function isDeniedFsFileName(fileName) {
29
- const folded = foldFsNameForDenylist(fileName);
30
- return denyRules.filenamePatterns.some((pattern) => new RegExp(pattern).test(fileName) || new RegExp(pattern).test(folded));
31
- }
32
- function isDeniedFsPathSegment(segmentName) {
33
- return denyRules.segments.has(segmentName.toLowerCase()) || denyRules.segments.has(foldFsNameForDenylist(segmentName));
34
- }
35
- // Default case-insensitive APFS can open LONG S/KELVIN SIGN aliases of denied names that plain
36
- // toLowerCase or non-Unicode /i misses. Windows also ignores trailing dots/spaces and opens
37
- // name::$DATA as name. Compare raw AND folded names: folding may add denials, never remove them,
38
- // and must not change the path actually opened.
39
- function foldFsNameForDenylist(name) {
40
- const streamAt = name.indexOf(":");
41
- const withoutStream = streamAt === -1 ? name : name.slice(0, streamAt);
42
- const withoutTrailing = trimCharsEnd({ text: withoutStream, chars: ". " });
43
- return withoutTrailing.toLowerCase().toUpperCase().toLowerCase();
44
- }
45
- // Split both separator spellings even on a host whose native separator is '/', so deny checks
46
- // remain cross-platform. The guard and reader must resolve the same spelling consistently.
47
- function normalizeFsRelativePath(relativePath) {
48
- const segments = [];
49
- for (const segment of relativePath.split(/[\\/]/)) {
50
- // Empty and "." segments are no-ops; ".." climbs one level; anything else descends.
51
- if (segment === "..")
52
- segments.pop();
53
- if (!NON_DESCENDING_SEGMENTS.has(segment))
54
- segments.push(segment);
55
- }
56
- return segments.join("/");
28
+ const context = { denyRules, fs, descriptorRead, descriptorFlags, existsSync, lstatSync, readdirSync, realpathSync, statSync, MAX_FS_FILE_BYTES, BINARY_SNIFF_BYTES, MAX_LISTED_FILES, MAX_WALK_DEPTH, MAX_WALK_ENTRIES, EXCLUDED_LISTING_DIR_NAMES };
29
+ return {
30
+ resolve: ({ relativePath }) => resolveFsFilePath({ rootPath, relativePath }, context),
31
+ read: ({ relativePath }) => readFsFile({ rootPath, relativePath }, context),
32
+ readBytes: ({ relativePath, maxBytes }) => openFsFileForRead({ rootPath, relativePath, maxBytes }, context),
33
+ list: (_required, optional = {}) => listFsFiles({ rootPath, ...optional }, context),
34
+ isDeniedFileName: ({ fileName }) => isDeniedFsFileName(fileName, context),
35
+ isDeniedPathSegment: ({ segmentName }) => isDeniedFsPathSegment(segmentName, context),
36
+ };
37
+ }
38
+ function isDeniedFsFileName(fileName, context) {
39
+ const { denyRules } = context;
40
+ const folded = foldFsNameForDenylist(fileName);
41
+ return denyRules.filenamePatterns.some((pattern) => new RegExp(pattern).test(fileName) || new RegExp(pattern).test(folded));
42
+ }
43
+ function isDeniedFsPathSegment(segmentName, context) {
44
+ const { denyRules } = context;
45
+ return denyRules.segments.has(segmentName.toLowerCase()) || denyRules.segments.has(foldFsNameForDenylist(segmentName));
46
+ }
47
+ // Default case-insensitive APFS can open LONG S/KELVIN SIGN aliases of denied names that plain
48
+ // toLowerCase or non-Unicode /i misses. Windows also ignores trailing dots/spaces and opens
49
+ // name::$DATA as name. Compare raw AND folded names: folding may add denials, never remove them,
50
+ // and must not change the path actually opened.
51
+ function foldFsNameForDenylist(name) {
52
+ const streamAt = name.indexOf(":");
53
+ const withoutStream = streamAt === -1 ? name : name.slice(0, streamAt);
54
+ const withoutTrailing = trimCharsEnd({ text: withoutStream, chars: ". " });
55
+ return withoutTrailing.toLowerCase().toUpperCase().toLowerCase();
56
+ }
57
+ // Split both separator spellings even on a host whose native separator is '/', so deny checks
58
+ // remain cross-platform. The guard and reader must resolve the same spelling consistently.
59
+ function normalizeFsRelativePath(relativePath) {
60
+ const segments = [];
61
+ for (const segment of relativePath.split(/[\\/]/)) {
62
+ // Empty and "." segments are no-ops; ".." climbs one level; anything else descends.
63
+ if (segment === "..")
64
+ segments.pop();
65
+ if (!NON_DESCENDING_SEGMENTS.has(segment))
66
+ segments.push(segment);
57
67
  }
58
- // A string prefix admits siblings whose names extend the root and ignores traversal. Resolve
59
- // first, then compare path.relative components; symlink containment needs its own check below.
60
- function isWithin(base, target) {
61
- if (base === target)
62
- return true;
63
- const rel = relative(base, target);
64
- return rel !== "" && !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel);
65
- }
66
- // Probe the deepest existing ancestor: a nonexistent descendant can still sit beneath a
67
- // symlink that escapes the root, even when its lexical path passed containment.
68
- // Bound ancestor steps to four times the listing depth, plus the endpoint check, so deeply
69
- // nested missing paths cannot cause unbounded synchronous probes. Unknown containment refuses.
70
- function assertNoSymlinkEscape(base, path, relativePathForError) {
71
- let probe = path;
72
- for (let i = 0; i < MAX_WALK_DEPTH * 4 && !existsSync(probe); i += 1) {
73
- const parent = dirname(probe);
74
- if (parent === probe)
75
- break;
76
- probe = parent;
77
- }
78
- if (!existsSync(probe))
79
- throw new FsFilePathError({ message: `path '${relativePathForError}' containment could not be established within the ancestor traversal limit` });
80
- const realProbe = realpathSync(probe);
81
- if (!isWithin(base, realProbe)) {
82
- throw new FsFilePathError({ message: `path '${relativePathForError}' resolves outside the allowed root through a symbolic link` });
83
- }
68
+ return segments.join("/");
69
+ }
70
+ // A string prefix admits siblings whose names extend the root and ignores traversal. Resolve
71
+ // first, then compare path.relative components; symlink containment needs its own check below.
72
+ function isWithin(base, target) {
73
+ if (base === target)
74
+ return true;
75
+ const rel = relative(base, target);
76
+ return rel !== "" && !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel);
77
+ }
78
+ // Probe the deepest existing ancestor: a nonexistent descendant can still sit beneath a
79
+ // symlink that escapes the root, even when its lexical path passed containment.
80
+ // Bound ancestor steps to four times the listing depth, plus the endpoint check, so deeply
81
+ // nested missing paths cannot cause unbounded synchronous probes. Unknown containment refuses.
82
+ function assertNoSymlinkEscape({ base, path, relativePathForError }, context) {
83
+ const { MAX_WALK_DEPTH, existsSync, realpathSync } = context;
84
+ let probe = path;
85
+ for (let i = 0; i < MAX_WALK_DEPTH * 4 && !existsSync(probe); i += 1) {
86
+ const parent = dirname(probe);
87
+ if (parent === probe)
88
+ break;
89
+ probe = parent;
84
90
  }
85
- function resolveFsFilePath(required) {
86
- const { rootPath, relativePath } = required;
87
- assertWellFormedRelativePath(relativePath);
88
- assertRequestedPathNotDenied(relativePath);
89
- // Canonicalize a symlinked root too, or the ancestor's realpath would compare to a different
90
- // representation and refuse legitimate reads through a linked package/root.
91
- const base = existsSync(rootPath) ? realpathSync(rootPath) : resolve(rootPath);
92
- const target = resolve(base, relativePath);
93
- if (!isWithin(base, target)) {
94
- throw new FsFilePathError({ message: `path '${relativePath}' resolves outside the allowed root` });
95
- }
96
- assertNoSymlinkEscape(base, target, relativePath);
97
- assertEffectiveTargetNotDenied(base, target, relativePath);
98
- return target;
99
- }
100
- // Isolate initial shape refusals so resolve reads as the ordered sequence of containment and
101
- // deny checks, rather than burying that boundary in one long guard block.
102
- function assertWellFormedRelativePath(relativePath) {
103
- if (relativePath.length === 0) {
104
- throw new FsFilePathError({ message: "path is required" });
105
- }
106
- if (relativePath.includes("\0")) {
107
- throw new FsFilePathError({ message: "path must not contain a NUL byte" });
108
- }
109
- if (isAbsolute(relativePath)) {
110
- throw new FsFilePathError({ message: `path '${relativePath}' must be relative to the root, not absolute` });
111
- }
91
+ if (!existsSync(probe))
92
+ throw new FsFilePathError({ message: `path '${relativePathForError}' containment could not be established within the ancestor traversal limit` });
93
+ const realProbe = realpathSync(probe);
94
+ if (!isWithin(base, realProbe)) {
95
+ throw new FsFilePathError({ message: `path '${relativePathForError}' resolves outside the allowed root through a symbolic link` });
112
96
  }
113
- // Refuse denied spellings before filesystem access, regardless of whether they exist. The
114
- // effective-target check is separate because a harmless alias can resolve to a denied file.
115
- function assertRequestedPathNotDenied(relativePath) {
116
- const normalized = normalizeFsRelativePath(relativePath);
117
- const segments = normalized.length === 0 ? [] : normalized.split("/");
118
- for (const segment of segments) {
119
- if (isDeniedFsPathSegment(segment)) {
120
- throw new FsFilePathError({ message: `path '${relativePath}' contains a denied path segment ('${segment}') and cannot be accessed` });
121
- }
122
- }
123
- const leafName = segments.at(-1) ?? "";
124
- if (leafName.length > 0 && isDeniedFsFileName(leafName)) {
125
- throw new FsFilePathError({ message: `path '${relativePath}' matches a denied filename pattern and cannot be accessed` });
126
- }
97
+ }
98
+ function resolveFsFilePath(required, context) {
99
+ const { existsSync, realpathSync } = context;
100
+ const { rootPath, relativePath } = required;
101
+ assertWellFormedRelativePath(relativePath);
102
+ assertRequestedPathNotDenied(relativePath, context);
103
+ // Canonicalize a symlinked root too, or the ancestor's realpath would compare to a different
104
+ // representation and refuse legitimate reads through a linked package/root.
105
+ const base = existsSync(rootPath) ? realpathSync(rootPath) : resolve(rootPath);
106
+ const target = resolve(base, relativePath);
107
+ if (!isWithin(base, target)) {
108
+ throw new FsFilePathError({ message: `path '${relativePath}' resolves outside the allowed root` });
127
109
  }
128
- // public.txt -> .env stays inside the root and passes lexical checks; Node follows it on read.
129
- // Deny the real target as well. existsSync excludes broken/circular links before realpath, and
130
- // the subsequent stat translates their failure into this reader's own refusal class.
131
- function assertEffectiveTargetNotDenied(base, target, relativePath) {
132
- if (!existsSync(target))
133
- return;
134
- const effectiveSegments = relative(base, realpathSync(target)).split(sep);
135
- for (const segment of effectiveSegments) {
136
- if (isDeniedFsPathSegment(segment)) {
137
- throw new FsFilePathError({ message: `path '${relativePath}' resolves to a denied path segment ('${segment}') and cannot be accessed` });
138
- }
139
- }
140
- // A target equal to base yields [""] after split, so check leaf length, not array length.
141
- // split always yields at least one element, so the leaf is always defined.
142
- const effectiveLeaf = effectiveSegments[effectiveSegments.length - 1];
143
- if (effectiveLeaf.length > 0 && isDeniedFsFileName(effectiveLeaf)) {
144
- throw new FsFilePathError({ message: `path '${relativePath}' resolves to a denied filename pattern and cannot be accessed` });
110
+ assertNoSymlinkEscape({ base, path: target, relativePathForError: relativePath }, context);
111
+ assertEffectiveTargetNotDenied({ base, target, relativePath }, context);
112
+ return target;
113
+ }
114
+ // Isolate initial shape refusals so resolve reads as the ordered sequence of containment and
115
+ // deny checks, rather than burying that boundary in one long guard block.
116
+ function assertWellFormedRelativePath(relativePath) {
117
+ if (relativePath.length === 0) {
118
+ throw new FsFilePathError({ message: "path is required" });
119
+ }
120
+ if (relativePath.includes("\0")) {
121
+ throw new FsFilePathError({ message: "path must not contain a NUL byte" });
122
+ }
123
+ if (isAbsolute(relativePath)) {
124
+ throw new FsFilePathError({ message: `path '${relativePath}' must be relative to the root, not absolute` });
125
+ }
126
+ }
127
+ // Refuse denied spellings before filesystem access, regardless of whether they exist. The
128
+ // effective-target check is separate because a harmless alias can resolve to a denied file.
129
+ function assertRequestedPathNotDenied(relativePath, context) {
130
+ const normalized = normalizeFsRelativePath(relativePath);
131
+ const segments = normalized.length === 0 ? [] : normalized.split("/");
132
+ for (const segment of segments) {
133
+ if (isDeniedFsPathSegment(segment, context)) {
134
+ throw new FsFilePathError({ message: `path '${relativePath}' contains a denied path segment ('${segment}') and cannot be accessed` });
145
135
  }
146
136
  }
147
- function visitFsDirEntry(dir, name, depth, base, found, state) {
148
- const full = resolve(dir, name);
149
- // lstat examines the link itself: stat would follow circular links and throw ELOOP before
150
- // the skip. Never enumerate/report links or descend denied directories, so listings do not
151
- // advertise secrets or anything outside the root. Ordinary excluded directories are noise.
152
- const stat = lstatSync(full, { throwIfNoEntry: false });
153
- if (!stat)
154
- return;
155
- if (stat.isSymbolicLink())
156
- return;
157
- if (stat.isDirectory()) {
158
- if (isDeniedFsPathSegment(name) || EXCLUDED_LISTING_DIR_NAMES.has(name))
159
- return;
160
- if (state.paged && depth === state.maxDepth) {
161
- found.push(relative(base, full).split(sep).join("/") + "/");
162
- return;
163
- }
164
- walkFsDir(full, depth + 1, base, found, state);
165
- return;
137
+ const leafName = segments.at(-1) ?? "";
138
+ if (leafName.length > 0 && isDeniedFsFileName(leafName, context)) {
139
+ throw new FsFilePathError({ message: `path '${relativePath}' matches a denied filename pattern and cannot be accessed` });
140
+ }
141
+ }
142
+ // public.txt -> .env stays inside the root and passes lexical checks; Node follows it on read.
143
+ // Deny the real target as well. existsSync excludes broken/circular links before realpath, and
144
+ // the subsequent stat translates their failure into this reader's own refusal class.
145
+ function assertEffectiveTargetNotDenied({ base, target, relativePath }, context) {
146
+ const { existsSync, realpathSync } = context;
147
+ if (!existsSync(target))
148
+ return;
149
+ const effectiveSegments = relative(base, realpathSync(target)).split(sep);
150
+ for (const segment of effectiveSegments) {
151
+ if (isDeniedFsPathSegment(segment, context)) {
152
+ throw new FsFilePathError({ message: `path '${relativePath}' resolves to a denied path segment ('${segment}') and cannot be accessed` });
166
153
  }
167
- if (!stat.isFile())
168
- return;
169
- if (isDeniedFsFileName(name))
170
- return;
171
- found.push(relative(base, full).split(sep).join("/"));
172
154
  }
173
- // Results, entries, and depth are independent limits; keep the decision shared by entry and
174
- // loop checks so adding one limit cannot leave an unbounded arm.
175
- function walkBoundReached(found, state, depth) {
176
- return depth > state.maxDepth || found.length >= state.maxFiles || state.remaining <= 0;
155
+ // A target equal to base yields [""] after split, so check leaf length, not array length.
156
+ // split always yields at least one element, so the leaf is always defined.
157
+ const effectiveLeaf = effectiveSegments[effectiveSegments.length - 1];
158
+ if (effectiveLeaf.length > 0 && isDeniedFsFileName(effectiveLeaf, context)) {
159
+ throw new FsFilePathError({ message: `path '${relativePath}' resolves to a denied filename pattern and cannot be accessed` });
160
+ }
161
+ }
162
+ function visitFsDirEntry({ dir, name, depth, base, found, state }, context) {
163
+ const { lstatSync } = context;
164
+ const full = resolve(dir, name);
165
+ // lstat examines the link itself: stat would follow circular links and throw ELOOP before
166
+ // the skip. Never enumerate/report links or descend denied directories, so listings do not
167
+ // advertise secrets or anything outside the root. Ordinary excluded directories are noise.
168
+ const stat = lstatSync(full, { throwIfNoEntry: false });
169
+ if (!stat)
170
+ return;
171
+ if (stat.isSymbolicLink())
172
+ return;
173
+ if (stat.isDirectory()) {
174
+ visitFsDirectory({ full, name, depth, base, found, state }, context);
175
+ return;
176
+ }
177
+ if (!stat.isFile())
178
+ return;
179
+ if (isDeniedFsFileName(name, context))
180
+ return;
181
+ found.push(relative(base, full).split(sep).join("/"));
182
+ }
183
+ function visitFsDirectory({ full, name, depth, base, found, state }, context) {
184
+ const { EXCLUDED_LISTING_DIR_NAMES } = context;
185
+ if (isDeniedFsPathSegment(name, context) || EXCLUDED_LISTING_DIR_NAMES.has(name))
186
+ return;
187
+ if (state.paged && depth === state.maxDepth) {
188
+ found.push(relative(base, full).split(sep).join("/") + "/");
189
+ return;
177
190
  }
178
- function walkFsDir(dir, depth, base, found, state) {
191
+ walkFsDir({ dir: full, depth: depth + 1, base, found, state }, context);
192
+ }
193
+ // Results, entries, and depth are independent limits; keep the decision shared by entry and
194
+ // loop checks so adding one limit cannot leave an unbounded arm.
195
+ function walkBoundReached(found, state, depth) {
196
+ return depth > state.maxDepth || found.length >= state.maxFiles || state.remaining <= 0;
197
+ }
198
+ function walkFsDir({ dir, depth, base, found, state }, context) {
199
+ const { readdirSync } = context;
200
+ if (walkBoundReached(found, state, depth)) {
201
+ state.truncated = true;
202
+ return;
203
+ }
204
+ const names = readdirSync(dir);
205
+ if (state.paged)
206
+ names.sort();
207
+ for (const name of names) {
208
+ // Recheck per entry: this loop spends traversal budget and adds results. Remaining
209
+ // entries mean a bound must set truncated rather than present a short list as complete.
179
210
  if (walkBoundReached(found, state, depth)) {
180
211
  state.truncated = true;
181
212
  return;
182
213
  }
183
- const names = readdirSync(dir);
184
- if (state.paged)
185
- names.sort();
186
- for (const name of names) {
187
- // Recheck per entry: this loop spends traversal budget and adds results. Remaining
188
- // entries mean a bound must set truncated rather than present a short list as complete.
189
- if (walkBoundReached(found, state, depth)) {
190
- state.truncated = true;
191
- return;
192
- }
193
- state.remaining -= 1;
194
- visitFsDirEntry(dir, name, depth, base, found, state);
195
- }
214
+ state.remaining -= 1;
215
+ visitFsDirEntry({ dir, name, depth, base, found, state }, context);
196
216
  }
197
- /** Walk with existing containment/deny rules, then bound the serialized page independently.
198
- * @complexity At most maxWalkEntries probes; sorting uses O(n log n) time and O(n) paths.
199
- * Directory reads remain synchronous; traversal exhaustion is reported as an unknown remainder.
200
- */
201
- function listFsFiles(required) {
202
- const paged = [required.depth, required.limit, required.cursor, required.maxOutputBytes].some(value => value !== undefined);
203
- const page = listingPageOptions(required, { maxDepth: MAX_WALK_DEPTH, maxFiles: MAX_LISTED_FILES });
204
- const { rootPath } = required;
205
- const relativePath = required.relativePath ?? "";
206
- const pathLabel = relativePath || ".";
207
- const startDir = relativePath.length === 0 ? resolve(rootPath) : resolveFsFilePath({ rootPath, relativePath });
208
- // Freshly provisioned roots/subdirectories may not exist yet; an empty listing is valid.
209
- if (!existsSync(startDir))
210
- return { files: [], truncated: false };
211
- const startStat = statOrFsPathError(startDir, pathLabel);
212
- if (!startStat)
213
- return { files: [], truncated: false };
214
- if (!startStat.isDirectory()) {
215
- throw new FsFilePathError({ message: `path '${pathLabel}' is not a directory` });
216
- }
217
- const base = realpathSync(startDir);
218
- const found = [];
219
- const state = { remaining: MAX_WALK_ENTRIES, truncated: false,
220
- maxDepth: paged ? page.depth - 1 : MAX_WALK_DEPTH,
221
- maxFiles: paged ? MAX_WALK_ENTRIES : MAX_LISTED_FILES, paged };
222
- walkFsDir(base, 0, base, found, state);
223
- // Paths are relative to the requested walk base, so a subdirectory listing can be consumed
224
- // without stripping that subdirectory's prefix a second time.
225
- const listing = { files: found.sort(), truncated: state.truncated };
226
- return paged ? paginateListing(listing, page) : listing;
227
- }
228
- // Circular-link ELOOP and other filesystem exceptions must become the reader's refusal class,
229
- // not escape raw while an ordinary missing path is represented by undefined.
230
- function statOrFsPathError(target, relativePath) {
231
- try {
232
- return statSync(target, { throwIfNoEntry: false });
233
- }
234
- catch (err) {
235
- throw new FsFilePathError({ message: `path '${relativePath}' could not be read: ${errorText(err)}` });
236
- }
217
+ }
218
+ /** Walk with existing containment/deny rules, then bound the serialized page independently.
219
+ * @complexity At most maxWalkEntries probes; sorting uses O(n log n) time and O(n) paths.
220
+ * Directory reads remain synchronous; traversal exhaustion is reported as an unknown remainder.
221
+ */
222
+ function listFsFiles(required, context) {
223
+ const { MAX_WALK_DEPTH, MAX_LISTED_FILES, existsSync, realpathSync, MAX_WALK_ENTRIES } = context;
224
+ const paged = [required.depth, required.limit, required.cursor, required.maxOutputBytes].some(value => value !== undefined);
225
+ const page = listingPageOptions(required, { maxDepth: MAX_WALK_DEPTH, maxFiles: MAX_LISTED_FILES });
226
+ const { rootPath } = required;
227
+ const relativePath = required.relativePath ?? "";
228
+ const pathLabel = relativePath || ".";
229
+ const startDir = relativePath.length === 0 ? resolve(rootPath) : resolveFsFilePath({ rootPath, relativePath }, context);
230
+ // Freshly provisioned roots/subdirectories may not exist yet; an empty listing is valid.
231
+ if (!existsSync(startDir))
232
+ return { files: [], truncated: false };
233
+ const startStat = statOrFsPathError(startDir, pathLabel, context);
234
+ if (!startStat)
235
+ return { files: [], truncated: false };
236
+ if (!startStat.isDirectory()) {
237
+ throw new FsFilePathError({ message: `path '${pathLabel}' is not a directory` });
237
238
  }
238
- // Both read paths refuse missing and non-regular targets with identical wording.
239
- function statRegularFile(target, relativePath) {
240
- const stat = statOrFsPathError(target, relativePath);
241
- if (!stat)
242
- throw new FsFilePathError({ message: `file '${relativePath}' does not exist` });
243
- if (!stat.isFile())
244
- throw new FsFilePathError({ message: `path '${relativePath}' is not a regular file` });
245
- return stat;
246
- }
247
- // A bounded leading-NUL heuristic keeps binary databases/images/archives out of inline UTF-8
248
- // model input without making type sniffing proportional to the full file size.
249
- function looksBinary(buffer) {
250
- const sniffLength = Math.min(buffer.length, BINARY_SNIFF_BYTES);
251
- for (let i = 0; i < sniffLength; i += 1) {
252
- if (buffer[i] === 0)
253
- return true;
254
- }
255
- return false;
239
+ const base = realpathSync(startDir);
240
+ const found = [];
241
+ const state = { remaining: MAX_WALK_ENTRIES, truncated: false,
242
+ maxDepth: paged ? page.depth - 1 : MAX_WALK_DEPTH,
243
+ maxFiles: paged ? MAX_WALK_ENTRIES : MAX_LISTED_FILES, paged };
244
+ walkFsDir({ dir: base, depth: 0, base, found, state }, context);
245
+ // Paths are relative to the requested walk base, so a subdirectory listing can be consumed
246
+ // without stripping that subdirectory's prefix a second time.
247
+ const listing = { files: found.sort(), truncated: state.truncated };
248
+ return paged ? paginateListing(listing, page) : listing;
249
+ }
250
+ // Circular-link ELOOP and other filesystem exceptions must become the reader's refusal class,
251
+ // not escape raw while an ordinary missing path is represented by undefined.
252
+ function statOrFsPathError(target, relativePath, context) {
253
+ const { statSync } = context;
254
+ try {
255
+ return statSync(target, { throwIfNoEntry: false });
256
256
  }
257
- function readFsFile(required) {
258
- const target = resolveFsFilePath(required);
259
- const stat = statRegularFile(target, required.relativePath);
260
- if (stat.size > MAX_FS_FILE_BYTES) {
261
- throw new FsFilePathError({ message: `file '${required.relativePath}' exceeds the ${MAX_FS_FILE_BYTES}-byte readable limit` });
262
- }
263
- const buffer = readBoundedSync(target, required.relativePath);
264
- if (looksBinary(buffer)) {
265
- throw new FsFilePathError({ message: `file '${required.relativePath}' looks like a binary file and cannot be read as text` });
257
+ catch (err) {
258
+ throw new FsFilePathError({ message: `path '${relativePath}' could not be read: ${errorText(err)}` });
259
+ }
260
+ }
261
+ // Both read paths refuse missing and non-regular targets with identical wording.
262
+ function statRegularFile(target, relativePath, context) {
263
+ const stat = statOrFsPathError(target, relativePath, context);
264
+ if (!stat)
265
+ throw new FsFilePathError({ message: `file '${relativePath}' does not exist` });
266
+ if (!stat.isFile())
267
+ throw new FsFilePathError({ message: `path '${relativePath}' is not a regular file` });
268
+ return stat;
269
+ }
270
+ // A bounded leading-NUL heuristic keeps binary databases/images/archives out of inline UTF-8
271
+ // model input without making type sniffing proportional to the full file size.
272
+ function looksBinary(buffer, context) {
273
+ const { BINARY_SNIFF_BYTES } = context;
274
+ const sniffLength = Math.min(buffer.length, BINARY_SNIFF_BYTES);
275
+ for (let i = 0; i < sniffLength; i += 1) {
276
+ if (buffer[i] === 0)
277
+ return true;
278
+ }
279
+ return false;
280
+ }
281
+ function readFsFile(required, context) {
282
+ const { MAX_FS_FILE_BYTES } = context;
283
+ const target = resolveFsFilePath(required, context);
284
+ const stat = statRegularFile(target, required.relativePath, context);
285
+ if (stat.size > MAX_FS_FILE_BYTES) {
286
+ throw new FsFilePathError({ message: `file '${required.relativePath}' exceeds the ${MAX_FS_FILE_BYTES}-byte readable limit` });
287
+ }
288
+ const buffer = readBoundedSync(target, required.relativePath, context);
289
+ if (looksBinary(buffer, context)) {
290
+ throw new FsFilePathError({ message: `file '${required.relativePath}' looks like a binary file and cannot be read as text` });
291
+ }
292
+ return { content: buffer.toString("utf8"), bytes: buffer.byteLength };
293
+ }
294
+ // Read one byte past the cap so a file that grew after stat is refused rather than clipped.
295
+ function readBoundedSync(target, relativePath, context) {
296
+ const { descriptorFlags, fs, MAX_FS_FILE_BYTES } = context;
297
+ const { fd, maxBytes } = descriptorFlags === undefined
298
+ ? { fd: fs.openSync(target, "r"), maxBytes: MAX_FS_FILE_BYTES }
299
+ : openValidatedDescriptor({ target, relativePath, maxBytes: MAX_FS_FILE_BYTES }, context);
300
+ try {
301
+ const bounded = Buffer.alloc(maxBytes + 1);
302
+ let count = 0;
303
+ while (count < bounded.length) {
304
+ const read = fs.readSync(fd, bounded, count, bounded.length - count, null);
305
+ if (read === 0)
306
+ break;
307
+ count += read;
266
308
  }
267
- return { content: buffer.toString("utf8"), bytes: buffer.byteLength };
309
+ if (count > maxBytes)
310
+ throw new FsFilePathError({ message: `file '${relativePath}' exceeds the ${maxBytes}-byte readable limit` });
311
+ return bounded.subarray(0, count);
312
+ }
313
+ finally {
314
+ fs.closeSync(fd);
315
+ }
316
+ }
317
+ /** Owns the descriptor until validated; every refusal closes it before propagating. */
318
+ function openValidatedDescriptor({ target, relativePath, maxBytes }, context) {
319
+ const { fs, descriptorRead } = context;
320
+ const fd = openNoFollow({ target, relativePath }, context);
321
+ try {
322
+ const stat = fs.fstatSync(fd);
323
+ assertDescriptorStat({ stat, relativePath, maxBytes }, descriptorRead);
324
+ return { fd, maxBytes: descriptorRead?.rejectGrowth ? Math.min(maxBytes, stat.size) : maxBytes };
268
325
  }
269
- // Read one byte past the cap so a file that grew after stat is refused rather than clipped.
270
- function readBoundedSync(target, relativePath) {
271
- const { fd, maxBytes } = descriptorFlags === undefined
272
- ? { fd: fs.openSync(target, "r"), maxBytes: MAX_FS_FILE_BYTES }
273
- : openValidatedDescriptor({ target, relativePath, maxBytes: MAX_FS_FILE_BYTES });
326
+ catch (error) {
274
327
  try {
275
- const bounded = Buffer.alloc(maxBytes + 1);
276
- let count = 0;
277
- while (count < bounded.length) {
278
- const read = fs.readSync(fd, bounded, count, bounded.length - count, null);
279
- if (read === 0)
280
- break;
281
- count += read;
282
- }
283
- if (count > maxBytes)
284
- throw new FsFilePathError({ message: `file '${relativePath}' exceeds the ${maxBytes}-byte readable limit` });
285
- return bounded.subarray(0, count);
286
- }
287
- finally {
288
328
  fs.closeSync(fd);
289
329
  }
330
+ catch { /* Preserve the validation error. */ }
331
+ throw error;
290
332
  }
291
- /** Owns the descriptor until validated; every refusal closes it before propagating. */
292
- function openValidatedDescriptor({ target, relativePath, maxBytes }) {
293
- const fd = openNoFollow({ target, relativePath });
294
- try {
295
- const stat = fs.fstatSync(fd);
296
- assertDescriptorStat({ stat, relativePath, maxBytes }, descriptorRead);
297
- return { fd, maxBytes: descriptorRead?.rejectGrowth ? Math.min(maxBytes, stat.size) : maxBytes };
298
- }
299
- catch (error) {
300
- try {
301
- fs.closeSync(fd);
302
- }
303
- catch { /* Preserve the validation error. */ }
304
- throw error;
305
- }
333
+ }
334
+ // A stat-only size check can be bypassed by a growing file: bound the stream independently and
335
+ // reject rather than return a clipped image/video. Destroy the stream on success or failure.
336
+ async function openFsFileForRead(required, context) {
337
+ const { relativePath, maxBytes } = required;
338
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
339
+ throw new FsFilePathError({ message: "maxBytes must be a positive safe integer" });
306
340
  }
307
- // A stat-only size check can be bypassed by a growing file: bound the stream independently and
308
- // reject rather than return a clipped image/video. Destroy the stream on success or failure.
309
- async function openFsFileForRead(required) {
310
- const { relativePath, maxBytes } = required;
311
- if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
312
- throw new FsFilePathError({ message: "maxBytes must be a positive safe integer" });
313
- }
314
- const target = resolveFsFilePath(required);
315
- const stat = statRegularFile(target, relativePath);
316
- if (stat.size > maxBytes) {
317
- throw new FsFilePathError({ message: `file '${relativePath}' is ${stat.size} bytes and exceeds the ${maxBytes}-byte import limit` });
318
- }
319
- return readBoundedStream(target, { relativePath, maxBytes });
341
+ const target = resolveFsFilePath(required, context);
342
+ const stat = statRegularFile(target, relativePath, context);
343
+ if (stat.size > maxBytes) {
344
+ throw new FsFilePathError({ message: `file '${relativePath}' is ${stat.size} bytes and exceeds the ${maxBytes}-byte import limit` });
320
345
  }
321
- async function readBoundedStream(target, { relativePath, maxBytes }) {
322
- const opened = createBoundedStream({ target, relativePath, maxBytes });
323
- const { stream } = opened;
324
- try {
325
- // Own refusals pass through; any other stream failure becomes this reader's refusal class.
326
- return await collectBoundedChunks(stream, { relativePath, maxBytes: opened.maxBytes }).catch((error) => Promise.reject(error instanceof FsFilePathError
327
- ? error
328
- : new FsFilePathError({ message: `path '${relativePath}' could not be read: ${errorText(error)}` })));
329
- }
330
- finally {
331
- stream.destroy();
332
- }
346
+ return readBoundedStream(target, { relativePath, maxBytes }, context);
347
+ }
348
+ async function readBoundedStream(target, { relativePath, maxBytes }, context) {
349
+ const opened = createBoundedStream({ target, relativePath, maxBytes }, context);
350
+ const { stream } = opened;
351
+ try {
352
+ // Own refusals pass through; any other stream failure becomes this reader's refusal class.
353
+ return await collectBoundedChunks(stream, { relativePath, maxBytes: opened.maxBytes }).catch((error) => Promise.reject(error instanceof FsFilePathError
354
+ ? error
355
+ : new FsFilePathError({ message: `path '${relativePath}' could not be read: ${errorText(error)}` })));
333
356
  }
334
- /** O_NOFOLLOW refusals (ELOOP) and other open failures carry absolute host paths; surface only
335
- * the caller's relative path, like every other refusal from this reader. */
336
- function openNoFollow({ target, relativePath }) {
337
- try {
338
- return fs.openSync(target, descriptorFlags);
339
- }
340
- catch {
341
- throw new FsFilePathError({ message: `path '${relativePath}' is a symbolic link or could not be opened` });
342
- }
357
+ finally {
358
+ stream.destroy();
359
+ }
360
+ }
361
+ /** O_NOFOLLOW refusals (ELOOP) and other open failures carry absolute host paths; surface only
362
+ * the caller's relative path, like every other refusal from this reader. */
363
+ function openNoFollow({ target, relativePath }, context) {
364
+ const { fs, descriptorFlags } = context;
365
+ try {
366
+ return fs.openSync(target, descriptorFlags);
367
+ }
368
+ catch {
369
+ throw new FsFilePathError({ message: `path '${relativePath}' is a symbolic link or could not be opened` });
343
370
  }
344
- /** Transfer ownership to the stream only after construction; it alone closes on end/error. */
345
- function createBoundedStream({ target, relativePath, maxBytes }) {
346
- const highWaterMark = Math.min(64 * 1024, maxBytes + 1);
347
- if (descriptorFlags === undefined)
348
- return { stream: fs.createReadStream(target, { highWaterMark }), maxBytes };
349
- const opened = openValidatedDescriptor({ target, relativePath, maxBytes });
371
+ }
372
+ /** Transfer ownership to the stream only after construction; it alone closes on end/error. */
373
+ function createBoundedStream({ target, relativePath, maxBytes }, context) {
374
+ const { descriptorFlags, fs } = context;
375
+ const highWaterMark = Math.min(64 * 1024, maxBytes + 1);
376
+ if (descriptorFlags === undefined)
377
+ return { stream: fs.createReadStream(target, { highWaterMark }), maxBytes };
378
+ const opened = openValidatedDescriptor({ target, relativePath, maxBytes }, context);
379
+ try {
380
+ return {
381
+ stream: fs.createReadStream(target, { fd: opened.fd, autoClose: true, highWaterMark: Math.min(highWaterMark, opened.maxBytes + 1) }),
382
+ maxBytes: opened.maxBytes,
383
+ };
384
+ }
385
+ catch (error) {
350
386
  try {
351
- return {
352
- stream: fs.createReadStream(target, { fd: opened.fd, autoClose: true, highWaterMark: Math.min(highWaterMark, opened.maxBytes + 1) }),
353
- maxBytes: opened.maxBytes,
354
- };
355
- }
356
- catch (error) {
357
- try {
358
- fs.closeSync(opened.fd);
359
- }
360
- catch { /* Preserve the construction error. */ }
361
- throw error;
387
+ fs.closeSync(opened.fd);
362
388
  }
389
+ catch { /* Preserve the construction error. */ }
390
+ throw error;
363
391
  }
364
- return {
365
- resolve: ({ relativePath }) => resolveFsFilePath({ rootPath, relativePath }),
366
- read: ({ relativePath }) => readFsFile({ rootPath, relativePath }),
367
- readBytes: ({ relativePath, maxBytes }) => openFsFileForRead({ rootPath, relativePath, maxBytes }),
368
- list: (_required, optional = {}) => listFsFiles({ rootPath, ...optional }),
369
- isDeniedFileName: ({ fileName }) => isDeniedFsFileName(fileName),
370
- isDeniedPathSegment: ({ segmentName }) => isDeniedFsPathSegment(segmentName),
371
- };
372
392
  }
373
393
  /** Validate page controls even for raw callers bypassing a tool schema; no filesystem effects. */
374
394
  function listingPageOptions(input, { maxDepth, maxFiles }) {