@clawchatsai/connector 0.1.25 → 0.1.26

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.
@@ -53,6 +53,6 @@ export declare function handleAuthMessage(dc: DataChannelSend, connectionId: str
53
53
  */
54
54
  export declare function cleanupAuth(connectionId: string): void;
55
55
  /**
56
- * Check if a connection is authenticated (no longer in auth sessions).
56
+ * Check if a connection completed auth.
57
57
  */
58
58
  export declare function isAuthenticated(connectionId: string): boolean;
@@ -19,15 +19,31 @@ import { issueSessionToken, verifySessionToken } from './session-token.js';
19
19
  // ---------------------------------------------------------------------------
20
20
  /** Tracks per-connection auth state */
21
21
  const authSessions = new Map();
22
+ /**
23
+ * Connections that completed auth. This is the only thing that grants access:
24
+ * a connection whose auth session was dropped (timeout, rate limit, eviction)
25
+ * is NOT authenticated, it is blocked until it reconnects.
26
+ */
27
+ const authenticatedConnections = new Set();
22
28
  /** Rate limiting: connectionIds blocked after too many failures */
23
29
  const blockedConnections = new Map(); // connectionId → unblock timestamp
24
30
  /** TOTP replay prevention */
25
31
  let lastUsedTotpStep = 0;
32
+ /**
33
+ * Gateway-wide auth-full lockout. Per-connection limits alone reset on every
34
+ * reconnect, so failures are also counted across all connections.
35
+ */
36
+ let globalFailCount = 0;
37
+ let globalLockoutCount = 0;
38
+ let globalLockedUntil = 0;
26
39
  /** Max nonces to prevent memory leaks from connection storms */
27
40
  const MAX_PENDING_NONCES = 10;
28
41
  const AUTH_TIMEOUT_MS = 60_000; // 60s — enough time to open authenticator app and enter code
29
42
  const MAX_FAILURES = 5;
30
43
  const BLOCK_DURATION_MS = 60_000;
44
+ const GLOBAL_MAX_FAILURES = 5;
45
+ const GLOBAL_LOCKOUT_BASE_MS = 60_000; // doubles per consecutive lockout
46
+ const GLOBAL_LOCKOUT_MAX_MS = 60 * 60_000;
31
47
  // ---------------------------------------------------------------------------
32
48
  // Public API
33
49
  // ---------------------------------------------------------------------------
@@ -63,6 +79,8 @@ export function initAuth(dc, connectionId) {
63
79
  const old = authSessions.get(oldestKey);
64
80
  clearTimeout(old.timeoutHandle);
65
81
  authSessions.delete(oldestKey);
82
+ // Tell the evicted client so it reconnects instead of hanging
83
+ old.dc.send(JSON.stringify({ type: 'auth-failed', reason: 'auth_timeout' }));
66
84
  }
67
85
  }
68
86
  const nonce = crypto.randomBytes(32).toString('hex');
@@ -83,6 +101,7 @@ export function initAuth(dc, connectionId) {
83
101
  failCount: 0,
84
102
  createdAt: Date.now(),
85
103
  timeoutHandle,
104
+ dc,
86
105
  });
87
106
  dc.send(JSON.stringify({
88
107
  type: 'auth-required',
@@ -99,16 +118,14 @@ export function initAuth(dc, connectionId) {
99
118
  * 'blocked' if the message was dropped (pre-auth non-auth message)
100
119
  */
101
120
  export async function handleAuthMessage(dc, connectionId, msg, config) {
102
- const session = authSessions.get(connectionId);
103
- // No auth session = already authenticated or unknown connection
104
- if (!session) {
121
+ if (authenticatedConnections.has(connectionId)) {
105
122
  return 'pass';
106
123
  }
107
- // Already authenticated (shouldn't happen, but be safe)
108
- if (session.state === 'authenticated') {
109
- clearTimeout(session.timeoutHandle);
110
- authSessions.delete(connectionId);
111
- return 'pass';
124
+ const session = authSessions.get(connectionId);
125
+ // No auth session and never authenticated: the session was dropped (timeout,
126
+ // rate limit, eviction) or never started. Block; the client must reconnect.
127
+ if (!session || session.state !== 'awaiting-auth') {
128
+ return 'blocked';
112
129
  }
113
130
  // Only accept auth messages pre-auth
114
131
  const msgType = msg['type'];
@@ -141,16 +158,23 @@ export async function handleAuthMessage(dc, connectionId, msg, config) {
141
158
  const totp = msg['totp'];
142
159
  const sessionDays = msg['sessionDays'] || 7;
143
160
  const msgNonce = msg['nonce'];
161
+ // Gateway-wide lockout: refuse without checking anything, so no guess is tested
162
+ if (Date.now() < globalLockedUntil) {
163
+ dc.send(JSON.stringify({ type: 'auth-failed', reason: 'rate_limited' }));
164
+ return 'pending';
165
+ }
144
166
  // Verify nonce
145
167
  if (msgNonce !== session.nonce) {
146
168
  return sendFailure(dc, connectionId, 'nonce_mismatch');
147
169
  }
148
- // Verify Google ID token (skipped when not configured or in dev mode)
170
+ // Google ID token check. The frontend sends 'signaling-verified' on purpose
171
+ // (bd29058): login.clawchats.ai already did Google sign-in, so TOTP is the
172
+ // connector-side factor and the gateway-wide lockout above protects it.
149
173
  const skipGoogle = !config.google.clientId || config.google.clientId === 'dev-placeholder'
150
174
  || idToken === 'signaling-verified'
151
175
  || (config.devMode && idToken === 'dev-mode-no-google');
152
176
  if (skipGoogle) {
153
- console.log('[Auth] Skipping Google ID token verification (not configured)');
177
+ console.log('[Auth] Skipping Google ID token verification (TOTP-only auth)');
154
178
  }
155
179
  else {
156
180
  try {
@@ -192,14 +216,18 @@ export async function handleAuthMessage(dc, connectionId, msg, config) {
192
216
  // Caller should persist the updated config
193
217
  }
194
218
  else {
219
+ recordGlobalFailure();
195
220
  return sendFailure(dc, connectionId, 'invalid_totp');
196
221
  }
197
222
  }
223
+ globalFailCount = 0;
224
+ globalLockoutCount = 0;
198
225
  // Issue session token
199
226
  const sessionToken = issueSessionToken(config.userId, config.google.authorizedSub, sessionDays, config.sessionSecret);
200
227
  const expiresAt = new Date(Date.now() + Math.min(Math.max(sessionDays, 1), 30) * 86400 * 1000).toISOString();
201
228
  clearTimeout(session.timeoutHandle);
202
229
  authSessions.delete(connectionId);
230
+ authenticatedConnections.add(connectionId);
203
231
  dc.send(JSON.stringify({
204
232
  type: 'auth-ok',
205
233
  sessionToken,
@@ -218,12 +246,13 @@ export function cleanupAuth(connectionId) {
218
246
  clearTimeout(session.timeoutHandle);
219
247
  authSessions.delete(connectionId);
220
248
  }
249
+ authenticatedConnections.delete(connectionId);
221
250
  }
222
251
  /**
223
- * Check if a connection is authenticated (no longer in auth sessions).
252
+ * Check if a connection completed auth.
224
253
  */
225
254
  export function isAuthenticated(connectionId) {
226
- return !authSessions.has(connectionId);
255
+ return authenticatedConnections.has(connectionId);
227
256
  }
228
257
  // ---------------------------------------------------------------------------
229
258
  // Internal helpers
@@ -234,9 +263,20 @@ function authSuccess(dc, connectionId) {
234
263
  clearTimeout(session.timeoutHandle);
235
264
  authSessions.delete(connectionId);
236
265
  }
266
+ authenticatedConnections.add(connectionId);
237
267
  dc.send(JSON.stringify({ type: 'auth-ok' }));
238
268
  return 'authenticated';
239
269
  }
270
+ function recordGlobalFailure() {
271
+ globalFailCount++;
272
+ if (globalFailCount < GLOBAL_MAX_FAILURES)
273
+ return;
274
+ const duration = Math.min(GLOBAL_LOCKOUT_BASE_MS * 2 ** globalLockoutCount, GLOBAL_LOCKOUT_MAX_MS);
275
+ globalLockedUntil = Date.now() + duration;
276
+ globalLockoutCount++;
277
+ globalFailCount = 0;
278
+ console.warn(`[Auth] ${GLOBAL_MAX_FAILURES} failed TOTP attempts — full auth locked for ${duration / 1000}s`);
279
+ }
240
280
  function sendFailure(dc, connectionId, reason) {
241
281
  const session = authSessions.get(connectionId);
242
282
  if (!session)
package/dist/index.js CHANGED
@@ -445,11 +445,9 @@ function setupDataChannelHandler(dc, connectionId, ctx) {
445
445
  // Pre-auth non-auth message — drop silently
446
446
  return;
447
447
  case 'pass':
448
- // Already authenticated — process message normally.
449
- // Note: if auth_timeout deleted the session but DC is still open,
450
- // we get 'pass' for a potentially un-authed connection. This is
451
- // acceptable because auth_timeout now triggers a P2P reconnect
452
- // (Fix 4), which re-establishes the full auth flow.
448
+ // Completed auth on this connection — process message normally.
449
+ // A connection whose auth timed out or was rate-limited gets
450
+ // 'blocked', never 'pass'; the client reconnects (Fix 4).
453
451
  break;
454
452
  }
455
453
  // Authenticated message processing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.25",
3
+ "version": "0.1.26",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
@@ -68,16 +68,121 @@ export function handleWorkspaceList(req, res, query) {
68
68
  send(res, 200, { files, cwd: resolved });
69
69
  }
70
70
 
71
+ const MAX_HINTS = 40;
72
+ const MAX_SEARCH_DIRS = 400;
73
+
74
+ function isFile(p) {
75
+ try { return fs.statSync(p).isFile(); } catch { return false; }
76
+ }
77
+
78
+ function exists(p) {
79
+ try { fs.statSync(p); return true; } catch { return false; }
80
+ }
81
+
82
+ function addMatch(matches, candidate) {
83
+ if (!isFile(candidate)) return;
84
+ try { matches.set(fs.realpathSync(candidate), candidate); } catch { /* vanished */ }
85
+ }
86
+
87
+ // True when the file sits in a git main checkout (`.git` is a folder), false in a linked
88
+ // worktree (`.git` is a file) or outside git.
89
+ function inMainCheckout(file) {
90
+ for (let dir = path.dirname(file); ; dir = path.dirname(dir)) {
91
+ try { return fs.statSync(path.join(dir, '.git')).isDirectory(); } catch { /* keep walking */ }
92
+ if (dir === path.dirname(dir)) return false;
93
+ }
94
+ }
95
+
96
+ // One distinct file wins; among several, a single one in a git main checkout wins (other chats'
97
+ // worktrees carry copies of the same file). Anything else is ambiguous.
98
+ function pickMatch(matches) {
99
+ const found = [...matches.values()];
100
+ if (found.length <= 1) return found[0] ?? null;
101
+ const main = found.filter(inMainCheckout);
102
+ return main.length === 1 ? main[0] : null;
103
+ }
104
+
105
+ // Directory children worth searching: no dot-folders, no node_modules.
106
+ function childDirs(dir) {
107
+ try {
108
+ return fs.readdirSync(dir, { withFileTypes: true })
109
+ .filter(e => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')
110
+ .map(e => path.join(dir, e.name));
111
+ } catch { return []; }
112
+ }
113
+
114
+ // The hint's folder no longer exists (typically a worktree removed after its branch merged). Search
115
+ // two levels below the parent of its nearest surviving ancestor, kept inside HOME, for the file.
116
+ function searchAroundGoneHint(hint, p, matches, searched) {
117
+ let survivor = path.dirname(hint);
118
+ while (!exists(survivor) && survivor !== path.dirname(survivor)) survivor = path.dirname(survivor);
119
+ const insideHome = d => d.startsWith(HOME + path.sep);
120
+ const base = insideHome(path.dirname(survivor)) ? path.dirname(survivor) : insideHome(survivor) ? survivor : null;
121
+ if (!base || searched.has(base)) return;
122
+ searched.add(base);
123
+ let budget = MAX_SEARCH_DIRS;
124
+ for (const child of childDirs(base)) {
125
+ if (--budget < 0) return;
126
+ addMatch(matches, path.join(child, p));
127
+ for (const grandchild of childDirs(child)) {
128
+ if (--budget < 0) return;
129
+ addMatch(matches, path.join(grandchild, p));
130
+ }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Where a file reference from chat points (specs/file-link-check.md in the clawchats repo).
136
+ * `~` is home and absolute paths stand as written. A relative path tries the session root, then
137
+ * the agent workspace. Failing those it tries every ancestor of each hint (absolute paths from
138
+ * the same turn's tool calls, e.g. a `cd` target); if none matches, hints whose folder is gone get
139
+ * a bounded search near where they were. Ties go to a git main checkout (pickMatch).
140
+ * Returns the absolute path, or null.
141
+ */
142
+ export function resolveReadPath(filePath, { roots = [], hints = [] } = {}) {
143
+ const p = filePath.replace(/^~(?=\/|$)/, HOME);
144
+ if (path.isAbsolute(p)) return isFile(p) ? path.resolve(p) : null;
145
+ for (const root of roots) {
146
+ if (!root) continue;
147
+ const candidate = path.resolve(root, p);
148
+ if (isFile(candidate)) return candidate;
149
+ }
150
+ const absHints = [...new Set(hints.slice(0, MAX_HINTS)
151
+ .map(h => h.replace(/^~(?=\/|$)/, HOME))
152
+ .filter(h => path.isAbsolute(h))
153
+ .map(h => path.resolve(h)))];
154
+ const matches = new Map(); // real path -> path as found
155
+ const tried = new Set();
156
+ for (const hint of absHints) {
157
+ for (let dir = hint; ; dir = path.dirname(dir)) {
158
+ if (!tried.has(dir)) {
159
+ tried.add(dir);
160
+ addMatch(matches, path.resolve(dir, p));
161
+ }
162
+ if (dir === path.dirname(dir)) break;
163
+ }
164
+ }
165
+ if (matches.size) return pickMatch(matches);
166
+ const searched = new Set();
167
+ for (const hint of absHints) {
168
+ if (!exists(hint)) searchAroundGoneHint(hint, p, matches, searched);
169
+ }
170
+ return pickMatch(matches);
171
+ }
172
+
71
173
  // Reads any file the gateway user can read (file links in chat open any path, as the agent
72
- // wrote it): `~` is home, relative paths resolve against the agent workspace. Writes and
73
- // deletes stay limited to HOME.
74
- export function handleWorkspaceFileRead(req, res, query, workspaceDir) {
174
+ // wrote it); resolution in resolveReadPath. `stat=1` answers {path, size} instead of the
175
+ // content, so a click can check a link before opening the pane. `hints` is newline-separated.
176
+ // Writes and deletes stay limited to HOME.
177
+ export function handleWorkspaceFileRead(req, res, query, workspaceDir, sessionRoot = null) {
75
178
  const filePath = query.path;
76
179
  if (!filePath) return sendError(res, 400, 'Missing path parameter');
77
- const resolved = path.resolve(workspaceDir, filePath.replace(/^~(?=\/|$)/, HOME));
78
- if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) return sendError(res, 404, 'File not found');
180
+ const hints = query.hints ? query.hints.split('\n').filter(Boolean) : [];
181
+ const resolved = resolveReadPath(filePath, { roots: [sessionRoot, workspaceDir], hints });
182
+ if (!resolved) return sendError(res, 404, 'File not found');
79
183
 
80
184
  const stat = fs.statSync(resolved);
185
+ if (query.stat) return send(res, 200, { path: resolved, size: stat.size });
81
186
  const ext = path.extname(resolved).toLowerCase().slice(1);
82
187
  const binaryMime = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', bmp: 'image/bmp', ico: 'image/x-icon', pdf: 'application/pdf', mp3: 'audio/mpeg', mp4: 'video/mp4', wav: 'audio/wav', ogg: 'audio/ogg', webm: 'video/webm' };
83
188
  const mime = binaryMime[ext];
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
3
3
  import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
- import { handleWorkspaceFileRead, handleWorkspaceCreate } from './filesystem.js';
6
+ import { handleWorkspaceFileRead, handleWorkspaceCreate, resolveReadPath } from './filesystem.js';
7
7
 
8
8
  function read(filePath, workspaceDir) {
9
9
  const out = { status: 0, body: '' };
@@ -47,6 +47,87 @@ test('file reads: ~/ expands to home', () => {
47
47
  }
48
48
  });
49
49
 
50
+ test('resolveReadPath: session root before workspace, then a unique match under a hint ancestor', () => {
51
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-resolve-'));
52
+ const mk = (rel, body = rel) => { const f = path.join(base, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, body); return f; };
53
+ const inSession = mk('session/src/a.ts');
54
+ mk('ws/src/a.ts');
55
+ const inRepo = mk('repos/up/ui/src/pages/p.ts');
56
+ mk('repos/up/ui/src/pages/deep/x.md');
57
+ mk('one/lib/dup.ts');
58
+ mk('two/lib/dup.ts');
59
+ const roots = [path.join(base, 'session'), path.join(base, 'ws')];
60
+ try {
61
+ assert.equal(resolveReadPath('src/a.ts', { roots }), inSession);
62
+ assert.equal(resolveReadPath('src/a.ts', { roots: [null, path.join(base, 'ws')] }), path.join(base, 'ws/src/a.ts'));
63
+ assert.equal(resolveReadPath(inRepo, { roots }), inRepo);
64
+ assert.equal(resolveReadPath('ui/src/pages/p.ts', { roots }), null);
65
+ // The agent `cd`'d deep into the repo; the repo root is an ancestor of the hint.
66
+ assert.equal(resolveReadPath('ui/src/pages/p.ts', { roots, hints: [path.join(base, 'repos/up/ui/src/pages/deep')] }), inRepo);
67
+ // Two different files match: ambiguous, not found.
68
+ assert.equal(resolveReadPath('lib/dup.ts', { roots, hints: [path.join(base, 'one/lib'), path.join(base, 'two')] }), null);
69
+ // Relative hints are ignored.
70
+ assert.equal(resolveReadPath('ui/src/pages/p.ts', { roots, hints: ['repos/up'] }), null);
71
+ } finally {
72
+ fs.rmSync(base, { recursive: true, force: true });
73
+ }
74
+ });
75
+
76
+ test('resolveReadPath: a hint into a removed worktree finds the file in the main checkout', () => {
77
+ // Searches stay inside HOME, so this layout lives there.
78
+ const base = fs.mkdtempSync(path.join(os.homedir(), '.cc-gone-'));
79
+ const mk = (rel, body = rel) => { const f = path.join(base, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, body); return f; };
80
+ fs.mkdirSync(path.join(base, 'repos/app/.git'), { recursive: true });
81
+ const main = mk('repos/app/known-gaps/q.md');
82
+ // Another chat's live worktree of the same repo has a copy (linked worktree: `.git` is a file).
83
+ mk('repos/worktrees/app-other/.git', 'gitdir: elsewhere');
84
+ mk('repos/worktrees/app-other/known-gaps/q.md');
85
+ const gone = path.join(base, 'repos/worktrees/app-queue/frontend');
86
+ try {
87
+ assert.equal(resolveReadPath('known-gaps/q.md', { hints: [gone] }), main);
88
+ // Two main checkouts with the file: ambiguous.
89
+ fs.mkdirSync(path.join(base, 'repos/fork/.git'), { recursive: true });
90
+ mk('repos/fork/known-gaps/q.md');
91
+ assert.equal(resolveReadPath('known-gaps/q.md', { hints: [gone] }), null);
92
+ // Hints that still exist never trigger the search.
93
+ assert.equal(resolveReadPath('known-gaps/q.md', { hints: [path.join(base, 'repos/worktrees')] }), null);
94
+ } finally {
95
+ fs.rmSync(base, { recursive: true, force: true });
96
+ }
97
+ });
98
+
99
+ test('resolveReadPath: several hint matches prefer the git main checkout', () => {
100
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-tie-'));
101
+ const mk = (rel, body = rel) => { const f = path.join(base, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, body); return f; };
102
+ fs.mkdirSync(path.join(base, 'app/.git'), { recursive: true });
103
+ const main = mk('app/src/a.js');
104
+ mk('wt/.git', 'gitdir: elsewhere');
105
+ mk('wt/src/a.js');
106
+ try {
107
+ assert.equal(resolveReadPath('src/a.js', { hints: [path.join(base, 'app/lib'), path.join(base, 'wt/lib')] }), main);
108
+ } finally {
109
+ fs.rmSync(base, { recursive: true, force: true });
110
+ }
111
+ });
112
+
113
+ test('file reads: stat=1 answers the resolved path and size; hints arrive newline-separated', () => {
114
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-stat-'));
115
+ const f = path.join(base, 'repo/docs/n.md');
116
+ fs.mkdirSync(path.dirname(f), { recursive: true });
117
+ fs.writeFileSync(f, 'hello');
118
+ const out = { status: 0, body: '' };
119
+ const res = { writeHead(s) { out.status = s; }, setHeader() {}, end(b) { out.body = String(b ?? ''); } };
120
+ try {
121
+ handleWorkspaceFileRead({}, res, { path: 'docs/n.md', stat: '1', hints: `/nonexistent\n${path.join(base, 'repo/docs')}` }, '/nonexistent-ws');
122
+ assert.equal(out.status, 200);
123
+ assert.deepEqual(JSON.parse(out.body), { path: f, size: 5 });
124
+ handleWorkspaceFileRead({}, res, { path: 'docs/gone.md', stat: '1' }, base, path.join(base, 'repo'));
125
+ assert.equal(out.status, 404);
126
+ } finally {
127
+ fs.rmSync(base, { recursive: true, force: true });
128
+ }
129
+ });
130
+
50
131
  function create(query) {
51
132
  const out = { status: 0, body: null };
52
133
  const res = {
package/server/index.js CHANGED
@@ -72,6 +72,21 @@ export function createApp(config = {}) {
72
72
  catch (e) { console.error('[extras] style seed failed:', e.message); }
73
73
  gatewayClient.lens = new SessionLens({ broadcast, request: (m, p, t) => gatewayClient.request(m, p, t), extras });
74
74
 
75
+ // A session's working root, for relative file links (gateway resolveSessionWorkspaceRoots:
76
+ // spawnedCwd before sessionRoot). Cached briefly; null when the gateway can't say.
77
+ const sessionRoots = new Map(); // key -> { root, at }
78
+ async function sessionRoot(key) {
79
+ const hit = sessionRoots.get(key);
80
+ if (hit && Date.now() - hit.at < 60_000) return hit.root;
81
+ let root = null;
82
+ try {
83
+ const s = (await gatewayClient.request('sessions.describe', { key }, 5000))?.session;
84
+ root = s?.spawnedCwd || s?.sessionRoot || null;
85
+ } catch { /* fall back to the workspace */ }
86
+ sessionRoots.set(key, { root, at: Date.now() });
87
+ return root;
88
+ }
89
+
75
90
  // Instantiate controllers
76
91
  const handleGatewayMedia = createGatewayMediaHandler({ gatewayWsUrl: gatewayUrl, gatewayToken });
77
92
 
@@ -153,7 +168,7 @@ export function createApp(config = {}) {
153
168
  if (method === 'GET' && urlPath === '/api/file') return handleServeFile(req, res, query, workspaceDir);
154
169
  if (method === 'GET' && urlPath === '/api/gw-media') return handleGatewayMedia(req, res, query);
155
170
  if (method === 'GET' && urlPath === '/api/workspace') return handleWorkspaceList(req, res, query);
156
- if (method === 'GET' && urlPath === '/api/workspace/file') return handleWorkspaceFileRead(req, res, query, workspaceDir);
171
+ if (method === 'GET' && urlPath === '/api/workspace/file') return handleWorkspaceFileRead(req, res, query, workspaceDir, query.session ? await sessionRoot(query.session) : null);
157
172
  if (method === 'PUT' && urlPath === '/api/workspace/file') return await handleWorkspaceFileWrite(req, res, query);
158
173
  if (method === 'DELETE' && urlPath === '/api/workspace/file') return handleWorkspaceFileDelete(req, res, query);
159
174
  if (method === 'POST' && urlPath === '/api/workspace/upload') return await handleWorkspaceUpload(req, res, query);