@j0hanz/filesystem-mcp 2.2.0 → 2.3.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.
Files changed (94) hide show
  1. package/README.md +40 -27
  2. package/dist/cli-help.d.ts.map +1 -1
  3. package/dist/cli-help.js +10 -2
  4. package/dist/cli-help.js.map +1 -1
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +10 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/core/concurrency.d.ts.map +1 -1
  9. package/dist/core/concurrency.js +21 -6
  10. package/dist/core/concurrency.js.map +1 -1
  11. package/dist/core/config.d.ts +2 -0
  12. package/dist/core/config.d.ts.map +1 -1
  13. package/dist/core/config.js.map +1 -1
  14. package/dist/core/errors.d.ts +6 -9
  15. package/dist/core/errors.d.ts.map +1 -1
  16. package/dist/core/errors.js +58 -102
  17. package/dist/core/errors.js.map +1 -1
  18. package/dist/core/file-uri.d.ts +5 -1
  19. package/dist/core/file-uri.d.ts.map +1 -1
  20. package/dist/core/file-uri.js +6 -2
  21. package/dist/core/file-uri.js.map +1 -1
  22. package/dist/core/fmt.d.ts +0 -1
  23. package/dist/core/fmt.d.ts.map +1 -1
  24. package/dist/core/fmt.js +0 -1
  25. package/dist/core/fmt.js.map +1 -1
  26. package/dist/core/fs.d.ts +31 -1
  27. package/dist/core/fs.d.ts.map +1 -1
  28. package/dist/core/fs.js +142 -2
  29. package/dist/core/fs.js.map +1 -1
  30. package/dist/core/glob.d.ts.map +1 -1
  31. package/dist/core/glob.js +3 -8
  32. package/dist/core/glob.js.map +1 -1
  33. package/dist/core/input-required.d.ts +8 -17
  34. package/dist/core/input-required.d.ts.map +1 -1
  35. package/dist/core/input-required.js +32 -47
  36. package/dist/core/input-required.js.map +1 -1
  37. package/dist/core/observability.d.ts +9 -0
  38. package/dist/core/observability.d.ts.map +1 -1
  39. package/dist/core/observability.js +11 -0
  40. package/dist/core/observability.js.map +1 -1
  41. package/dist/core/page-store.d.ts +4 -3
  42. package/dist/core/page-store.d.ts.map +1 -1
  43. package/dist/core/page-store.js +4 -3
  44. package/dist/core/page-store.js.map +1 -1
  45. package/dist/core/search.d.ts +5 -0
  46. package/dist/core/search.d.ts.map +1 -1
  47. package/dist/core/search.js +18 -19
  48. package/dist/core/search.js.map +1 -1
  49. package/dist/core/sensitive.d.ts +4 -2
  50. package/dist/core/sensitive.d.ts.map +1 -1
  51. package/dist/core/sensitive.js +261 -43
  52. package/dist/core/sensitive.js.map +1 -1
  53. package/dist/core/watcher-registry.d.ts.map +1 -1
  54. package/dist/core/watcher-registry.js +5 -1
  55. package/dist/core/watcher-registry.js.map +1 -1
  56. package/dist/resources.d.ts.map +1 -1
  57. package/dist/resources.js +13 -4
  58. package/dist/resources.js.map +1 -1
  59. package/dist/server.d.ts.map +1 -1
  60. package/dist/server.js +7 -2
  61. package/dist/server.js.map +1 -1
  62. package/dist/tools/create.d.ts.map +1 -1
  63. package/dist/tools/create.js +163 -14
  64. package/dist/tools/create.js.map +1 -1
  65. package/dist/tools/define.d.ts +6 -1
  66. package/dist/tools/define.d.ts.map +1 -1
  67. package/dist/tools/define.js +25 -5
  68. package/dist/tools/define.js.map +1 -1
  69. package/dist/tools/delete.d.ts.map +1 -1
  70. package/dist/tools/delete.js +8 -11
  71. package/dist/tools/delete.js.map +1 -1
  72. package/dist/tools/edit.d.ts.map +1 -1
  73. package/dist/tools/edit.js +77 -69
  74. package/dist/tools/edit.js.map +1 -1
  75. package/dist/tools/index.d.ts +1 -0
  76. package/dist/tools/index.d.ts.map +1 -1
  77. package/dist/tools/index.js +1 -0
  78. package/dist/tools/index.js.map +1 -1
  79. package/dist/tools/move.d.ts.map +1 -1
  80. package/dist/tools/move.js +14 -33
  81. package/dist/tools/move.js.map +1 -1
  82. package/dist/tools/patch.js +3 -3
  83. package/dist/tools/patch.js.map +1 -1
  84. package/dist/tools/search-text.d.ts.map +1 -1
  85. package/dist/tools/search-text.js +64 -1
  86. package/dist/tools/search-text.js.map +1 -1
  87. package/dist/transport/http.d.ts.map +1 -1
  88. package/dist/transport/http.js +5 -1
  89. package/dist/transport/http.js.map +1 -1
  90. package/dist/transport/stdio.d.ts +1 -0
  91. package/dist/transport/stdio.d.ts.map +1 -1
  92. package/dist/transport/stdio.js +1 -0
  93. package/dist/transport/stdio.js.map +1 -1
  94. package/package.json +6 -9
@@ -1 +1 @@
1
- {"version":3,"file":"sensitive.d.ts","sourceRoot":"","sources":["../../src/core/sensitive.ts"],"names":[],"mappings":"AAiJA,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;gBAElC,QAAQ,GAAE,SAAS,MAAM,EAA6B;IAIlE,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;CAWvC"}
1
+ {"version":3,"file":"sensitive.d.ts","sourceRoot":"","sources":["../../src/core/sensitive.ts"],"names":[],"mappings":"AAoUA,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;IAC9C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAqB;gBAK/B,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,EAAE,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE;IAanE,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;CAcvC"}
@@ -8,27 +8,178 @@ import { normalize, posix, sep } from 'node:path';
8
8
  import { cli } from './config.js';
9
9
  import { IS_WINDOWS, isAlpha, parseTrueEnvFlag, toPosixPath } from './primitives.js';
10
10
  const CHAR_COLON = 58;
11
- const CHAR_FORWARD_SLASH = 47;
12
11
  function normalizeForMatch(input) {
13
12
  // Always lowercase for case-insensitive denylist matching on all platforms.
14
- return toPosixPath(normalize(input)).toLowerCase();
13
+ // normalize() preserves the double leading slash of UNC paths
14
+ // (//server/share/...) on Windows; collapse it to one so the compiled
15
+ // patterns — which carry no leading slash — still match their segments.
16
+ return toPosixPath(normalize(input)).toLowerCase().replace(/^\/+/u, '/');
15
17
  }
16
- function isWindowsAbsolutePosixPath(normalizedPattern) {
17
- return (normalizedPattern.length >= 3 &&
18
- normalizedPattern.charCodeAt(1) === CHAR_COLON &&
19
- normalizedPattern.charCodeAt(2) === CHAR_FORWARD_SLASH &&
20
- isAlpha(normalizedPattern.charCodeAt(0)));
18
+ // posix.matchesGlob runs with dot:false semantics and does not honor a dot
19
+ // option at all (verified on Node 24): '*' and '**' never match dot-leading
20
+ // path segments, so a deny of `secrets/**` silently let `secrets/.env`
21
+ // through — fail-open against exactly the hidden files this list exists to
22
+ // guard. Compile our own matcher instead. Supported metacharacters: '*'
23
+ // (any run within a segment), '**' (any run of whole segments), '?' (one
24
+ // char), '[...]' classes, and '{a,b}' alternation; everything else is
25
+ // literal, and dot-leading segments match like any other.
26
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
27
+ // Character classes can carry '{', '}' and ',' as members, so every scanner
28
+ // below must skip a class's interior. classEnd returns the index of the ']'
29
+ // closing the class opened at openIdx, or -1 when unclosed (then '[' is a
30
+ // literal, matching globToRegExp's fallback). A ']' right after '[' or the
31
+ // '!' negation is a literal member, per glob syntax.
32
+ function classEnd(glob, openIdx) {
33
+ let i = openIdx + 1;
34
+ if (glob[i] === '!')
35
+ i++;
36
+ if (glob[i] === ']')
37
+ i++;
38
+ while (i < glob.length && glob[i] !== ']')
39
+ i++;
40
+ return i < glob.length ? i : -1;
21
41
  }
22
- function compilePatternGlobs(normalizedPattern) {
23
- const globs = new Set([normalizedPattern]);
24
- const isRooted = normalizedPattern.startsWith('**/') || isWindowsAbsolutePosixPath(normalizedPattern);
25
- if (!isRooted) {
26
- const withoutRoot = normalizedPattern.replace(/^\/+/, '');
27
- if (withoutRoot) {
28
- globs.add(`**/${withoutRoot}`);
42
+ function expandBraces(glob) {
43
+ // First '{' outside any [...] class.
44
+ let open = -1;
45
+ for (let i = 0; i < glob.length; i++) {
46
+ const char = glob[i] ?? '';
47
+ if (char === '[') {
48
+ const end = classEnd(glob, i);
49
+ if (end !== -1)
50
+ i = end;
51
+ }
52
+ else if (char === '{') {
53
+ open = i;
54
+ break;
55
+ }
56
+ }
57
+ if (open === -1)
58
+ return [glob];
59
+ // Pair the outer '{' with ITS matching '}' — indexOf would grab the inner
60
+ // group's closer and produce garbage like 'data/x}/secret'. Then split the
61
+ // body on depth-0 commas so nested groups stay intact for the recursion.
62
+ let depth = 0;
63
+ let close = -1;
64
+ for (let i = open; i < glob.length; i++) {
65
+ const char = glob[i] ?? '';
66
+ if (char === '[') {
67
+ const end = classEnd(glob, i);
68
+ if (end !== -1) {
69
+ i = end;
70
+ continue;
71
+ }
72
+ }
73
+ if (char === '{')
74
+ depth++;
75
+ else if (char === '}') {
76
+ depth--;
77
+ if (depth === 0) {
78
+ close = i;
79
+ break;
80
+ }
81
+ }
82
+ }
83
+ if (close === -1)
84
+ return [glob];
85
+ const prefix = glob.slice(0, open);
86
+ const suffix = glob.slice(close + 1);
87
+ const body = glob.slice(open + 1, close);
88
+ const parts = [];
89
+ let start = 0;
90
+ depth = 0;
91
+ for (let i = 0; i < body.length; i++) {
92
+ const char = body[i] ?? '';
93
+ if (char === '[') {
94
+ const end = classEnd(body, i);
95
+ if (end !== -1) {
96
+ i = end;
97
+ continue;
98
+ }
99
+ }
100
+ if (char === '{')
101
+ depth++;
102
+ else if (char === '}')
103
+ depth--;
104
+ else if (char === ',' && depth === 0) {
105
+ parts.push(body.slice(start, i));
106
+ start = i + 1;
29
107
  }
30
108
  }
31
- return Array.from(globs);
109
+ parts.push(body.slice(start));
110
+ return parts.flatMap((part) => expandBraces(`${prefix}${part}${suffix}`));
111
+ }
112
+ function globToRegExp(glob) {
113
+ const segments = glob.split('/');
114
+ let source = '';
115
+ for (let i = 0; i < segments.length; i++) {
116
+ const segment = segments[i] ?? '';
117
+ const last = i === segments.length - 1;
118
+ if (segment === '**') {
119
+ source += last ? '(?:.*)?' : '(?:[^/]+/)*';
120
+ continue;
121
+ }
122
+ for (let j = 0; j < segment.length; j++) {
123
+ const char = segment[j] ?? '';
124
+ if (char === '*') {
125
+ while (segment[j + 1] === '*')
126
+ j++;
127
+ source += '[^/]*';
128
+ }
129
+ else if (char === '?') {
130
+ source += '[^/]';
131
+ }
132
+ else if (char === '[') {
133
+ // Same classEnd rule the scanners use: a ']' right after '[' (or
134
+ // after the '!' negation) is a literal member, not the closer.
135
+ const close = classEnd(segment, j);
136
+ if (close !== -1) {
137
+ // Pass the class through, flipping glob '!' negation to '^' and
138
+ // escaping backslashes so no body can make new RegExp throw. A
139
+ // leading ']' must be escaped or the 'u' flag parses '[]a]' as an
140
+ // empty class followed by stray literals; a leading '^' is a
141
+ // literal member (glob negation is '!' only), unescaped it would
142
+ // negate the class and relieve more than the operator named.
143
+ let body = segment.slice(j + 1, close).replace(/\\/gu, '\\\\');
144
+ const negated = body.startsWith('!');
145
+ if (negated)
146
+ body = body.slice(1);
147
+ if (body.startsWith(']') || body.startsWith('^'))
148
+ body = `\\${body}`;
149
+ source += `[${negated ? '^' : ''}${body}]`;
150
+ j = close;
151
+ }
152
+ else {
153
+ source += escapeRegExp(char);
154
+ }
155
+ }
156
+ else {
157
+ source += escapeRegExp(char);
158
+ }
159
+ }
160
+ if (!last)
161
+ source += '/';
162
+ }
163
+ // Candidates are absolute paths but patterns carry no leading '/', so the
164
+ // anchor optionally eats the root slash — `**/` then reaches from any
165
+ // parent, exactly as matchesGlob's globstar did. '$' is strict in
166
+ // JavaScript (it matches end-of-input only, unlike PCRE's, which also
167
+ // matches before a final newline), so an exact-name pattern can never
168
+ // match a '.env\n' lookalike. The 's' flag makes the terminal-`**` `.`
169
+ // match newlines too: filenames can contain them, and a deny ending in
170
+ // '/**' must not fail open on 'secrets/plan\nnotes'.
171
+ return new RegExp(`^/?${source}$`, 'su');
172
+ }
173
+ function compilePatternGlobs(normalizedPattern) {
174
+ // A leading '/' (POSIX-absolute) is rooted like a Windows drive path:
175
+ // aliasing '/abs/secret' as '**/abs/secret' would also match
176
+ // 'other/abs/secret', and on the allow side that is over-relief. The
177
+ // drive-letter regex is safe on [a-z] because normalizeForMatch lowercased.
178
+ const isRooted = normalizedPattern.startsWith('/') ||
179
+ normalizedPattern.startsWith('**/') ||
180
+ /^[a-z]:\//u.test(normalizedPattern);
181
+ const withoutRoot = isRooted ? '' : normalizedPattern.replace(/^\/+/, '');
182
+ return withoutRoot ? [normalizedPattern, `**/${withoutRoot}`] : [normalizedPattern];
32
183
  }
33
184
  function toPatternSet(patterns) {
34
185
  const pathGlobs = new Set();
@@ -38,8 +189,11 @@ function toPatternSet(patterns) {
38
189
  const normalized = normalizeForMatch(pattern);
39
190
  const matchesPath = normalized.includes('/');
40
191
  const target = matchesPath ? pathGlobs : nameGlobs;
41
- for (const glob of matchesPath ? compilePatternGlobs(normalized) : [normalized]) {
42
- target.add(glob);
192
+ const globs = matchesPath ? compilePatternGlobs(normalized) : [normalized];
193
+ for (const glob of globs) {
194
+ for (const expanded of expandBraces(glob)) {
195
+ target.add(globToRegExp(expanded));
196
+ }
43
197
  }
44
198
  }
45
199
  return {
@@ -48,13 +202,7 @@ function toPatternSet(patterns) {
48
202
  };
49
203
  }
50
204
  function matchesAnyGlob(globs, candidate) {
51
- if (globs.length === 0)
52
- return false;
53
- for (const glob of globs) {
54
- if (posix.matchesGlob(candidate, glob))
55
- return true;
56
- }
57
- return false;
205
+ return globs.some((glob) => glob.test(candidate));
58
206
  }
59
207
  // Strip NTFS alternate-data-stream suffixes (the ":stream" after a segment)
60
208
  // before denylist matching, so `.env:secret` is caught as `.env`. Preserves the
@@ -99,36 +247,106 @@ const DEFAULT_SENSITIVE_PATTERNS = [
99
247
  '*id_rsa*',
100
248
  '*id_dsa*',
101
249
  ];
102
- function buildSensitivePatterns() {
250
+ // Built-ins and operator-supplied deny entries live in separate tiers because
251
+ // they answer to different relief switches: an allow entry (FS_ALLOWLIST /
252
+ // --allow) can lift a built-in hit, but never an explicit deny.
253
+ // Split an env pattern list on commas and newlines at brace depth 0 only and
254
+ // outside any [...] class, so documented syntax like '*.{pem,key}' or
255
+ // 'x[1,2].env' survives as one pattern instead of tearing apart.
256
+ function splitPatternList(value) {
257
+ const naive = () => value
258
+ .split(/,|\n/u)
259
+ .map((t) => t.trim())
260
+ .filter((t) => t.length > 0);
261
+ const parts = [];
262
+ let depth = 0;
263
+ let start = 0;
264
+ let unbalanced = false;
265
+ for (let i = 0; i < value.length; i++) {
266
+ const char = value[i] ?? '';
267
+ if (char === '[') {
268
+ const end = classEnd(value, i);
269
+ if (end !== -1) {
270
+ i = end;
271
+ continue;
272
+ }
273
+ }
274
+ if (char === '{')
275
+ depth++;
276
+ else if (char === '}') {
277
+ if (depth === 0)
278
+ unbalanced = true;
279
+ else
280
+ depth--;
281
+ }
282
+ else if (depth === 0 && (char === ',' || char === '\n')) {
283
+ parts.push(value.slice(start, i));
284
+ start = i + 1;
285
+ }
286
+ }
287
+ // An unbalanced brace would swallow every separator behind it into one
288
+ // bogus literal pattern and silently drop the real entries — '{bad,
289
+ // secrets/**' must not lose 'secrets/**'. A typo'd brace costs the brace
290
+ // pattern only: fall back to the naive split.
291
+ if (unbalanced || depth !== 0)
292
+ return naive();
293
+ parts.push(value.slice(start));
294
+ return parts.map((t) => t.trim()).filter((t) => t.length > 0);
295
+ }
296
+ function buildDenyTiers() {
103
297
  const allowSensitive = cli.allowSensitive ?? parseTrueEnvFlag(process.env['FS_ALLOW_SENSITIVE'], 'FS_ALLOW_SENSITIVE');
104
- const envValue = process.env['FS_DENYLIST'];
105
- const envDenylist = envValue
106
- ? envValue
107
- .split(/[,\n]/u)
108
- .map((t) => t.trim())
109
- .filter((t) => t.length > 0)
298
+ const envDenylist = process.env['FS_DENYLIST']
299
+ ? splitPatternList(process.env['FS_DENYLIST'])
110
300
  : [];
111
301
  const flagDenylist = cli.denyPatterns ?? [];
112
302
  // FS_ALLOW_SENSITIVE suppresses built-ins only; deny entries (env and --deny)
113
303
  // always apply. Set-dedupe so a pattern in both sources matches once.
114
- return [
115
- ...(allowSensitive ? [] : DEFAULT_SENSITIVE_PATTERNS),
116
- ...new Set([...envDenylist, ...flagDenylist]),
117
- ];
304
+ return {
305
+ builtin: allowSensitive ? [] : DEFAULT_SENSITIVE_PATTERNS,
306
+ operator: [...new Set([...envDenylist, ...flagDenylist])],
307
+ };
118
308
  }
309
+ function buildAllowPatterns() {
310
+ const envAllowlist = process.env['FS_ALLOWLIST']
311
+ ? splitPatternList(process.env['FS_ALLOWLIST'])
312
+ : [];
313
+ const flagAllowlist = cli.allowPatterns ?? [];
314
+ return [...new Set([...envAllowlist, ...flagAllowlist])];
315
+ }
316
+ const EMPTY_PATTERN_SET = { pathGlobs: [], nameGlobs: [] };
119
317
  export class SensitiveMatcher {
120
- patterns;
121
- constructor(patterns = buildSensitivePatterns()) {
122
- this.patterns = toPatternSet(patterns);
318
+ builtin;
319
+ operator;
320
+ allow;
321
+ // An explicit pattern list (tests, custom guards) is one relievable tier;
322
+ // the default construction splits built-ins from operator-supplied
323
+ // FS_DENYLIST/--deny entries, which allow entries can never lift.
324
+ constructor(patterns, allow) {
325
+ if (patterns !== undefined || allow !== undefined) {
326
+ this.builtin = toPatternSet(patterns ?? []);
327
+ this.operator = EMPTY_PATTERN_SET;
328
+ this.allow = toPatternSet(allow ?? []);
329
+ }
330
+ else {
331
+ const tiers = buildDenyTiers();
332
+ this.builtin = toPatternSet(tiers.builtin);
333
+ this.operator = toPatternSet(tiers.operator);
334
+ this.allow = toPatternSet(buildAllowPatterns());
335
+ }
123
336
  }
124
337
  isSensitive(filePath) {
125
- if (this.patterns.pathGlobs.length === 0 && this.patterns.nameGlobs.length === 0) {
126
- return false;
127
- }
128
338
  const pathToCheck = IS_WINDOWS ? stripAlternateDataStreams(filePath) : filePath;
129
339
  const normalizedPath = normalizeForMatch(pathToCheck);
130
- return (matchesAnyGlob(this.patterns.pathGlobs, normalizedPath) ||
131
- matchesAnyGlob(this.patterns.nameGlobs, posix.basename(normalizedPath)));
340
+ const name = posix.basename(normalizedPath);
341
+ const matches = (set) => matchesAnyGlob(set.pathGlobs, normalizedPath) || matchesAnyGlob(set.nameGlobs, name);
342
+ // Explicit deny entries (FS_DENYLIST/--deny) always apply.
343
+ if (matches(this.operator))
344
+ return true;
345
+ if (!matches(this.builtin))
346
+ return false;
347
+ // A built-in hit is lifted only by an allow entry that matches the same
348
+ // normalized candidate — a pattern that matches nothing relieves nothing.
349
+ return !matches(this.allow);
132
350
  }
133
351
  }
134
352
  //# sourceMappingURL=sensitive.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sensitive.js","sourceRoot":"","sources":["../../src/core/sensitive.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,4EAA4E;AAC5E,4EAA4E;AAC5E,wEAAwE;AACxE,2EAA2E;AAC3E,wEAAwE;AACxE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAErF,MAAM,UAAU,GAAG,EAAE,CAAC;AACtB,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAE9B,SAAS,iBAAiB,CAAC,KAAa;IACtC,4EAA4E;IAC5E,OAAO,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AACrD,CAAC;AAOD,SAAS,0BAA0B,CAAC,iBAAyB;IAC3D,OAAO,CACL,iBAAiB,CAAC,MAAM,IAAI,CAAC;QAC7B,iBAAiB,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,UAAU;QAC9C,iBAAiB,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,kBAAkB;QACtD,OAAO,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CACzC,CAAC;AACJ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AI,GAAG,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,YAAY,CAAC,CAAC;KAC9C,CAAC;AACJ,CAAC;AAED,MAAM,OAAO,gBAAgB;IACV,QAAQ,CAAqB;IAE9C,YAAY,WAA8B,sBAAsB,EAAE;QAChE,IAAI,CAAC,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;IACzC,CAAC;IAED,WAAW,CAAC,QAAgB;QAC1B,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACjF,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,WAAW,GAAG,UAAU,CAAC,CAAC,CAAC,yBAAyB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;QAChF,MAAM,cAAc,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;QACtD,OAAO,CACL,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC;YACvD,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC,CACxE,CAAC;IACJ,CAAC;CACF","sourcesContent":["// Sensitive-file denylist policy: the compiled pattern set, the path\n// normalization that feeds it, and the NTFS alternate-data-stream stripping\n// Windows needs. Split out of path.ts so the denylist has its own home — it\n// shares only isAlpha / toPosixPath / IS_WINDOWS with the primitives in\n// primitives.ts, not the allowed-directory assembly. path-completer.ts and\n// glob.ts reach it through PathGuard.isSensitive, which delegates here.\nimport { normalize, posix, sep } from 'node:path';\n\nimport { cli } from './config.js';\nimport { IS_WINDOWS, isAlpha, parseTrueEnvFlag, toPosixPath } from './primitives.js';\n\nconst CHAR_COLON = 58;\nconst CHAR_FORWARD_SLASH = 47;\n\nfunction normalizeForMatch(input: string): string {\n // Always lowercase for case-insensitive denylist matching on all platforms.\n return toPosixPath(normalize(input)).toLowerCase();\n}\n\ninterface CompiledPatternSet {\n pathGlobs: readonly string[];\n nameGlobs: readonly string[];\n}\n\nfunction isWindowsAbsolutePosixPath(normalizedPattern: string): boolean {\n return (\n normalizedPattern.length >= 3 &&\n normalizedPattern.charCodeAt(1) === CHAR_COLON &&\n normalizedPattern.charCodeAt(2) === CHAR_FORWARD_SLASH &&\n isAlpha(normalizedPattern.charCodeAt(0))\n );\n}\n\nfunction compilePatternGlobs(normalizedPattern: string): readonly string[] {\n const globs = new Set<string>([normalizedPattern]);\n\n const isRooted =\n normalizedPattern.startsWith('**/') || isWindowsAbsolutePosixPath(normalizedPattern);\n if (!isRooted) {\n const withoutRoot = normalizedPattern.replace(/^\\/+/, '');\n if (withoutRoot) {\n globs.add(`**/${withoutRoot}`);\n }\n }\n\n return Array.from(globs);\n}\n\nfunction toPatternSet(patterns: readonly string[]): CompiledPatternSet {\n const pathGlobs = new Set<string>();\n const nameGlobs = new Set<string>();\n\n const deduped = Array.from(new Set(patterns.map((p) => p.trim()).filter((p) => p.length > 0)));\n for (const pattern of deduped) {\n const normalized = normalizeForMatch(pattern);\n const matchesPath = normalized.includes('/');\n const target = matchesPath ? pathGlobs : nameGlobs;\n for (const glob of matchesPath ? compilePatternGlobs(normalized) : [normalized]) {\n target.add(glob);\n }\n }\n\n return {\n pathGlobs: [...pathGlobs],\n nameGlobs: [...nameGlobs],\n };\n}\n\nfunction matchesAnyGlob(globs: readonly string[], candidate: string): boolean {\n if (globs.length === 0) return false;\n\n for (const glob of globs) {\n if (posix.matchesGlob(candidate, glob)) return true;\n }\n\n return false;\n}\n\n// Strip NTFS alternate-data-stream suffixes (the \":stream\" after a segment)\n// before denylist matching, so `.env:secret` is caught as `.env`. Preserves the\n// drive-letter colon in the first segment of an absolute path. Also trims\n// trailing dots/spaces: Win32 strips them at the syscall boundary (a request\n// to create `.env ` actually creates `.env`), so without trimming them here the\n// exact-name patterns (`.env`, `.npmrc`) are bypassed on Windows. Mirrors the\n// precedent in getReservedDeviceName (path.ts) which trims for the same reason.\nfunction stripAlternateDataStreams(filePath: string): string {\n const parts = filePath.split(/[\\\\/]/);\n const stripped = parts.map((segment, i) => {\n if (\n i === 0 &&\n segment.length === 2 &&\n isAlpha(segment.charCodeAt(0)) &&\n segment.charCodeAt(1) === CHAR_COLON\n ) {\n return segment;\n }\n const colonIdx = segment.indexOf(':');\n const withoutStream = colonIdx !== -1 ? segment.slice(0, colonIdx) : segment;\n // Win32 strips trailing dots and spaces at the syscall boundary, so a\n // request for \".env \" creates \".env\". Strip them before denylist matching\n // or the exact-name patterns (\".env\", \".npmrc\") are bypassed on Windows.\n return trimTrailingDotsAndSpaces(withoutStream);\n });\n return stripped.join(sep);\n}\n\nconst trimTrailingDotsAndSpaces = (segment: string): string => segment.replace(/[. ]+$/, '');\n\nconst DEFAULT_SENSITIVE_PATTERNS = [\n '.env',\n '.env.*',\n '.npmrc',\n '.pypirc',\n '.aws/credentials',\n '.aws/config',\n '.mcpregistry_*_token',\n '*.pem',\n '*.key',\n '*.p12',\n '*.pfx',\n '*.crt',\n '*.cer',\n '*id_rsa*',\n '*id_dsa*',\n] as const;\n\nfunction buildSensitivePatterns(): readonly string[] {\n const allowSensitive =\n cli.allowSensitive ?? parseTrueEnvFlag(process.env['FS_ALLOW_SENSITIVE'], 'FS_ALLOW_SENSITIVE');\n const envValue = process.env['FS_DENYLIST'];\n const envDenylist = envValue\n ? envValue\n .split(/[,\\n]/u)\n .map((t) => t.trim())\n .filter((t) => t.length > 0)\n : [];\n const flagDenylist = cli.denyPatterns ?? [];\n // FS_ALLOW_SENSITIVE suppresses built-ins only; deny entries (env and --deny)\n // always apply. Set-dedupe so a pattern in both sources matches once.\n return [\n ...(allowSensitive ? [] : DEFAULT_SENSITIVE_PATTERNS),\n ...new Set([...envDenylist, ...flagDenylist]),\n ];\n}\n\nexport class SensitiveMatcher {\n private readonly patterns: CompiledPatternSet;\n\n constructor(patterns: readonly string[] = buildSensitivePatterns()) {\n this.patterns = toPatternSet(patterns);\n }\n\n isSensitive(filePath: string): boolean {\n if (this.patterns.pathGlobs.length === 0 && this.patterns.nameGlobs.length === 0) {\n return false;\n }\n const pathToCheck = IS_WINDOWS ? stripAlternateDataStreams(filePath) : filePath;\n const normalizedPath = normalizeForMatch(pathToCheck);\n return (\n matchesAnyGlob(this.patterns.pathGlobs, normalizedPath) ||\n matchesAnyGlob(this.patterns.nameGlobs, posix.basename(normalizedPath))\n );\n }\n}\n"]}
1
+ {"version":3,"file":"sensitive.js","sourceRoot":"","sources":["../../src/core/sensitive.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,4EAA4E;AAC5E,4EAA4E;AAC5E,wEAAwE;AACxE,2EAA2E;AAC3E,wEAAwE;AACxE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAErF,MAAM,UAAU,GAAG,EAAE,CAAC;AAEtB,SAAS,iBAAiB,CAAC,KAAa;IACtC,4EAA4E;IAC5E,8DAA8D;IAC9D,sEAAsE;IACtE,wEAAwE;IACxE,OAAO,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;AAC3E,CAAC;AAOD,2EAA2E;AAC3E,4EAA4E;AAC5E,uEAAuE;AACvE,2EAA2E;AAC3E,wEAAwE;AACxE,yEAAyE;AACzE,sEAAsE;AACtE,0DAA0D;AAC1D,MAAM,YAAY,GAAG,CAAC,IAAY,EAAU,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;AAE3F,4EAA4E;AAC5E,4EAA4E;AAC5E,0EAA0E;A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AC;QAC5C,MAAM,OAAO,GAAG,CAAC,GAAuB,EAAW,EAAE,CACnD,cAAc,CAAC,GAAG,CAAC,SAAS,EAAE,cAAc,CAAC,IAAI,cAAc,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QAEvF,2DAA2D;QAC3D,IAAI,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAC;QACxC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC;YAAE,OAAO,KAAK,CAAC;QACzC,wEAAwE;QACxE,0EAA0E;QAC1E,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;CACF","sourcesContent":["// Sensitive-file denylist policy: the compiled pattern set, the path\n// normalization that feeds it, and the NTFS alternate-data-stream stripping\n// Windows needs. Split out of path.ts so the denylist has its own home — it\n// shares only isAlpha / toPosixPath / IS_WINDOWS with the primitives in\n// primitives.ts, not the allowed-directory assembly. path-completer.ts and\n// glob.ts reach it through PathGuard.isSensitive, which delegates here.\nimport { normalize, posix, sep } from 'node:path';\n\nimport { cli } from './config.js';\nimport { IS_WINDOWS, isAlpha, parseTrueEnvFlag, toPosixPath } from './primitives.js';\n\nconst CHAR_COLON = 58;\n\nfunction normalizeForMatch(input: string): string {\n // Always lowercase for case-insensitive denylist matching on all platforms.\n // normalize() preserves the double leading slash of UNC paths\n // (//server/share/...) on Windows; collapse it to one so the compiled\n // patterns — which carry no leading slash — still match their segments.\n return toPosixPath(normalize(input)).toLowerCase().replace(/^\\/+/u, '/');\n}\n\ninterface CompiledPatternSet {\n pathGlobs: readonly RegExp[];\n nameGlobs: readonly RegExp[];\n}\n\n// posix.matchesGlob runs with dot:false semantics and does not honor a dot\n// option at all (verified on Node 24): '*' and '**' never match dot-leading\n// path segments, so a deny of `secrets/**` silently let `secrets/.env`\n// through — fail-open against exactly the hidden files this list exists to\n// guard. Compile our own matcher instead. Supported metacharacters: '*'\n// (any run within a segment), '**' (any run of whole segments), '?' (one\n// char), '[...]' classes, and '{a,b}' alternation; everything else is\n// literal, and dot-leading segments match like any other.\nconst escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n// Character classes can carry '{', '}' and ',' as members, so every scanner\n// below must skip a class's interior. classEnd returns the index of the ']'\n// closing the class opened at openIdx, or -1 when unclosed (then '[' is a\n// literal, matching globToRegExp's fallback). A ']' right after '[' or the\n// '!' negation is a literal member, per glob syntax.\nfunction classEnd(glob: string, openIdx: number): number {\n let i = openIdx + 1;\n if (glob[i] === '!') i++;\n if (glob[i] === ']') i++;\n while (i < glob.length && glob[i] !== ']') i++;\n return i < glob.length ? i : -1;\n}\n\nfunction expandBraces(glob: string): string[] {\n // First '{' outside any [...] class.\n let open = -1;\n for (let i = 0; i < glob.length; i++) {\n const char = glob[i] ?? '';\n if (char === '[') {\n const end = classEnd(glob, i);\n if (end !== -1) i = end;\n } else if (char === '{') {\n open = i;\n break;\n }\n }\n if (open === -1) return [glob];\n // Pair the outer '{' with ITS matching '}' — indexOf would grab the inner\n // group's closer and produce garbage like 'data/x}/secret'. Then split the\n // body on depth-0 commas so nested groups stay intact for the recursion.\n let depth = 0;\n let close = -1;\n for (let i = open; i < glob.length; i++) {\n const char = glob[i] ?? '';\n if (char === '[') {\n const end = classEnd(glob, i);\n if (end !== -1) {\n i = end;\n continue;\n }\n }\n if (char === '{') depth++;\n else if (char === '}') {\n depth--;\n if (depth === 0) {\n close = i;\n break;\n }\n }\n }\n if (close === -1) return [glob];\n const prefix = glob.slice(0, open);\n const suffix = glob.slice(close + 1);\n const body = glob.slice(open + 1, close);\n const parts: string[] = [];\n let start = 0;\n depth = 0;\n for (let i = 0; i < body.length; i++) {\n const char = body[i] ?? '';\n if (char === '[') {\n const end = classEnd(body, i);\n if (end !== -1) {\n i = end;\n continue;\n }\n }\n if (char === '{') depth++;\n else if (char === '}') depth--;\n else if (char === ',' && depth === 0) {\n parts.push(body.slice(start, i));\n start = i + 1;\n }\n }\n parts.push(body.slice(start));\n return parts.flatMap((part) => expandBraces(`${prefix}${part}${suffix}`));\n}\n\nfunction globToRegExp(glob: string): RegExp {\n const segments = glob.split('/');\n let source = '';\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i] ?? '';\n const last = i === segments.length - 1;\n if (segment === '**') {\n source += last ? '(?:.*)?' : '(?:[^/]+/)*';\n continue;\n }\n for (let j = 0; j < segment.length; j++) {\n const char = segment[j] ?? '';\n if (char === '*') {\n while (segment[j + 1] === '*') j++;\n source += '[^/]*';\n } else if (char === '?') {\n source += '[^/]';\n } else if (char === '[') {\n // Same classEnd rule the scanners use: a ']' right after '[' (or\n // after the '!' negation) is a literal member, not the closer.\n const close = classEnd(segment, j);\n if (close !== -1) {\n // Pass the class through, flipping glob '!' negation to '^' and\n // escaping backslashes so no body can make new RegExp throw. A\n // leading ']' must be escaped or the 'u' flag parses '[]a]' as an\n // empty class followed by stray literals; a leading '^' is a\n // literal member (glob negation is '!' only), unescaped it would\n // negate the class and relieve more than the operator named.\n let body = segment.slice(j + 1, close).replace(/\\\\/gu, '\\\\\\\\');\n const negated = body.startsWith('!');\n if (negated) body = body.slice(1);\n if (body.startsWith(']') || body.startsWith('^')) body = `\\\\${body}`;\n source += `[${negated ? '^' : ''}${body}]`;\n j = close;\n } else {\n source += escapeRegExp(char);\n }\n } else {\n source += escapeRegExp(char);\n }\n }\n if (!last) source += '/';\n }\n // Candidates are absolute paths but patterns carry no leading '/', so the\n // anchor optionally eats the root slash — `**/` then reaches from any\n // parent, exactly as matchesGlob's globstar did. '$' is strict in\n // JavaScript (it matches end-of-input only, unlike PCRE's, which also\n // matches before a final newline), so an exact-name pattern can never\n // match a '.env\\n' lookalike. The 's' flag makes the terminal-`**` `.`\n // match newlines too: filenames can contain them, and a deny ending in\n // '/**' must not fail open on 'secrets/plan\\nnotes'.\n return new RegExp(`^/?${source}$`, 'su');\n}\n\nfunction compilePatternGlobs(normalizedPattern: string): readonly string[] {\n // A leading '/' (POSIX-absolute) is rooted like a Windows drive path:\n // aliasing '/abs/secret' as '**/abs/secret' would also match\n // 'other/abs/secret', and on the allow side that is over-relief. The\n // drive-letter regex is safe on [a-z] because normalizeForMatch lowercased.\n const isRooted =\n normalizedPattern.startsWith('/') ||\n normalizedPattern.startsWith('**/') ||\n /^[a-z]:\\//u.test(normalizedPattern);\n const withoutRoot = isRooted ? '' : normalizedPattern.replace(/^\\/+/, '');\n return withoutRoot ? [normalizedPattern, `**/${withoutRoot}`] : [normalizedPattern];\n}\n\nfunction toPatternSet(patterns: readonly string[]): CompiledPatternSet {\n const pathGlobs = new Set<RegExp>();\n const nameGlobs = new Set<RegExp>();\n\n const deduped = Array.from(new Set(patterns.map((p) => p.trim()).filter((p) => p.length > 0)));\n for (const pattern of deduped) {\n const normalized = normalizeForMatch(pattern);\n const matchesPath = normalized.includes('/');\n const target = matchesPath ? pathGlobs : nameGlobs;\n const globs = matchesPath ? compilePatternGlobs(normalized) : [normalized];\n for (const glob of globs) {\n for (const expanded of expandBraces(glob)) {\n target.add(globToRegExp(expanded));\n }\n }\n }\n\n return {\n pathGlobs: [...pathGlobs],\n nameGlobs: [...nameGlobs],\n };\n}\n\nfunction matchesAnyGlob(globs: readonly RegExp[], candidate: string): boolean {\n return globs.some((glob) => glob.test(candidate));\n}\n\n// Strip NTFS alternate-data-stream suffixes (the \":stream\" after a segment)\n// before denylist matching, so `.env:secret` is caught as `.env`. Preserves the\n// drive-letter colon in the first segment of an absolute path. Also trims\n// trailing dots/spaces: Win32 strips them at the syscall boundary (a request\n// to create `.env ` actually creates `.env`), so without trimming them here the\n// exact-name patterns (`.env`, `.npmrc`) are bypassed on Windows. Mirrors the\n// precedent in getReservedDeviceName (path.ts) which trims for the same reason.\nfunction stripAlternateDataStreams(filePath: string): string {\n const parts = filePath.split(/[\\\\/]/);\n const stripped = parts.map((segment, i) => {\n if (\n i === 0 &&\n segment.length === 2 &&\n isAlpha(segment.charCodeAt(0)) &&\n segment.charCodeAt(1) === CHAR_COLON\n ) {\n return segment;\n }\n const colonIdx = segment.indexOf(':');\n const withoutStream = colonIdx !== -1 ? segment.slice(0, colonIdx) : segment;\n // Win32 strips trailing dots and spaces at the syscall boundary, so a\n // request for \".env \" creates \".env\". Strip them before denylist matching\n // or the exact-name patterns (\".env\", \".npmrc\") are bypassed on Windows.\n return trimTrailingDotsAndSpaces(withoutStream);\n });\n return stripped.join(sep);\n}\n\nconst trimTrailingDotsAndSpaces = (segment: string): string => segment.replace(/[. ]+$/, '');\n\nconst DEFAULT_SENSITIVE_PATTERNS = [\n '.env',\n '.env.*',\n '.npmrc',\n '.pypirc',\n '.aws/credentials',\n '.aws/config',\n '.mcpregistry_*_token',\n '*.pem',\n '*.key',\n '*.p12',\n '*.pfx',\n '*.crt',\n '*.cer',\n '*id_rsa*',\n '*id_dsa*',\n] as const;\n\n// Built-ins and operator-supplied deny entries live in separate tiers because\n// they answer to different relief switches: an allow entry (FS_ALLOWLIST /\n// --allow) can lift a built-in hit, but never an explicit deny.\n\n// Split an env pattern list on commas and newlines at brace depth 0 only and\n// outside any [...] class, so documented syntax like '*.{pem,key}' or\n// 'x[1,2].env' survives as one pattern instead of tearing apart.\nfunction splitPatternList(value: string): string[] {\n const naive = (): string[] =>\n value\n .split(/,|\\n/u)\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n let unbalanced = false;\n for (let i = 0; i < value.length; i++) {\n const char = value[i] ?? '';\n if (char === '[') {\n const end = classEnd(value, i);\n if (end !== -1) {\n i = end;\n continue;\n }\n }\n if (char === '{') depth++;\n else if (char === '}') {\n if (depth === 0) unbalanced = true;\n else depth--;\n } else if (depth === 0 && (char === ',' || char === '\\n')) {\n parts.push(value.slice(start, i));\n start = i + 1;\n }\n }\n // An unbalanced brace would swallow every separator behind it into one\n // bogus literal pattern and silently drop the real entries — '{bad,\n // secrets/**' must not lose 'secrets/**'. A typo'd brace costs the brace\n // pattern only: fall back to the naive split.\n if (unbalanced || depth !== 0) return naive();\n parts.push(value.slice(start));\n return parts.map((t) => t.trim()).filter((t) => t.length > 0);\n}\n\nfunction buildDenyTiers(): { builtin: readonly string[]; operator: readonly string[] } {\n const allowSensitive =\n cli.allowSensitive ?? parseTrueEnvFlag(process.env['FS_ALLOW_SENSITIVE'], 'FS_ALLOW_SENSITIVE');\n const envDenylist = process.env['FS_DENYLIST']\n ? splitPatternList(process.env['FS_DENYLIST'])\n : [];\n const flagDenylist = cli.denyPatterns ?? [];\n // FS_ALLOW_SENSITIVE suppresses built-ins only; deny entries (env and --deny)\n // always apply. Set-dedupe so a pattern in both sources matches once.\n return {\n builtin: allowSensitive ? [] : DEFAULT_SENSITIVE_PATTERNS,\n operator: [...new Set([...envDenylist, ...flagDenylist])],\n };\n}\n\nfunction buildAllowPatterns(): readonly string[] {\n const envAllowlist = process.env['FS_ALLOWLIST']\n ? splitPatternList(process.env['FS_ALLOWLIST'])\n : [];\n const flagAllowlist = cli.allowPatterns ?? [];\n return [...new Set([...envAllowlist, ...flagAllowlist])];\n}\n\nconst EMPTY_PATTERN_SET: CompiledPatternSet = { pathGlobs: [], nameGlobs: [] };\n\nexport class SensitiveMatcher {\n private readonly builtin: CompiledPatternSet;\n private readonly operator: CompiledPatternSet;\n private readonly allow: CompiledPatternSet;\n\n // An explicit pattern list (tests, custom guards) is one relievable tier;\n // the default construction splits built-ins from operator-supplied\n // FS_DENYLIST/--deny entries, which allow entries can never lift.\n constructor(patterns?: readonly string[], allow?: readonly string[]) {\n if (patterns !== undefined || allow !== undefined) {\n this.builtin = toPatternSet(patterns ?? []);\n this.operator = EMPTY_PATTERN_SET;\n this.allow = toPatternSet(allow ?? []);\n } else {\n const tiers = buildDenyTiers();\n this.builtin = toPatternSet(tiers.builtin);\n this.operator = toPatternSet(tiers.operator);\n this.allow = toPatternSet(buildAllowPatterns());\n }\n }\n\n isSensitive(filePath: string): boolean {\n const pathToCheck = IS_WINDOWS ? stripAlternateDataStreams(filePath) : filePath;\n const normalizedPath = normalizeForMatch(pathToCheck);\n const name = posix.basename(normalizedPath);\n const matches = (set: CompiledPatternSet): boolean =>\n matchesAnyGlob(set.pathGlobs, normalizedPath) || matchesAnyGlob(set.nameGlobs, name);\n\n // Explicit deny entries (FS_DENYLIST/--deny) always apply.\n if (matches(this.operator)) return true;\n if (!matches(this.builtin)) return false;\n // A built-in hit is lifted only by an allow entry that matches the same\n // normalized candidate — a pattern that matches nothing relieves nothing.\n return !matches(this.allow);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"watcher-registry.d.ts","sourceRoot":"","sources":["../../src/core/watcher-registry.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAK3C,eAAO,MAAM,YAAY,QAA+C,CAAC;AAMzE;;;;;GAKG;AACH,MAAM,MAAM,mBAAmB,GAC3B;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GACZ;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,OAAO,GAAG,QAAQ,GAAG,SAAS,GAAG,eAAe,CAAA;CAAE,GACvE;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,cAAc,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1D;;;;;;;GAOG;AACH,wBAAgB,qBAAqB;sBAiGV,MAAM,KAAG,OAAO;IAwFvC,wFAAwF;gBAC9E,MAAM;mBA7CI,MAAM,KAAG,IAAI;IAiDjC;;;;;;;;;;;;;;;;;;;;;;OAsBG;uBAEU,SAAS,OACf,MAAM,UACH,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,sBACF;QAAE,aAAa,CAAC,EAAE,OAAO,CAAA;KAAE,GACrD,OAAO,CAAC,mBAAmB,CAAC;eA6DpB,IAAI;EAmBlB;AAED,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,qBAAqB,CAAC,CAAC"}
1
+ {"version":3,"file":"watcher-registry.d.ts","sourceRoot":"","sources":["../../src/core/watcher-registry.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAK3C,eAAO,MAAM,YAAY,QAA+C,CAAC;AAMzE;;;;;GAKG;AACH,MAAM,MAAM,mBAAmB,GAC3B;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GACZ;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,OAAO,GAAG,QAAQ,GAAG,SAAS,GAAG,eAAe,CAAA;CAAE,GACvE;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,cAAc,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAE1D;;;;;;;GAOG;AACH,wBAAgB,qBAAqB;sBAiGV,MAAM,KAAG,OAAO;IA4FvC,wFAAwF;gBAC9E,MAAM;mBA7CI,MAAM,KAAG,IAAI;IAiDjC;;;;;;;;;;;;;;;;;;;;;;OAsBG;uBAEU,SAAS,OACf,MAAM,UACH,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,sBACF;QAAE,aAAa,CAAC,EAAE,OAAO,CAAA;KAAE,GACrD,OAAO,CAAC,mBAAmB,CAAC;eA6DpB,IAAI;EAmBlB;AAED,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,qBAAqB,CAAC,CAAC"}
@@ -142,7 +142,11 @@ export function createWatcherRegistry() {
142
142
  activeCallbacks.set(uri, callbacks);
143
143
  }
144
144
  callbacks.add(notify);
145
- desiredState.set(uri, 'subscribed');
145
+ // A live subscription needs no marker: every reader treats "no entry" the
146
+ // way it treated 'subscribed'. Clearing here is what retires the
147
+ // 'subscribing' marker `startSubscribe` set, so teardown deletes the entry
148
+ // instead of mapping it onto a 'unsubscribed' that would block a later attach.
149
+ desiredState.delete(uri);
146
150
  };
147
151
  const retain = (uri) => {
148
152
  subscriberCounts.set(uri, (subscriberCounts.get(u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AI,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,CAAC,CAAC;YACtD,CAAC;YACD,MAAM,CAAC,GAAG,CAAC,CAAC;YACZ,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;QACtB,CAAC;QAED,OAAO;YACL,SAAS,GAAG,IAAI,CAAC;YACjB,KAAK,MAAM,KAAK,IAAI,cAAc,CAAC,MAAM,EAAE,EAAE,CAAC;gBAC5C,YAAY,CAAC,KAAK,CAAC,CAAC;YACtB,CAAC;YACD,cAAc,CAAC,KAAK,EAAE,CAAC;YACvB,KAAK,MAAM,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;gBACxC,IAAI,CAAC;oBACH,OAAO,CAAC,KAAK,EAAE,CAAC;gBAClB,CAAC;gBAAC,MAAM,CAAC;oBACP,uDAAuD;gBACzD,CAAC;YACH,CAAC;YACD,QAAQ,CAAC,KAAK,EAAE,CAAC;YACjB,eAAe,CAAC,KAAK,EAAE,CAAC;YACxB,gBAAgB,CAAC,KAAK,EAAE,CAAC;YACzB,YAAY,CAAC,KAAK,EAAE,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { FSWatcher } from 'node:fs';\nimport { statSync, watch } from 'node:fs';\n\nimport { formatUnknownErrorMessage } from './errors.js';\nimport { extractPath } from './file-uri.js';\nimport { Logger } from './observability.js';\nimport type { PathGuard } from './path.js';\nimport { parseEnvInt } from './util.js';\n\n// Cap concurrent file watchers to avoid exhausting OS-level watch handles\n// (e.g. Linux inotify, default ~8192/user). One subscription == one watcher.\nexport const MAX_WATCHERS = parseEnvInt('FS_MAX_WATCHERS', 256, 1, 4096);\n\nfunction warnWatcherCap(uri: string): void {\n Logger.warn(`Cannot subscribe to ${uri}: MAX_WATCHERS limit (${MAX_WATCHERS}) reached.`);\n}\n\n/**\n * `ok` means a watcher is live for this uri and `notify` is registered. Every\n * other outcome names why, and only `invalid-path` carries what\n * `validateExistingPath` threw — so `error` is unreachable on a branch that has\n * none.\n */\nexport type WatcherAttachResult =\n | { ok: true }\n | { ok: false; reason: 'stale' | 'capped' | 'bad-uri' | 'attach-failed' }\n | { ok: false; reason: 'invalid-path'; error: unknown };\n\n/**\n * Owns the uri → FSWatcher map and the subscription bookkeeping around it:\n * notify callbacks, desired subscribe/unsubscribe state, and the watcher cap —\n * plus `acquire`, the one ladder that sequences them correctly. `acquire` awaits\n * path validation midway and re-checks `isStale` and `hasWatcher` itself\n * afterwards, so callers do not: they take a lease and release it. The\n * individual primitives stay closure-private.\n */\nexport function createWatcherRegistry() {\n const watchers = new Map<string, FSWatcher>();\n // A URI may have several notification sinks and several independent leases.\n // Callback identity and lifetime are intentionally separate: the HTTP leg\n // uses one stable bus-publishing callback for every listen stream, while each\n // stream still owns one lease that must be released on close.\n // ponytail: no per-subscription id in the SDK unsubscribe contract, so we\n // ref-count by URI. A departed direct-notification callback can linger until\n // the final lease ends; sends to a closed transport already fail harmlessly.\n // The count outlives the watcher (see `dropWatcher`), so a URI whose watcher\n // errored keeps one map entry per still-unreleased lease until they drain —\n // no watcher slot, just bookkeeping. Per-subscription-id keying retires both\n // this and the unsubscribe-by-URI over-release if that churn is observed.\n const activeCallbacks = new Map<string, Set<(uri: string) => void>>();\n const subscriberCounts = new Map<string, number>();\n const desiredState = new Map<string, 'subscribed' | 'unsubscribed' | 'subscribing'>();\n const debounceTimers = new Map<string, NodeJS.Timeout>();\n let destroyed = false;\n\n // 'unsubscribed' exists only to abort a subscribe that is mid-await\n // (isStale). If no subscribe is in flight, keep no entry at all: a lingering\n // 'unsubscribed' would permanently block the modern attach path (which never\n // calls startSubscribe) and leak one map entry per URI ever watched. This\n // must be idempotent: remove()'s teardown branch calls this directly and\n // then unconditionally calls dropWatcher (which also calls this) for the\n // same uri — the second call must not clobber what the first one set.\n const settleDesiredState = (uri: string): void => {\n const current = desiredState.get(uri);\n if (current === 'subscribing') {\n desiredState.set(uri, 'unsubscribed');\n } else if (current !== 'unsubscribed') {\n desiredState.delete(uri);\n }\n };\n\n // Tears down the watcher itself, NOT the ref-count. The 'error' event calls\n // this with leases still outstanding: clearing the count there would let the\n // next release from one of those leases decrement from zero and drop a\n // watcher a later subscriber re-established for the same URI. `drop` below is\n // the only path that ends leases, and it is the only one that clears them.\n const dropWatcher = (uri: string, watcher: FSWatcher): void => {\n const current = watchers.get(uri);\n if (current !== watcher) return;\n const timer = debounceTimers.get(uri);\n if (timer) {\n clearTimeout(timer);\n debounceTimers.delete(uri);\n }\n watcher.close();\n watchers.delete(uri);\n activeCallbacks.delete(uri);\n settleDesiredState(uri);\n };\n\n /** The last lease ended: drop the watcher and every trace of the URI. */\n const drop = (uri: string): void => {\n const timer = debounceTimers.get(uri);\n if (timer) {\n clearTimeout(timer);\n debounceTimers.delete(uri);\n }\n const watcher = watchers.get(uri);\n if (watcher) dropWatcher(uri, watcher);\n activeCallbacks.delete(uri);\n subscriberCounts.delete(uri);\n settleDesiredState(uri);\n };\n\n const notifyAll = (uri: string): void => {\n const callbacks = activeCallbacks.get(uri);\n if (!callbacks || callbacks.size === 0) return;\n const existing = debounceTimers.get(uri);\n if (existing) {\n clearTimeout(existing);\n }\n const timer = setTimeout(() => {\n debounceTimers.delete(uri);\n const cbs = activeCallbacks.get(uri);\n if (!cbs) return;\n // One debounce timer per URI — fan out to every subscriber inside it, so\n // a burst of changes still fires one notification round per URI, not per\n // subscriber.\n for (const cb of cbs) {\n try {\n cb(uri);\n } catch (err) {\n Logger.warn(`Notify callback error for ${uri}: ${formatUnknownErrorMessage(err)}`);\n }\n }\n }, 50);\n timer.unref();\n debounceTimers.set(uri, timer);\n };\n\n // The primitives below are hoisted out of the returned literal so `acquire`\n // can sequence them from inside the closure. They are closure-private.\n\n const hasWatcher = (uri: string): boolean => watchers.has(uri);\n\n const isAtCap = (): boolean => watchers.size >= MAX_WATCHERS;\n\n /** The registry was destroyed, or this uri was unsubscribed, mid-await. */\n const isStale = (uri: string): boolean => destroyed || desiredState.get(uri) === 'unsubscribed';\n\n const startSubscribe = (uri: string): void => {\n desiredState.set(uri, 'subscribing');\n };\n\n /**\n * A subscribe that declared intent and then failed — bad URI, unvalidatable\n * path, cap, fs.watch refusal — drops the entry entirely. Not\n * `settleDesiredState`: that maps 'subscribing' onto 'unsubscribed' to abort\n * an attach still mid-await, and a *finished* failure leaving 'unsubscribed'\n * behind would make `isStale` true forever, so the modern attach path (which\n * never calls `startSubscribe`) could never watch this uri again. Only\n * clears its own 'subscribing' — a concurrent unsubscribe that already set\n * 'unsubscribed' still wins.\n */\n const cancelSubscribe = (uri: string): void => {\n if (desiredState.get(uri) === 'subscribing') desiredState.delete(uri);\n };\n\n const addCallback = (uri: string, notify: (uri: string) => void): void => {\n let callbacks = activeCallbacks.get(uri);\n if (!callbacks) {\n callbacks = new Set();\n activeCallbacks.set(uri, callbacks);\n }\n callbacks.add(notify);\n desiredState.set(uri, 'subscribed');\n };\n\n const retain = (uri: string): void => {\n subscriberCounts.set(uri, (subscriberCounts.get(uri) ?? 0) + 1);\n };\n\n /**\n * Ref-count by URI: only tear down the shared watcher when the last lease\n * ends. Callback identity is independent from this count. A release with no\n * lease outstanding (a rolled-back attach) drops the watcher outright.\n */\n const release = (uri: string): void => {\n const remaining = (subscriberCounts.get(uri) ?? 0) - 1;\n if (remaining > 0) {\n subscriberCounts.set(uri, remaining);\n return;\n }\n drop(uri);\n };\n\n const attach = (uri: string, resolvedPath: string): boolean => {\n try {\n // Watch directories recursively (children included) and files as-is.\n // `fs.watch` async errors arrive via the 'error' event below, not as a\n // sync throw, so no recursive-fallback try/catch is needed here — the\n // outer catch handles sync throws (inotify exhaustion, path-race).\n // `{ recursive: true }` is honored on macOS, Windows, and — since Node\n // 20.13 — Linux; `engines.node` is >=24, so all three are covered.\n const recursive = statSync(resolvedPath).isDirectory();\n const watcher = watch(resolvedPath, recursive ? { recursive: true } : undefined, () => {\n notifyAll(uri);\n });\n watcher.on('error', (err: Error) => {\n Logger.warn(`Watcher error for ${uri}: ${err.message}`);\n dropWatcher(uri, watcher);\n });\n // Two attaches that both cleared `hasWatcher` before either finished\n // validating land here for the same uri. Keep the one already wired to\n // the callback set and close this one — overwriting the map entry would\n // strand the first watcher's fd with nothing left holding a reference.\n if (watchers.has(uri)) {\n watcher.close();\n return true;\n }\n watchers.set(uri, watcher);\n return true;\n } catch (err) {\n Logger.error(`Failed to create watcher for ${uri}: ${formatUnknownErrorMessage(err)}`);\n return false;\n }\n };\n\n return {\n hasWatcher,\n\n /** Live watcher count, for pre-checking a batched listen against remaining capacity. */\n size: (): number => watchers.size,\n\n release,\n\n /**\n * The one attach ladder both watcher entry points run: `resources/subscribe`\n * (2025 era) and the `subscriptions/listen` filter (modern era, HTTP and\n * stdio). Never throws — it reports the outcome and lets each caller decide\n * what that is worth: subscribe owes its caller a precise error, and listen\n * (`prepareListenWatchers`) treats the batch as all-or-nothing, releasing\n * every lease it already took and rejecting the request. Idempotent per URI\n * — a second call for an already-watched URI re-registers the notify\n * callback (one watcher per URI).\n *\n * `markSubscribe` is the one branch that differs: only `resources/subscribe`\n * declares desired state (what `isStale` aborts against). The listen path\n * must not, or a rejected attach past that point strands a `'subscribing'`\n * entry nothing settles. Whoever declares it, this function settles it:\n * every failing exit past that point cancels the declaration, so no uri is\n * poisoned for a later attach.\n *\n * Every `ok` return takes one lease; lifetime is the caller's to manage.\n * HTTP releases when the listen response closes. Stdio tracks the listen\n * request ID and releases on cancellation, SDK rejection, or graceful\n * completion. In both legs the ref-count is by URI, so a watcher another\n * stream still holds survives.\n */\n async acquire(\n pathGuard: PathGuard,\n uri: string,\n notify: (uri: string) => void,\n { markSubscribe = false }: { markSubscribe?: boolean } = {},\n ): Promise<WatcherAttachResult> {\n // Every failing exit below routes through here, so the declaration made by\n // `startSubscribe` can never outlive the attach that made it.\n const fail = (result: WatcherAttachResult & { ok: false }): WatcherAttachResult => {\n if (markSubscribe) cancelSubscribe(uri);\n return result;\n };\n\n if (hasWatcher(uri)) {\n // A watcher already tracks this uri; just (re)register the callback so\n // its change events reach the new subscriber. No validation or cap work\n // is needed for an already-live watcher.\n addCallback(uri, notify);\n retain(uri);\n return { ok: true };\n }\n // A cap hit before validation and one found after the await are the same\n // condition, and both are reported the same way.\n if (isAtCap()) {\n warnWatcherCap(uri);\n return { ok: false, reason: 'capped' };\n }\n\n if (markSubscribe) startSubscribe(uri);\n\n const filePath = extractPath(uri);\n if (!filePath) return fail({ ok: false, reason: 'bad-uri' });\n\n let resolved: string;\n try {\n resolved = await pathGuard.validateExistingPath(filePath);\n } catch (error: unknown) {\n return fail({ ok: false, reason: 'invalid-path', error });\n }\n\n // Re-check what the await could have changed. A stale uri is the one\n // failure that must NOT cancel: an unsubscribe landed mid-await and its\n // 'unsubscribed' marker is the thing that aborted this attach.\n if (isStale(uri)) return { ok: false, reason: 'stale' };\n if (hasWatcher(uri)) {\n addCallback(uri, notify);\n retain(uri);\n return { ok: true };\n }\n if (isAtCap()) {\n warnWatcherCap(uri);\n return fail({ ok: false, reason: 'capped' });\n }\n\n addCallback(uri, notify);\n if (!attach(uri, resolved)) {\n // fs.watch threw (inotify exhaustion, or a race deleted the path): roll\n // back so no dangling callback is left believing a watcher exists. No\n // lease was taken yet, so `release` drops the entry outright.\n release(uri);\n return fail({ ok: false, reason: 'attach-failed' });\n }\n retain(uri);\n return { ok: true };\n },\n\n destroy(): void {\n destroyed = true;\n for (const timer of debounceTimers.values()) {\n clearTimeout(timer);\n }\n debounceTimers.clear();\n for (const watcher of watchers.values()) {\n try {\n watcher.close();\n } catch {\n /* ignore close errors so all watchers are attempted */\n }\n }\n watchers.clear();\n activeCallbacks.clear();\n subscriberCounts.clear();\n desiredState.clear();\n },\n };\n}\n\nexport type WatcherRegistry = ReturnType<typeof createWatcherRegistry>;\n"]}
1
+ {"version":3,"file":"watcher-registry.js","sourceRoot":"","sources":["../../src/core/watcher-registry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;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,CAAC;YACZ,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;QACtB,CAAC;QAED,OAAO;YACL,SAAS,GAAG,IAAI,CAAC;YACjB,KAAK,MAAM,KAAK,IAAI,cAAc,CAAC,MAAM,EAAE,EAAE,CAAC;gBAC5C,YAAY,CAAC,KAAK,CAAC,CAAC;YACtB,CAAC;YACD,cAAc,CAAC,KAAK,EAAE,CAAC;YACvB,KAAK,MAAM,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;gBACxC,IAAI,CAAC;oBACH,OAAO,CAAC,KAAK,EAAE,CAAC;gBAClB,CAAC;gBAAC,MAAM,CAAC;oBACP,uDAAuD;gBACzD,CAAC;YACH,CAAC;YACD,QAAQ,CAAC,KAAK,EAAE,CAAC;YACjB,eAAe,CAAC,KAAK,EAAE,CAAC;YACxB,gBAAgB,CAAC,KAAK,EAAE,CAAC;YACzB,YAAY,CAAC,KAAK,EAAE,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { FSWatcher } from 'node:fs';\nimport { statSync, watch } from 'node:fs';\n\nimport { formatUnknownErrorMessage } from './errors.js';\nimport { extractPath } from './file-uri.js';\nimport { Logger } from './observability.js';\nimport type { PathGuard } from './path.js';\nimport { parseEnvInt } from './util.js';\n\n// Cap concurrent file watchers to avoid exhausting OS-level watch handles\n// (e.g. Linux inotify, default ~8192/user). One subscription == one watcher.\nexport const MAX_WATCHERS = parseEnvInt('FS_MAX_WATCHERS', 256, 1, 4096);\n\nfunction warnWatcherCap(uri: string): void {\n Logger.warn(`Cannot subscribe to ${uri}: MAX_WATCHERS limit (${MAX_WATCHERS}) reached.`);\n}\n\n/**\n * `ok` means a watcher is live for this uri and `notify` is registered. Every\n * other outcome names why, and only `invalid-path` carries what\n * `validateExistingPath` threw — so `error` is unreachable on a branch that has\n * none.\n */\nexport type WatcherAttachResult =\n | { ok: true }\n | { ok: false; reason: 'stale' | 'capped' | 'bad-uri' | 'attach-failed' }\n | { ok: false; reason: 'invalid-path'; error: unknown };\n\n/**\n * Owns the uri → FSWatcher map and the subscription bookkeeping around it:\n * notify callbacks, desired subscribe/unsubscribe state, and the watcher cap —\n * plus `acquire`, the one ladder that sequences them correctly. `acquire` awaits\n * path validation midway and re-checks `isStale` and `hasWatcher` itself\n * afterwards, so callers do not: they take a lease and release it. The\n * individual primitives stay closure-private.\n */\nexport function createWatcherRegistry() {\n const watchers = new Map<string, FSWatcher>();\n // A URI may have several notification sinks and several independent leases.\n // Callback identity and lifetime are intentionally separate: the HTTP leg\n // uses one stable bus-publishing callback for every listen stream, while each\n // stream still owns one lease that must be released on close.\n // ponytail: no per-subscription id in the SDK unsubscribe contract, so we\n // ref-count by URI. A departed direct-notification callback can linger until\n // the final lease ends; sends to a closed transport already fail harmlessly.\n // The count outlives the watcher (see `dropWatcher`), so a URI whose watcher\n // errored keeps one map entry per still-unreleased lease until they drain —\n // no watcher slot, just bookkeeping. Per-subscription-id keying retires both\n // this and the unsubscribe-by-URI over-release if that churn is observed.\n const activeCallbacks = new Map<string, Set<(uri: string) => void>>();\n const subscriberCounts = new Map<string, number>();\n const desiredState = new Map<string, 'unsubscribed' | 'subscribing'>();\n const debounceTimers = new Map<string, NodeJS.Timeout>();\n let destroyed = false;\n\n // 'unsubscribed' exists only to abort a subscribe that is mid-await\n // (isStale). If no subscribe is in flight, keep no entry at all: a lingering\n // 'unsubscribed' would permanently block the modern attach path (which never\n // calls startSubscribe) and leak one map entry per URI ever watched. This\n // must be idempotent: remove()'s teardown branch calls this directly and\n // then unconditionally calls dropWatcher (which also calls this) for the\n // same uri — the second call must not clobber what the first one set.\n const settleDesiredState = (uri: string): void => {\n const current = desiredState.get(uri);\n if (current === 'subscribing') {\n desiredState.set(uri, 'unsubscribed');\n } else if (current !== 'unsubscribed') {\n desiredState.delete(uri);\n }\n };\n\n // Tears down the watcher itself, NOT the ref-count. The 'error' event calls\n // this with leases still outstanding: clearing the count there would let the\n // next release from one of those leases decrement from zero and drop a\n // watcher a later subscriber re-established for the same URI. `drop` below is\n // the only path that ends leases, and it is the only one that clears them.\n const dropWatcher = (uri: string, watcher: FSWatcher): void => {\n const current = watchers.get(uri);\n if (current !== watcher) return;\n const timer = debounceTimers.get(uri);\n if (timer) {\n clearTimeout(timer);\n debounceTimers.delete(uri);\n }\n watcher.close();\n watchers.delete(uri);\n activeCallbacks.delete(uri);\n settleDesiredState(uri);\n };\n\n /** The last lease ended: drop the watcher and every trace of the URI. */\n const drop = (uri: string): void => {\n const timer = debounceTimers.get(uri);\n if (timer) {\n clearTimeout(timer);\n debounceTimers.delete(uri);\n }\n const watcher = watchers.get(uri);\n if (watcher) dropWatcher(uri, watcher);\n activeCallbacks.delete(uri);\n subscriberCounts.delete(uri);\n settleDesiredState(uri);\n };\n\n const notifyAll = (uri: string): void => {\n const callbacks = activeCallbacks.get(uri);\n if (!callbacks || callbacks.size === 0) return;\n const existing = debounceTimers.get(uri);\n if (existing) {\n clearTimeout(existing);\n }\n const timer = setTimeout(() => {\n debounceTimers.delete(uri);\n const cbs = activeCallbacks.get(uri);\n if (!cbs) return;\n // One debounce timer per URI — fan out to every subscriber inside it, so\n // a burst of changes still fires one notification round per URI, not per\n // subscriber.\n for (const cb of cbs) {\n try {\n cb(uri);\n } catch (err) {\n Logger.warn(`Notify callback error for ${uri}: ${formatUnknownErrorMessage(err)}`);\n }\n }\n }, 50);\n timer.unref();\n debounceTimers.set(uri, timer);\n };\n\n // The primitives below are hoisted out of the returned literal so `acquire`\n // can sequence them from inside the closure. They are closure-private.\n\n const hasWatcher = (uri: string): boolean => watchers.has(uri);\n\n const isAtCap = (): boolean => watchers.size >= MAX_WATCHERS;\n\n /** The registry was destroyed, or this uri was unsubscribed, mid-await. */\n const isStale = (uri: string): boolean => destroyed || desiredState.get(uri) === 'unsubscribed';\n\n const startSubscribe = (uri: string): void => {\n desiredState.set(uri, 'subscribing');\n };\n\n /**\n * A subscribe that declared intent and then failed — bad URI, unvalidatable\n * path, cap, fs.watch refusal — drops the entry entirely. Not\n * `settleDesiredState`: that maps 'subscribing' onto 'unsubscribed' to abort\n * an attach still mid-await, and a *finished* failure leaving 'unsubscribed'\n * behind would make `isStale` true forever, so the modern attach path (which\n * never calls `startSubscribe`) could never watch this uri again. Only\n * clears its own 'subscribing' — a concurrent unsubscribe that already set\n * 'unsubscribed' still wins.\n */\n const cancelSubscribe = (uri: string): void => {\n if (desiredState.get(uri) === 'subscribing') desiredState.delete(uri);\n };\n\n const addCallback = (uri: string, notify: (uri: string) => void): void => {\n let callbacks = activeCallbacks.get(uri);\n if (!callbacks) {\n callbacks = new Set();\n activeCallbacks.set(uri, callbacks);\n }\n callbacks.add(notify);\n // A live subscription needs no marker: every reader treats \"no entry\" the\n // way it treated 'subscribed'. Clearing here is what retires the\n // 'subscribing' marker `startSubscribe` set, so teardown deletes the entry\n // instead of mapping it onto a 'unsubscribed' that would block a later attach.\n desiredState.delete(uri);\n };\n\n const retain = (uri: string): void => {\n subscriberCounts.set(uri, (subscriberCounts.get(uri) ?? 0) + 1);\n };\n\n /**\n * Ref-count by URI: only tear down the shared watcher when the last lease\n * ends. Callback identity is independent from this count. A release with no\n * lease outstanding (a rolled-back attach) drops the watcher outright.\n */\n const release = (uri: string): void => {\n const remaining = (subscriberCounts.get(uri) ?? 0) - 1;\n if (remaining > 0) {\n subscriberCounts.set(uri, remaining);\n return;\n }\n drop(uri);\n };\n\n const attach = (uri: string, resolvedPath: string): boolean => {\n try {\n // Watch directories recursively (children included) and files as-is.\n // `fs.watch` async errors arrive via the 'error' event below, not as a\n // sync throw, so no recursive-fallback try/catch is needed here — the\n // outer catch handles sync throws (inotify exhaustion, path-race).\n // `{ recursive: true }` is honored on macOS, Windows, and — since Node\n // 20.13 — Linux; `engines.node` is >=24, so all three are covered.\n const recursive = statSync(resolvedPath).isDirectory();\n const watcher = watch(resolvedPath, recursive ? { recursive: true } : undefined, () => {\n notifyAll(uri);\n });\n watcher.on('error', (err: Error) => {\n Logger.warn(`Watcher error for ${uri}: ${err.message}`);\n dropWatcher(uri, watcher);\n });\n // Two attaches that both cleared `hasWatcher` before either finished\n // validating land here for the same uri. Keep the one already wired to\n // the callback set and close this one — overwriting the map entry would\n // strand the first watcher's fd with nothing left holding a reference.\n if (watchers.has(uri)) {\n watcher.close();\n return true;\n }\n watchers.set(uri, watcher);\n return true;\n } catch (err) {\n Logger.error(`Failed to create watcher for ${uri}: ${formatUnknownErrorMessage(err)}`);\n return false;\n }\n };\n\n return {\n hasWatcher,\n\n /** Live watcher count, for pre-checking a batched listen against remaining capacity. */\n size: (): number => watchers.size,\n\n release,\n\n /**\n * The one attach ladder both watcher entry points run: `resources/subscribe`\n * (2025 era) and the `subscriptions/listen` filter (modern era, HTTP and\n * stdio). Never throws — it reports the outcome and lets each caller decide\n * what that is worth: subscribe owes its caller a precise error, and listen\n * (`prepareListenWatchers`) treats the batch as all-or-nothing, releasing\n * every lease it already took and rejecting the request. Idempotent per URI\n * — a second call for an already-watched URI re-registers the notify\n * callback (one watcher per URI).\n *\n * `markSubscribe` is the one branch that differs: only `resources/subscribe`\n * declares desired state (what `isStale` aborts against). The listen path\n * must not, or a rejected attach past that point strands a `'subscribing'`\n * entry nothing settles. Whoever declares it, this function settles it:\n * every failing exit past that point cancels the declaration, so no uri is\n * poisoned for a later attach.\n *\n * Every `ok` return takes one lease; lifetime is the caller's to manage.\n * HTTP releases when the listen response closes. Stdio tracks the listen\n * request ID and releases on cancellation, SDK rejection, or graceful\n * completion. In both legs the ref-count is by URI, so a watcher another\n * stream still holds survives.\n */\n async acquire(\n pathGuard: PathGuard,\n uri: string,\n notify: (uri: string) => void,\n { markSubscribe = false }: { markSubscribe?: boolean } = {},\n ): Promise<WatcherAttachResult> {\n // Every failing exit below routes through here, so the declaration made by\n // `startSubscribe` can never outlive the attach that made it.\n const fail = (result: WatcherAttachResult & { ok: false }): WatcherAttachResult => {\n if (markSubscribe) cancelSubscribe(uri);\n return result;\n };\n\n if (hasWatcher(uri)) {\n // A watcher already tracks this uri; just (re)register the callback so\n // its change events reach the new subscriber. No validation or cap work\n // is needed for an already-live watcher.\n addCallback(uri, notify);\n retain(uri);\n return { ok: true };\n }\n // A cap hit before validation and one found after the await are the same\n // condition, and both are reported the same way.\n if (isAtCap()) {\n warnWatcherCap(uri);\n return { ok: false, reason: 'capped' };\n }\n\n if (markSubscribe) startSubscribe(uri);\n\n const filePath = extractPath(uri);\n if (!filePath) return fail({ ok: false, reason: 'bad-uri' });\n\n let resolved: string;\n try {\n resolved = await pathGuard.validateExistingPath(filePath);\n } catch (error: unknown) {\n return fail({ ok: false, reason: 'invalid-path', error });\n }\n\n // Re-check what the await could have changed. A stale uri is the one\n // failure that must NOT cancel: an unsubscribe landed mid-await and its\n // 'unsubscribed' marker is the thing that aborted this attach.\n if (isStale(uri)) return { ok: false, reason: 'stale' };\n if (hasWatcher(uri)) {\n addCallback(uri, notify);\n retain(uri);\n return { ok: true };\n }\n if (isAtCap()) {\n warnWatcherCap(uri);\n return fail({ ok: false, reason: 'capped' });\n }\n\n addCallback(uri, notify);\n if (!attach(uri, resolved)) {\n // fs.watch threw (inotify exhaustion, or a race deleted the path): roll\n // back so no dangling callback is left believing a watcher exists. No\n // lease was taken yet, so `release` drops the entry outright.\n release(uri);\n return fail({ ok: false, reason: 'attach-failed' });\n }\n retain(uri);\n return { ok: true };\n },\n\n destroy(): void {\n destroyed = true;\n for (const timer of debounceTimers.values()) {\n clearTimeout(timer);\n }\n debounceTimers.clear();\n for (const watcher of watchers.values()) {\n try {\n watcher.close();\n } catch {\n /* ignore close errors so all watchers are attempted */\n }\n }\n watchers.clear();\n activeCallbacks.clear();\n subscriberCounts.clear();\n desiredState.clear();\n },\n };\n}\n\nexport type WatcherRegistry = ReturnType<typeof createWatcherRegistry>;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../src/resources.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,SAAS,EACT,gCAAgC,EAChC,SAA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E,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,GAAG,gBAAgB,EAAE,CAM7F;AA8BD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,qBAAqB,GAAG;IAAE,OAAO,IAAI,IAAI,CAAA;CAAE,CAwJlF"}
package/dist/resources.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { checkResourceAllowed, ProtocolError, ProtocolErrorCode, ResourceNotFoundError, ResourceTemplate, resourceUrlFromServerUrl, } from '@modelcontextprotocol/server';
2
- import { ErrorCode, formatUnknownErrorMessage, fsErrorCode, hasErrorShape, isFsError, } from './core/errors.js';
2
+ import { ErrorCode, formatUnknownErrorMessage, fsErrorCode, isFsError } from './core/errors.js';
3
3
  import { decodeFileUriPath, encodeFileUriPath, extractPath, FILESYSTEM_FILE_URI_TEMPLATE, } from './core/file-uri.js';
4
4
  import { GuardedFileSystem } from './core/fs.js';
5
5
  import { Logger } from './core/observability.js';
@@ -254,7 +254,9 @@ function wrapRead(contract) {
254
254
  return await contract.read(uri, variables, ctx);
255
255
  }
256
256
  catch (error) {
257
- if (hasErrorShape(error, 'ProtocolError'))
257
+ // The SDK brands ProtocolError with `static [Symbol.hasInstance]`, so this
258
+ // holds across separately bundled SDK copies and realms.
259
+ if (error instanceof ProtocolError)
258
260
  throw error;
259
261
  // A missing or out-of-root path is a not-found, not a malformed request.
260
262
  // The SDK puts ResourceNotFoundError on the wire as -32602 with
@@ -296,8 +298,15 @@ export function registerResources(deps) {
296
298
  // `resources/subscribe`/`unsubscribe` are 2025-era-only verbs; a modern
297
299
  // server answers `-32601 Method not found` for them, so registering these
298
300
  // handlers on a modern-era instance would dispatch to code no request can
299
- // reach.
300
- if (deps.era !== 'modern') {
301
+ // reach. A legacy instance on the HTTP leg (the one built with a `notifier`)
302
+ // lives for one request: a subscription accepted there would take a watcher
303
+ // lease for an instance that is gone before the file changes. Leave the
304
+ // handlers off so the SDK refuses the verb, and no lease is taken. The
305
+ // predicate mirrors the capability gate in server.ts exactly, so the
306
+ // handler is registered if and only if `resources.subscribe` is advertised.
307
+ // sunset(SEP-2577): removal trigger in docs/adr/002-legacy-protocol-paths-sunset.md.
308
+ const legacyHttp = deps.era === 'legacy' && deps.notifier !== undefined;
309
+ if (deps.era !== 'modern' && !legacyHttp) {
301
310
  server.server.assertCanSetRequestHandler('resources/subscribe');
302
311
  server.server.assertCanSetRequestHandler('resources/unsubscribe');
303
312
  // One stable callback for the whole registrar, NOT one per subscribe. The