@radnine/claude-session-daemon 0.8.0 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@radnine/claude-session-daemon",
3
- "version": "0.8.0",
3
+ "version": "0.8.3",
4
4
  "description": "Node.js daemon for managing Claude CLI sessions",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
7
7
  "type": "git",
8
- "url": "git+ssh://git@github.com/radixhound/rad-project.git",
8
+ "url": "git+ssh://git@github.com/radixhound/flight-deck.git",
9
9
  "directory": "daemon"
10
10
  },
11
11
  "main": "src/index.js",
@@ -1,56 +1,222 @@
1
1
  'use strict';
2
2
 
3
+ const { execFile } = require('node:child_process');
3
4
  const fs = require('node:fs').promises;
4
5
  const os = require('node:os');
5
6
  const path = require('node:path');
7
+ const { promisify } = require('node:util');
8
+
9
+ const execFileAsync = promisify(execFile);
6
10
 
7
11
  const CACHE_TTL_MS = 60_000;
12
+ const EXEC_TIMEOUT_MS = 5000;
13
+
8
14
  let _cache = null; // { value, expiresAt }
9
15
 
10
16
  /**
11
- * Read the logged-in Claude account from ~/.claude.json.
17
+ * Report which Claude account a pilot actually runs as.
12
18
  *
13
- * The Claude CLI persists the active OAuth account at `oauthAccount.emailAddress`.
14
- * We surface email + account/org UUIDs so the UI can warn when the user is logged
15
- * into a different account than they expect (different rate limits).
19
+ * The daemon spawns the CLI with `{...process.env, ...sessionEnv}`, so the
20
+ * account in force is whatever that environment resolves to — and two env vars
21
+ * move it off the home directory:
16
22
  *
17
- * Cached for 60s; returns null if the file is missing/malformed or the field is absent.
23
+ * - CLAUDE_CONFIG_DIR relocates the whole config directory. Pointed at a
24
+ * directory with no account, the CLI is signed out even though the login
25
+ * Keychain still holds the default credentials.
26
+ * - CLAUDE_CODE_OAUTH_TOKEN overrides the login entirely, while
27
+ * `~/.claude.json` goes on naming the default account.
18
28
  *
19
- * @param {string} [filePath] - Override path for tests.
20
- * @returns {Promise<{email: string, account_uuid: string|null, organization_uuid: string|null}|null>}
29
+ * Reading `~/.claude.json` therefore states the opposite of the truth under
30
+ * either one, which defeats the point of the display — catching a pilot on an
31
+ * unexpected subscription. So we ask the CLI (`claude auth status`, JSON on
32
+ * stdout) with the same environment, and fall back to the config file only when
33
+ * the subprocess gives us nothing.
34
+ *
35
+ * Always resolves to an account object, never null. `signed_out` and `unknown`
36
+ * are answers: they overwrite the last-known account on the server, where a
37
+ * null would leave the previous pilot's email sitting on screen. A wrong-but-
38
+ * confident email is the defect this exists to prevent.
39
+ *
40
+ * Cached for 60s — which also bounds the subprocess to once a minute.
41
+ *
42
+ * @param {object} [options]
43
+ * @param {object} [options.env] - Environment to resolve against (default process.env).
44
+ * @param {Function} [options.exec] - execFile-style runner, for tests.
45
+ * @param {string} [options.configFile] - Override the resolved `.claude.json` path.
46
+ * @returns {Promise<{state: string, email: string|null, account_uuid: string|null,
47
+ * organization_uuid: string|null, auth_method: string|null,
48
+ * subscription_type: string|null, source: string, config_dir: string|null}>}
21
49
  */
22
- async function getClaudeAccount(filePath) {
50
+ async function getClaudeAccount(options = {}) {
23
51
  const now = Date.now();
24
- if (!filePath && _cache && _cache.expiresAt > now) {
52
+ const cacheable = !options.env && !options.exec && !options.configFile;
53
+ if (cacheable && _cache && _cache.expiresAt > now) {
25
54
  return _cache.value;
26
55
  }
27
56
 
28
- const target = filePath || path.join(os.homedir(), '.claude.json');
29
- let value = null;
57
+ const env = options.env || process.env;
58
+ const exec = options.exec || execFileAsync;
59
+ const configDir = readEnv(env, 'CLAUDE_CONFIG_DIR');
60
+ const configFile = options.configFile || path.join(configDir || os.homedir(), '.claude.json');
61
+
62
+ const [status, fileAccount] = await Promise.all([
63
+ readAuthStatus(env, exec),
64
+ readClaudeConfigAccount(configFile),
65
+ ]);
66
+
67
+ const value = status
68
+ ? fromAuthStatus(status, fileAccount, configDir)
69
+ : fromConfigFile(fileAccount, env, configDir);
70
+
71
+ if (cacheable) {
72
+ _cache = { value, expiresAt: now + CACHE_TTL_MS };
73
+ }
74
+ return value;
75
+ }
30
76
 
77
+ /**
78
+ * Read the account recorded in a `.claude.json`.
79
+ *
80
+ * The Claude CLI persists the active OAuth account at `oauthAccount.emailAddress`.
81
+ * Returns null if the file is missing/malformed or the field is absent — note
82
+ * that a config directory the CLI has written to but nobody has logged into has
83
+ * a `.claude.json` with no `oauthAccount` at all, so null here means "this file
84
+ * names no account", not "signed out".
85
+ *
86
+ * @param {string} filePath
87
+ * @returns {Promise<{email: string, account_uuid: string|null, organization_uuid: string|null}|null>}
88
+ */
89
+ async function readClaudeConfigAccount(filePath) {
31
90
  try {
32
- const raw = await fs.readFile(target, 'utf8');
91
+ const raw = await fs.readFile(filePath, 'utf8');
33
92
  const parsed = JSON.parse(raw);
34
93
  const oauth = parsed && parsed.oauthAccount;
35
94
  if (oauth && typeof oauth.emailAddress === 'string' && oauth.emailAddress.length > 0) {
36
- value = {
95
+ return {
37
96
  email: oauth.emailAddress,
38
97
  account_uuid: oauth.accountUuid || null,
39
98
  organization_uuid: oauth.organizationUuid || null,
40
99
  };
41
100
  }
42
101
  } catch (_) {
43
- value = null;
102
+ return null;
44
103
  }
104
+ return null;
105
+ }
45
106
 
46
- if (!filePath) {
47
- _cache = { value, expiresAt: now + CACHE_TTL_MS };
107
+ /**
108
+ * Run `claude auth status` and return its parsed JSON verdict, or null when the
109
+ * CLI gives us no usable answer.
110
+ */
111
+ async function readAuthStatus(env, exec) {
112
+ const command = readEnv(env, 'CLAUDE_COMMAND') || 'claude';
113
+ let stdout = null;
114
+
115
+ try {
116
+ ({ stdout } = await exec(command, ['auth', 'status'], { env, timeout: EXEC_TIMEOUT_MS }));
117
+ } catch (err) {
118
+ // Signed out is reported as exit 1 with the JSON verdict still on stdout
119
+ // (verified against CLI 2.1.246), so a non-zero exit is not "no answer".
120
+ stdout = err && typeof err.stdout === 'string' ? err.stdout : null;
48
121
  }
49
- return value;
122
+
123
+ if (!stdout) return null;
124
+
125
+ try {
126
+ const parsed = JSON.parse(stdout);
127
+ // `loggedIn` is the field the whole verdict hangs on. Without it we are
128
+ // looking at partial output or a different command's JSON.
129
+ return parsed && typeof parsed.loggedIn === 'boolean' ? parsed : null;
130
+ } catch (_) {
131
+ return null;
132
+ }
133
+ }
134
+
135
+ function fromAuthStatus(status, fileAccount, configDir) {
136
+ const authMethod = nonEmpty(status.authMethod);
137
+
138
+ if (!status.loggedIn) {
139
+ return account({ state: 'signed_out', auth_method: authMethod, source: 'cli', config_dir: configDir });
140
+ }
141
+
142
+ const email = nonEmpty(status.email);
143
+ if (!email) {
144
+ // Signed in, but the CLI will not name the account — the token-auth case.
145
+ return account({
146
+ state: 'unknown',
147
+ auth_method: authMethod,
148
+ subscription_type: nonEmpty(status.subscriptionType),
149
+ source: 'cli',
150
+ config_dir: configDir,
151
+ });
152
+ }
153
+
154
+ // `auth status` has no account UUID of its own. Borrow it from the config
155
+ // file only when that file names the same account we just resolved.
156
+ const sameAccount = fileAccount && fileAccount.email === email;
157
+
158
+ return account({
159
+ state: 'signed_in',
160
+ email,
161
+ account_uuid: sameAccount ? fileAccount.account_uuid : null,
162
+ organization_uuid: nonEmpty(status.orgId) || (sameAccount ? fileAccount.organization_uuid : null),
163
+ auth_method: authMethod,
164
+ subscription_type: nonEmpty(status.subscriptionType),
165
+ source: 'cli',
166
+ config_dir: configDir,
167
+ });
168
+ }
169
+
170
+ // Fallback for when the CLI gave us nothing. Weaker than the CLI on purpose:
171
+ // credentials live in the login Keychain keyed to the config directory, so a
172
+ // `.claude.json` naming an account does not prove a session is signed in to it.
173
+ // This keeps a broken or slow CLI degrading to the old behaviour rather than
174
+ // blanking the display.
175
+ function fromConfigFile(fileAccount, env, configDir) {
176
+ // A token overrides whatever the config file names, and without the CLI we
177
+ // cannot resolve it. The file's email is the one answer we know is wrong.
178
+ if (readEnv(env, 'CLAUDE_CODE_OAUTH_TOKEN')) {
179
+ return account({ state: 'unknown', auth_method: 'oauth_token', source: 'config_file', config_dir: configDir });
180
+ }
181
+
182
+ if (fileAccount) {
183
+ return account({
184
+ state: 'signed_in',
185
+ email: fileAccount.email,
186
+ account_uuid: fileAccount.account_uuid,
187
+ organization_uuid: fileAccount.organization_uuid,
188
+ source: 'config_file',
189
+ config_dir: configDir,
190
+ });
191
+ }
192
+
193
+ return account({ state: 'unknown', source: 'config_file', config_dir: configDir });
194
+ }
195
+
196
+ /** Build the full payload shape so every field is present in every state. */
197
+ function account(fields) {
198
+ return {
199
+ state: fields.state,
200
+ email: fields.email || null,
201
+ account_uuid: fields.account_uuid || null,
202
+ organization_uuid: fields.organization_uuid || null,
203
+ auth_method: fields.auth_method || null,
204
+ subscription_type: fields.subscription_type || null,
205
+ source: fields.source,
206
+ config_dir: fields.config_dir || null,
207
+ };
208
+ }
209
+
210
+ function nonEmpty(value) {
211
+ return typeof value === 'string' && value.trim().length > 0 ? value : null;
212
+ }
213
+
214
+ function readEnv(env, name) {
215
+ return nonEmpty(env && env[name]);
50
216
  }
51
217
 
52
218
  function _resetCacheForTests() {
53
219
  _cache = null;
54
220
  }
55
221
 
56
- module.exports = { getClaudeAccount, _resetCacheForTests };
222
+ module.exports = { getClaudeAccount, readClaudeConfigAccount, _resetCacheForTests };
@@ -299,17 +299,57 @@ class ClaudeProcess extends EventEmitter {
299
299
  if (!settings.hooks) settings.hooks = {};
300
300
  if (!Array.isArray(settings.hooks.PreToolUse)) settings.hooks.PreToolUse = [];
301
301
 
302
- // Check if our hook is already registered (avoid duplicates)
303
- const alreadyRegistered = settings.hooks.PreToolUse.some(
304
- (h) => h.command && h.command.includes('permission-gate.sh')
305
- );
302
+ const isOurHook = (cmd) => typeof cmd === 'string' && cmd.includes('permission-gate.sh');
303
+ const isGateEntry = (entry) =>
304
+ isOurHook(entry.command) ||
305
+ (Array.isArray(entry.hooks) && entry.hooks.some((h) => h && isOurHook(h.command)));
306
+
307
+ const before = JSON.stringify(settings.hooks.PreToolUse);
308
+ const next = [];
309
+ let seenGate = false;
310
+
311
+ for (const entry of settings.hooks.PreToolUse) {
312
+ if (!entry || typeof entry !== 'object' || !isGateEntry(entry)) {
313
+ next.push(entry);
314
+ continue;
315
+ }
316
+
317
+ // Collapse to a single gate. Two match-all entries would run the hook
318
+ // twice per tool call — two blocking POSTs and doubled approval prompts.
319
+ // Seen in the wild as one valid entry alongside a legacy one.
320
+ if (seenGate) continue;
321
+ seenGate = true;
322
+
323
+ // Daemons <= 0.8.0 wrote { matcher, command }. Claude Code's schema
324
+ // requires a nested `hooks` array, so those entries never ran.
325
+ let command = isOurHook(entry.command)
326
+ ? entry.command
327
+ : entry.hooks.find((h) => h && isOurHook(h.command)).command;
328
+
329
+ // A path from an install that has since been removed would fail on every
330
+ // tool call, so fall back to the copy we are running from.
331
+ if (!fs.existsSync(command)) command = hookScript;
332
+
333
+ const others = (Array.isArray(entry.hooks) ? entry.hooks : []).filter(
334
+ (h) => !(h && isOurHook(h.command))
335
+ );
336
+ delete entry.command;
337
+ if (typeof entry.matcher !== 'string') entry.matcher = '';
338
+ entry.hooks = [...others, { type: 'command', command }];
339
+ next.push(entry);
340
+ }
306
341
 
307
- if (!alreadyRegistered) {
308
- settings.hooks.PreToolUse.push({
342
+ if (!seenGate) {
343
+ next.push({
309
344
  matcher: '',
310
- command: hookScript,
345
+ hooks: [{ type: 'command', command: hookScript }],
311
346
  });
347
+ }
348
+
349
+ settings.hooks.PreToolUse = next;
350
+ const changed = JSON.stringify(settings.hooks.PreToolUse) !== before;
312
351
 
352
+ if (changed) {
313
353
  fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
314
354
  this._logger.info('Registered permission hook in project settings', {
315
355
  settingsPath,
@@ -10,6 +10,7 @@ const { getGitContext } = require('../git-context');
10
10
  const { getClaudeAccount } = require('../claude-account');
11
11
  const { getMachineEffort } = require('../machine-effort');
12
12
  const { scanPersonas, readPersonaBody } = require('../persona-scanner');
13
+ const { handleFsRequest } = require('../fs-bridge');
13
14
  const daemonPkg = require('../../package.json');
14
15
 
15
16
  /**
@@ -522,6 +523,9 @@ class ActionCableClient extends BaseConnection {
522
523
  case 'file_request':
523
524
  this._handleFileRequest(inner);
524
525
  break;
526
+ case 'fs_request':
527
+ this._handleFsRequest(inner);
528
+ break;
525
529
  case 'permission_response':
526
530
  this._handlePermissionResponse(inner);
527
531
  break;
@@ -988,6 +992,48 @@ class ActionCableClient extends BaseConnection {
988
992
  }
989
993
  }
990
994
 
995
+ /**
996
+ * Handle fs_request — generalized filesystem RPC (stat/read) secured by
997
+ * realpath containment. See src/fs-bridge.js for the containment and op
998
+ * logic; this method only does message dispatch and response transmission,
999
+ * mirroring _handleFileRequest's conventions above. That older flow is
1000
+ * plan-doc-specific (.md/.markdown only, lexical containment) and is left
1001
+ * untouched — this is the generalized replacement path for new callers.
1002
+ * @param {object} message - { op, path, request_id, reply_stream }
1003
+ */
1004
+ async _handleFsRequest(message) {
1005
+ const requestId = message.request_id;
1006
+ const replyStream = message.reply_stream;
1007
+ const op = message.op;
1008
+ const requestedPath = message.path;
1009
+
1010
+ this._logger.info('Received fs_request', { op, path: requestedPath, requestId });
1011
+
1012
+ let result;
1013
+ try {
1014
+ result = await handleFsRequest(message, { workingDir: this._workingDir, logger: this._logger });
1015
+ } catch (err) {
1016
+ // handleFsRequest is designed not to throw, but never let an
1017
+ // unexpected exception leave the request unanswered.
1018
+ this._logger.error('fs_request handling threw unexpectedly', { path: requestedPath, error: err.message });
1019
+ result = { op, path: requestedPath, error: `Internal error: ${err.message}` };
1020
+ }
1021
+
1022
+ if (result.error) {
1023
+ this._logger.warn('fs_request failed', { op, path: requestedPath, error: result.error });
1024
+ } else {
1025
+ this._logger.info('fs_request fulfilled', { op, path: requestedPath, exists: result.exists });
1026
+ }
1027
+
1028
+ this.sendDaemonMessage({
1029
+ type: 'fs_response',
1030
+ request_id: requestId,
1031
+ reply_stream: replyStream,
1032
+ ...result,
1033
+ timestamp: new Date().toISOString(),
1034
+ });
1035
+ }
1036
+
991
1037
  // ---------------------------------------------------------------------------
992
1038
  // Outbound helper methods
993
1039
  // ---------------------------------------------------------------------------
@@ -0,0 +1,374 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs').promises;
4
+ const path = require('node:path');
5
+
6
+ /**
7
+ * Generalized filesystem RPC for the daemon<->Rails bridge (fs_request /
8
+ * fs_response). This generalizes the older, plan-doc-specific file_request
9
+ * flow (see connections/action-cable-client.js `_handleFileRequest`) to
10
+ * arbitrary ops (`stat`, `read`, `list`) behind realpath-based
11
+ * containment, since the old flow's lexical `path.resolve()` +
12
+ * `.startsWith()` check has two known defects:
13
+ * 1. Symlink escape: a symlink that lives *inside* the working directory
14
+ * but points outside it passes the lexical check untouched, because
15
+ * `path.resolve` does not follow symlinks.
16
+ * 2. Prefix collision: `.startsWith(workingDir)` is a *string* prefix
17
+ * test, so a sibling directory whose name extends the workdir's name
18
+ * (e.g. workdir `/work`, sibling `/work-evil`) is wrongly treated as
19
+ * contained.
20
+ *
21
+ * Both are fixed by resolving both sides through `fs.realpath` and
22
+ * comparing with `path.relative`, never with string prefixes.
23
+ */
24
+
25
+ // Extensions allowed for fs_request reads/stats, compared lowercase.
26
+ // Extend this list as new doc types need to be exposed to Rails.
27
+ //
28
+ // File bridge S3 added the code-extension block below (clickable file
29
+ // references in chat need to fetch source files, not just docs) — kept in
30
+ // lockstep with VaultFileTypes::ALLOWED_EXTENSIONS (app/models/vault_file_types.rb)
31
+ // by hand; VaultFileTypesSpec asserts the two lists match by reading this
32
+ // file off disk.
33
+ const ALLOWED_EXTENSIONS = Object.freeze([
34
+ '.md', '.markdown', '.txt',
35
+ '.rb', '.js', '.ts', '.jsx', '.tsx', '.json', '.yaml', '.yml',
36
+ '.erb', '.html', '.css', '.scss', '.py', '.sh', '.sql', '.scad', '.toml',
37
+ ]);
38
+
39
+ // Reject reads of files larger than this before ever touching file content.
40
+ const MAX_READ_BYTES = 1048576; // 1 MB
41
+
42
+ // Reject `list` results with more raw directory entries than this — a typed
43
+ // error, not silent truncation, so the caller knows the listing is
44
+ // incomplete rather than assuming it saw everything.
45
+ const MAX_LIST_ENTRIES = 500;
46
+
47
+ /**
48
+ * Cheap, fs-free pre-check on the raw requested path string. Must run
49
+ * before any fs access.
50
+ *
51
+ * @param {*} requestedPath
52
+ * @param {{ allowEmptyRoot?: boolean }} [options] - `allowEmptyRoot: true`
53
+ * lets `""` (and `"."`, which already passes unmodified below) through as
54
+ * a legal reference to the working directory itself. Only `list` passes
55
+ * this — `stat`/`read` are unaffected and still reject an empty path,
56
+ * since neither of those operations has a meaningful "root" target.
57
+ * @returns {string|null} an error message, or null if the shape is fine
58
+ */
59
+ function checkPathShape(requestedPath, options) {
60
+ const allowEmptyRoot = Boolean(options && options.allowEmptyRoot);
61
+
62
+ if (typeof requestedPath !== 'string') {
63
+ return 'Path must be a non-empty string';
64
+ }
65
+ if (requestedPath.length === 0) {
66
+ if (allowEmptyRoot) return null;
67
+ return 'Path must be a non-empty string';
68
+ }
69
+ if (requestedPath.includes('\0')) {
70
+ return 'Access denied: path contains a NUL byte';
71
+ }
72
+ if (path.isAbsolute(requestedPath)) {
73
+ return 'Access denied: absolute paths are not allowed';
74
+ }
75
+ const segments = requestedPath.split('/');
76
+ if (segments.includes('..')) {
77
+ return 'Access denied: path contains directory traversal';
78
+ }
79
+ return null;
80
+ }
81
+
82
+ /**
83
+ * Case-insensitive extension allowlist check.
84
+ * @param {string} requestedPath
85
+ * @returns {boolean}
86
+ */
87
+ function isAllowedExtension(requestedPath) {
88
+ const ext = path.extname(requestedPath).toLowerCase();
89
+ return ALLOWED_EXTENSIONS.includes(ext);
90
+ }
91
+
92
+ /**
93
+ * Pure containment predicate: is `realTarget` equal to, or inside,
94
+ * `realWorkdir`? Both arguments MUST already be realpath-resolved — this
95
+ * function does no fs I/O, so it is safe (and intended) to unit test
96
+ * directly with hand-constructed strings (e.g. prefix-collision cases).
97
+ *
98
+ * Deliberately uses `path.relative` rather than a string-prefix test —
99
+ * `path.relative('/work', '/work-evil/x')` is `'../work-evil/x'`, which
100
+ * `.startsWith('..')` catches, whereas `'/work-evil/x'.startsWith('/work')`
101
+ * would (wrongly) be `true`.
102
+ *
103
+ * @param {string} realWorkdir
104
+ * @param {string} realTarget
105
+ * @returns {boolean}
106
+ */
107
+ function isPathContained(realWorkdir, realTarget) {
108
+ if (realTarget === realWorkdir) return true;
109
+ const rel = path.relative(realWorkdir, realTarget);
110
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
111
+ }
112
+
113
+ /**
114
+ * Resolve `requestedPath` (workdir-relative, already shape-checked) against
115
+ * `workingDir` and decide containment using realpath on both sides.
116
+ *
117
+ * Two cases:
118
+ * - The target exists: realpath the target itself and check containment
119
+ * against the realpath'd working dir.
120
+ * - The target does not exist (ENOENT): realpath the target's *parent*
121
+ * directory instead and apply the same containment check to it. This
122
+ * closes the symlinked-directory variant of the escape (a directory
123
+ * symlink inside the workdir pointing outside, traversed to a path that
124
+ * happens not to exist) while still letting a plain "file not found"
125
+ * inside the real workdir report `exists: false` cleanly. If the parent
126
+ * itself doesn't exist, there is nothing further up worth resolving —
127
+ * report `exists: false` without leaking any fs structure.
128
+ *
129
+ * @param {string} workingDir - absolute working directory (may itself be
130
+ * a symlink; realpath'd here)
131
+ * @param {string} requestedPath - workdir-relative path, already passed
132
+ * through `checkPathShape`
133
+ * @returns {Promise<
134
+ * { contained: true, exists: true, realPath: string } |
135
+ * { contained: true, exists: false } |
136
+ * { contained: false, error: string }
137
+ * >}
138
+ */
139
+ async function resolveContained(workingDir, requestedPath) {
140
+ let realWorkdir;
141
+ try {
142
+ realWorkdir = await fs.realpath(workingDir);
143
+ } catch (err) {
144
+ return { contained: false, error: `Cannot resolve working directory: ${err.message}` };
145
+ }
146
+
147
+ const candidate = path.resolve(workingDir, requestedPath);
148
+
149
+ try {
150
+ const realTarget = await fs.realpath(candidate);
151
+ if (!isPathContained(realWorkdir, realTarget)) {
152
+ return { contained: false, error: 'Access denied: path is outside the working directory' };
153
+ }
154
+ return { contained: true, exists: true, realPath: realTarget };
155
+ } catch (err) {
156
+ if (err.code !== 'ENOENT') {
157
+ return { contained: false, error: `Cannot resolve path: ${err.message}` };
158
+ }
159
+ // Candidate itself doesn't exist — check the parent directory instead.
160
+ const parent = path.dirname(candidate);
161
+ let realParent;
162
+ try {
163
+ realParent = await fs.realpath(parent);
164
+ } catch (parentErr) {
165
+ if (parentErr.code === 'ENOENT') {
166
+ // Nothing further up exists either — plain not-found, no structure leaked.
167
+ return { contained: true, exists: false };
168
+ }
169
+ return { contained: false, error: `Cannot resolve path: ${parentErr.message}` };
170
+ }
171
+ if (!isPathContained(realWorkdir, realParent)) {
172
+ return { contained: false, error: 'Access denied: path is outside the working directory' };
173
+ }
174
+ return { contained: true, exists: false };
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Directory listing for the tree browser (`op: "list"`). One level deep —
180
+ * no recursion, the caller (the UI tree) lazy-loads deeper levels with
181
+ * further `list` calls. Entries are filtered (dotfiles/dot-dirs excluded,
182
+ * files restricted to `ALLOWED_EXTENSIONS`, symlink entries omitted rather
183
+ * than resolved — see the module README/PR notes for why: resolving each
184
+ * entry's realpath to decide whether *it* escapes containment would cost an
185
+ * extra stat per entry for a case that's already covered defense-in-depth
186
+ * by `resolveContained` rejecting the escape the moment anything tries to
187
+ * `list`/`stat`/`read` *through* that symlink) and sorted dirs-first, then
188
+ * by name.
189
+ *
190
+ * @param {string} requestedPath - already shape-checked (empty allowed)
191
+ * @param {string} workingDir
192
+ * @returns {Promise<object>} response fields for an fs_response
193
+ */
194
+ async function handleListRequest(requestedPath, workingDir) {
195
+ const fail = (error) => ({ op: 'list', path: requestedPath, error });
196
+
197
+ // "" and "." both mean "the working directory itself" — resolveContained/
198
+ // path.resolve already treat "." this way, so only "" needs normalizing.
199
+ const normalizedPath = requestedPath === '' ? '.' : requestedPath;
200
+
201
+ const resolution = await resolveContained(workingDir, normalizedPath);
202
+ if (!resolution.contained) {
203
+ return fail(resolution.error);
204
+ }
205
+
206
+ if (!resolution.exists) {
207
+ return { op: 'list', path: requestedPath, exists: false };
208
+ }
209
+
210
+ let stats;
211
+ try {
212
+ stats = await fs.stat(resolution.realPath);
213
+ } catch (err) {
214
+ return fail(`Failed to stat path: ${err.message}`);
215
+ }
216
+
217
+ if (!stats.isDirectory()) {
218
+ return fail('Not a directory');
219
+ }
220
+
221
+ let dirents;
222
+ try {
223
+ dirents = await fs.readdir(resolution.realPath, { withFileTypes: true });
224
+ } catch (err) {
225
+ return fail(`Failed to read directory: ${err.message}`);
226
+ }
227
+
228
+ const candidates = dirents.filter((dirent) => {
229
+ if (dirent.name.startsWith('.')) return false; // .git, .claude, etc. stay invisible
230
+ if (dirent.isDirectory()) return true;
231
+ if (dirent.isFile()) return isAllowedExtension(dirent.name);
232
+ return false; // symlinks and other special entry types omitted
233
+ });
234
+
235
+ // Capped on the *filtered* count (what would actually be returned), not
236
+ // the raw directory size — a directory full of excluded dotfiles/other
237
+ // extensions shouldn't be rejected just for being noisy; it's the
238
+ // resulting `entries` payload (and the per-entry stat calls below) this
239
+ // limit protects.
240
+ if (candidates.length > MAX_LIST_ENTRIES) {
241
+ return fail(`Directory too large: ${candidates.length} entries exceeds ${MAX_LIST_ENTRIES} entry limit`);
242
+ }
243
+
244
+ const entries = [];
245
+ for (const dirent of candidates) {
246
+ const entryPath = path.join(resolution.realPath, dirent.name);
247
+ let entryStats;
248
+ try {
249
+ entryStats = await fs.stat(entryPath);
250
+ } catch (_err) {
251
+ continue; // raced/removed between readdir and stat — drop it silently
252
+ }
253
+ entries.push({
254
+ name: dirent.name,
255
+ type: dirent.isDirectory() ? 'dir' : 'file',
256
+ size_bytes: entryStats.size,
257
+ mtime: entryStats.mtime.toISOString(),
258
+ });
259
+ }
260
+
261
+ entries.sort((a, b) => {
262
+ if (a.type !== b.type) return a.type === 'dir' ? -1 : 1;
263
+ return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
264
+ });
265
+
266
+ return { op: 'list', path: requestedPath, exists: true, entries };
267
+ }
268
+
269
+ /**
270
+ * Handle a single fs_request end-to-end and return the response payload
271
+ * fields (everything an fs_response carries EXCEPT `type`, `request_id`,
272
+ * `reply_stream`, and `timestamp` — the caller/transport layer attaches
273
+ * those). `content` is present only on a successful `read`; `entries` is
274
+ * present only on a successful `list` of a directory; `error` is always
275
+ * mutually exclusive with `exists`/`mtime`/`size_bytes`/`content`/`entries`.
276
+ *
277
+ * @param {{ op: string, path: string }} message
278
+ * @param {{ workingDir: string, logger?: object }} opts
279
+ * @returns {Promise<object>} response fields: { op, path, exists?, mtime?, size_bytes?, content?, entries?, error? }
280
+ */
281
+ async function handleFsRequest(message, opts) {
282
+ const { workingDir } = opts || {};
283
+ const op = message && message.op;
284
+ const requestedPath = message && message.path;
285
+
286
+ const fail = (error) => ({ op, path: requestedPath, error });
287
+
288
+ if (op !== 'stat' && op !== 'read' && op !== 'list') {
289
+ return fail(`Unsupported operation: "${op}"`);
290
+ }
291
+
292
+ if (!workingDir) {
293
+ return fail('No working directory configured');
294
+ }
295
+
296
+ const shapeError = checkPathShape(requestedPath, { allowEmptyRoot: op === 'list' });
297
+ if (shapeError) return fail(shapeError);
298
+
299
+ if (op === 'list') {
300
+ return handleListRequest(requestedPath, workingDir);
301
+ }
302
+
303
+ if (!isAllowedExtension(requestedPath)) {
304
+ const ext = path.extname(requestedPath) || '(none)';
305
+ return fail(`Disallowed file extension: ${ext}`);
306
+ }
307
+
308
+ const resolution = await resolveContained(workingDir, requestedPath);
309
+ if (!resolution.contained) {
310
+ return fail(resolution.error);
311
+ }
312
+
313
+ if (!resolution.exists) {
314
+ return { op, path: requestedPath, exists: false };
315
+ }
316
+
317
+ let stats;
318
+ try {
319
+ stats = await fs.stat(resolution.realPath);
320
+ } catch (err) {
321
+ return fail(`Failed to stat file: ${err.message}`);
322
+ }
323
+
324
+ if (!stats.isFile()) {
325
+ return fail('Not a regular file');
326
+ }
327
+
328
+ if (op === 'stat') {
329
+ // stat must never read file content.
330
+ return {
331
+ op,
332
+ path: requestedPath,
333
+ exists: true,
334
+ mtime: stats.mtime.toISOString(),
335
+ size_bytes: stats.size,
336
+ };
337
+ }
338
+
339
+ // op === 'read' — check size BEFORE reading content.
340
+ if (stats.size > MAX_READ_BYTES) {
341
+ return fail(`File too large: ${stats.size} bytes exceeds ${MAX_READ_BYTES} byte limit`);
342
+ }
343
+
344
+ let buffer;
345
+ try {
346
+ buffer = await fs.readFile(resolution.realPath);
347
+ } catch (err) {
348
+ return fail(`Failed to read file: ${err.message}`);
349
+ }
350
+
351
+ if (buffer.includes(0)) {
352
+ return fail('binary file');
353
+ }
354
+
355
+ return {
356
+ op,
357
+ path: requestedPath,
358
+ exists: true,
359
+ mtime: stats.mtime.toISOString(),
360
+ size_bytes: stats.size,
361
+ content: buffer.toString('utf8'),
362
+ };
363
+ }
364
+
365
+ module.exports = {
366
+ ALLOWED_EXTENSIONS,
367
+ MAX_READ_BYTES,
368
+ MAX_LIST_ENTRIES,
369
+ checkPathShape,
370
+ isAllowedExtension,
371
+ isPathContained,
372
+ resolveContained,
373
+ handleFsRequest,
374
+ };