@myrialabs/clopen 0.3.9 → 0.3.11

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 (48) hide show
  1. package/README.md +22 -19
  2. package/backend/auth/auth-service.ts +56 -1
  3. package/backend/auth/permissions.test.ts +30 -0
  4. package/backend/auth/permissions.ts +28 -1
  5. package/backend/auth/session-cleanup.ts +58 -0
  6. package/backend/chat/stream-manager.ts +72 -13
  7. package/backend/db-client/connection-manager.ts +9 -3
  8. package/backend/engine/adapters/codex/error-handler.ts +2 -2
  9. package/backend/engine/adapters/codex/stream.ts +12 -8
  10. package/backend/engine/adapters/copilot/stream.ts +5 -8
  11. package/backend/engine/adapters/opencode/presets.ts +1 -1
  12. package/backend/engine/adapters/opencode/stream.ts +5 -1
  13. package/backend/engine/adapters/qwen/stream.ts +1 -2
  14. package/backend/files/path-browsing.ts +20 -0
  15. package/backend/git/git-service.ts +81 -11
  16. package/backend/git/git-spawn-validation.test.ts +75 -0
  17. package/backend/git/git-spawn-validation.ts +77 -0
  18. package/backend/index.ts +5 -0
  19. package/backend/preview/browser/browser-tab-manager.ts +23 -3
  20. package/backend/snapshot/gitignore.ts +4 -9
  21. package/backend/tunnel/cloudflared/binary.ts +2 -2
  22. package/backend/tunnel/global-tunnel-manager.ts +9 -3
  23. package/backend/utils/ws.ts +5 -1
  24. package/backend/ws/access.ts +5 -5
  25. package/backend/ws/auth/index.ts +14 -0
  26. package/backend/ws/auth/login.ts +3 -0
  27. package/backend/ws/auth/users.ts +61 -1
  28. package/backend/ws/chat/stream.ts +103 -10
  29. package/backend/ws/db-client/query.ts +3 -1
  30. package/backend/ws/files/path-access.ts +101 -0
  31. package/backend/ws/files/read.ts +35 -12
  32. package/backend/ws/files/search.ts +10 -6
  33. package/backend/ws/files/watch.ts +1 -1
  34. package/backend/ws/files/write.ts +109 -15
  35. package/backend/ws/preview/browser/console.ts +2 -2
  36. package/backend/ws/projects/crud.ts +15 -7
  37. package/backend/ws/projects/status.ts +3 -1
  38. package/backend/ws/sessions/crud.ts +10 -4
  39. package/backend/ws/terminal/access.ts +3 -3
  40. package/backend/ws/terminal/persistence.ts +1 -1
  41. package/backend/ws/terminal/session.ts +2 -2
  42. package/dist/assets/{index-D8V2wj9B.js → index-DmghE6mf.js} +2 -2
  43. package/dist/assets/main-DiDuzJJh.js +318 -0
  44. package/dist/assets/main-N1w7Llvp.css +1 -0
  45. package/dist/index.html +2 -2
  46. package/package.json +2 -1
  47. package/dist/assets/main-C9nYVmnw.js +0 -312
  48. package/dist/assets/main-hspyFOoK.css +0 -1
@@ -24,6 +24,14 @@ import type {
24
24
  GitConflictFile
25
25
  } from '$shared/types/git';
26
26
  import { debug } from '$shared/utils/logger';
27
+ import {
28
+ assertSafeGitCommitMessage,
29
+ assertSafeGitPathOperand,
30
+ assertSafeGitRemoteName,
31
+ assertSafeGitRemoteUrl,
32
+ assertSafeGitRevish,
33
+ assertSafeGitShowRef
34
+ } from './git-spawn-validation';
27
35
 
28
36
  export class GitService {
29
37
  /**
@@ -45,7 +53,10 @@ export class GitService {
45
53
  */
46
54
  async init(cwd: string, defaultBranch?: string): Promise<void> {
47
55
  const args = ['init'];
48
- if (defaultBranch) args.push('-b', defaultBranch);
56
+ if (defaultBranch) {
57
+ assertSafeGitRevish(defaultBranch, 'default branch');
58
+ args.push('-b', defaultBranch);
59
+ }
49
60
  const result = await execGit(args, cwd);
50
61
  if (result.exitCode !== 0) {
51
62
  throw new Error(`git init failed: ${result.stderr}`);
@@ -69,6 +80,7 @@ export class GitService {
69
80
  // ============================================
70
81
 
71
82
  async stageFile(cwd: string, filePath: string): Promise<void> {
83
+ assertSafeGitPathOperand(filePath, 'stage path');
72
84
  const result = await execGit(['add', '--', filePath], cwd);
73
85
  if (result.exitCode !== 0) {
74
86
  throw new Error(`git add failed: ${result.stderr}`);
@@ -83,10 +95,11 @@ export class GitService {
83
95
  }
84
96
 
85
97
  async unstageFile(cwd: string, filePath: string): Promise<void> {
98
+ assertSafeGitPathOperand(filePath, 'unstage path');
86
99
  // Try normal reset first, fall back to rm --cached for initial commit
87
100
  const result = await execGit(['reset', 'HEAD', '--', filePath], cwd);
88
101
  if (result.exitCode !== 0) {
89
- const fallback = await execGit(['rm', '--cached', '--', filePath], cwd);
102
+ const fallback = await execGit(['rm', '--cached', '--', filePath], cwd); // filePath validated above
90
103
  if (fallback.exitCode !== 0) {
91
104
  throw new Error(`git unstage failed: ${result.stderr}`);
92
105
  }
@@ -105,6 +118,7 @@ export class GitService {
105
118
  }
106
119
 
107
120
  async discardFile(cwd: string, filePath: string): Promise<void> {
121
+ assertSafeGitPathOperand(filePath, 'discard path');
108
122
  // Check if file is untracked
109
123
  const statusResult = await execGit(['status', '--porcelain=v1', '--', filePath], cwd);
110
124
  const statusLine = statusResult.stdout.trim();
@@ -135,6 +149,7 @@ export class GitService {
135
149
  // ============================================
136
150
 
137
151
  async commit(cwd: string, message: string): Promise<string> {
152
+ assertSafeGitCommitMessage(message);
138
153
  const result = await execGit(['commit', '-m', message], cwd);
139
154
  if (result.exitCode !== 0) {
140
155
  throw new Error(`git commit failed: ${result.stderr}`);
@@ -147,6 +162,7 @@ export class GitService {
147
162
  async amendCommit(cwd: string, message?: string): Promise<string> {
148
163
  const args = ['commit', '--amend'];
149
164
  if (message) {
165
+ assertSafeGitCommitMessage(message);
150
166
  args.push('-m', message);
151
167
  } else {
152
168
  args.push('--no-edit');
@@ -165,24 +181,33 @@ export class GitService {
165
181
 
166
182
  async getDiffUnstaged(cwd: string, filePath?: string): Promise<GitFileDiff[]> {
167
183
  const args = ['diff'];
168
- if (filePath) args.push('--', filePath);
184
+ if (filePath) {
185
+ assertSafeGitPathOperand(filePath, 'diff path');
186
+ args.push('--', filePath);
187
+ }
169
188
  const result = await execGit(args, cwd);
170
189
  return parseDiff(result.stdout);
171
190
  }
172
191
 
173
192
  async getDiffStaged(cwd: string, filePath?: string): Promise<GitFileDiff[]> {
174
193
  const args = ['diff', '--cached'];
175
- if (filePath) args.push('--', filePath);
194
+ if (filePath) {
195
+ assertSafeGitPathOperand(filePath, 'diff path');
196
+ args.push('--', filePath);
197
+ }
176
198
  const result = await execGit(args, cwd);
177
199
  return parseDiff(result.stdout);
178
200
  }
179
201
 
180
202
  async getDiffCommit(cwd: string, commitHash: string): Promise<GitFileDiff[]> {
203
+ assertSafeGitRevish(commitHash, 'commit hash');
181
204
  const result = await execGit(['diff', `${commitHash}^`, commitHash], cwd);
182
205
  return parseDiff(result.stdout);
183
206
  }
184
207
 
185
208
  async getDiffBetween(cwd: string, from: string, to: string): Promise<GitFileDiff[]> {
209
+ assertSafeGitRevish(from, 'diff from');
210
+ assertSafeGitRevish(to, 'diff to');
186
211
  const result = await execGit(['diff', from, to], cwd);
187
212
  return parseDiff(result.stdout);
188
213
  }
@@ -192,6 +217,8 @@ export class GitService {
192
217
  * Returns null when the file does not exist at that ref (untracked / new file).
193
218
  */
194
219
  async getFileAtRef(cwd: string, ref: string, filePath: string): Promise<string | null> {
220
+ assertSafeGitShowRef(ref);
221
+ assertSafeGitPathOperand(filePath, 'show path');
195
222
  const result = await execGit(['show', `${ref}:${filePath}`], cwd);
196
223
  if (result.exitCode !== 0) {
197
224
  return null;
@@ -247,8 +274,12 @@ export class GitService {
247
274
  }
248
275
 
249
276
  async createBranch(cwd: string, name: string, startPoint?: string): Promise<void> {
277
+ assertSafeGitRevish(name, 'branch name');
250
278
  const args = ['checkout', '-b', name];
251
- if (startPoint) args.push(startPoint);
279
+ if (startPoint) {
280
+ assertSafeGitRevish(startPoint, 'start point');
281
+ args.push(startPoint);
282
+ }
252
283
  const result = await execGit(args, cwd);
253
284
  if (result.exitCode !== 0) {
254
285
  throw new Error(`git checkout -b failed: ${result.stderr}`);
@@ -256,6 +287,7 @@ export class GitService {
256
287
  }
257
288
 
258
289
  async switchBranch(cwd: string, name: string): Promise<void> {
290
+ assertSafeGitRevish(name, 'branch name');
259
291
  const result = await execGit(['checkout', name], cwd);
260
292
  if (result.exitCode !== 0) {
261
293
  throw new Error(`git checkout failed: ${result.stderr}`);
@@ -263,6 +295,7 @@ export class GitService {
263
295
  }
264
296
 
265
297
  async deleteBranch(cwd: string, name: string, force = false): Promise<void> {
298
+ assertSafeGitRevish(name, 'branch name');
266
299
  const flag = force ? '-D' : '-d';
267
300
  const result = await execGit(['branch', flag, name], cwd);
268
301
  if (result.exitCode !== 0) {
@@ -271,6 +304,8 @@ export class GitService {
271
304
  }
272
305
 
273
306
  async renameBranch(cwd: string, oldName: string, newName: string): Promise<void> {
307
+ assertSafeGitRevish(oldName, 'old branch name');
308
+ assertSafeGitRevish(newName, 'new branch name');
274
309
  const result = await execGit(['branch', '-m', oldName, newName], cwd);
275
310
  if (result.exitCode !== 0) {
276
311
  throw new Error(`git branch -m failed: ${result.stderr}`);
@@ -278,6 +313,7 @@ export class GitService {
278
313
  }
279
314
 
280
315
  async mergeBranch(cwd: string, branchName: string): Promise<{ success: boolean; message: string }> {
316
+ assertSafeGitRevish(branchName, 'merge branch');
281
317
  const result = await execGit(['merge', branchName], cwd);
282
318
  return {
283
319
  success: result.exitCode === 0,
@@ -301,7 +337,10 @@ export class GitService {
301
337
  `--skip=${skip}`
302
338
  ];
303
339
 
304
- if (branch) args.push(branch);
340
+ if (branch) {
341
+ assertSafeGitRevish(branch, 'log branch');
342
+ args.push(branch);
343
+ }
305
344
 
306
345
  const result = await execGit(args, cwd);
307
346
  if (result.exitCode !== 0) {
@@ -313,7 +352,8 @@ export class GitService {
313
352
  if (hasMore) commits.pop(); // Remove the extra one
314
353
 
315
354
  // Get total count
316
- const countResult = await execGit(['rev-list', '--count', branch || 'HEAD'], cwd);
355
+ const countRef = branch ?? 'HEAD';
356
+ const countResult = await execGit(['rev-list', '--count', countRef], cwd);
317
357
  const total = parseInt(countResult.stdout.trim()) || commits.length;
318
358
 
319
359
  return { commits, total, hasMore };
@@ -329,6 +369,7 @@ export class GitService {
329
369
  }
330
370
 
331
371
  async fetch(cwd: string, remote = 'origin'): Promise<string> {
372
+ assertSafeGitRemoteName(remote);
332
373
  // Use explicit refspec to ensure all branches are fetched regardless of clone config
333
374
  const result = await execGit(['fetch', remote, `+refs/heads/*:refs/remotes/${remote}/*`, '--prune'], cwd, 60000);
334
375
  if (result.exitCode !== 0) {
@@ -338,8 +379,12 @@ export class GitService {
338
379
  }
339
380
 
340
381
  async pull(cwd: string, remote = 'origin', branch?: string): Promise<{ success: boolean; message: string }> {
382
+ assertSafeGitRemoteName(remote);
341
383
  const args = ['pull', remote];
342
- if (branch) args.push(branch);
384
+ if (branch) {
385
+ assertSafeGitRevish(branch, 'pull branch');
386
+ args.push(branch);
387
+ }
343
388
  const result = await execGit(args, cwd, 60000);
344
389
  return {
345
390
  success: result.exitCode === 0,
@@ -348,8 +393,12 @@ export class GitService {
348
393
  }
349
394
 
350
395
  async push(cwd: string, remote = 'origin', branch?: string, force = false): Promise<{ success: boolean; message: string }> {
396
+ assertSafeGitRemoteName(remote);
351
397
  const args = ['push', remote];
352
- if (branch) args.push(branch);
398
+ if (branch) {
399
+ assertSafeGitRevish(branch, 'push branch');
400
+ args.push(branch);
401
+ }
353
402
  if (force) args.push('--force-with-lease');
354
403
  // Set upstream if needed
355
404
  args.push('-u');
@@ -361,6 +410,8 @@ export class GitService {
361
410
  }
362
411
 
363
412
  async addRemote(cwd: string, name: string, url: string): Promise<void> {
413
+ assertSafeGitRemoteName(name);
414
+ assertSafeGitRemoteUrl(url);
364
415
  const result = await execGit(['remote', 'add', name, url], cwd);
365
416
  if (result.exitCode !== 0) {
366
417
  throw new Error(`git remote add failed: ${result.stderr}`);
@@ -368,6 +419,7 @@ export class GitService {
368
419
  }
369
420
 
370
421
  async removeRemote(cwd: string, name: string): Promise<void> {
422
+ assertSafeGitRemoteName(name);
371
423
  const result = await execGit(['remote', 'remove', name], cwd);
372
424
  if (result.exitCode !== 0) {
373
425
  throw new Error(`git remote remove failed: ${result.stderr}`);
@@ -385,7 +437,10 @@ export class GitService {
385
437
 
386
438
  async stashSave(cwd: string, message?: string): Promise<void> {
387
439
  const args = ['stash', 'push'];
388
- if (message) args.push('-m', message);
440
+ if (message) {
441
+ assertSafeGitCommitMessage(message);
442
+ args.push('-m', message);
443
+ }
389
444
  const result = await execGit(args, cwd);
390
445
  if (result.exitCode !== 0) {
391
446
  throw new Error(`git stash failed: ${result.stderr}`);
@@ -393,6 +448,9 @@ export class GitService {
393
448
  }
394
449
 
395
450
  async stashPop(cwd: string, index = 0): Promise<void> {
451
+ if (!Number.isInteger(index) || index < 0) {
452
+ throw new Error('Invalid stash index');
453
+ }
396
454
  const result = await execGit(['stash', 'pop', `stash@{${index}}`], cwd);
397
455
  if (result.exitCode !== 0) {
398
456
  throw new Error(`git stash pop failed: ${result.stderr}`);
@@ -400,6 +458,9 @@ export class GitService {
400
458
  }
401
459
 
402
460
  async stashDrop(cwd: string, index = 0): Promise<void> {
461
+ if (!Number.isInteger(index) || index < 0) {
462
+ throw new Error('Invalid stash index');
463
+ }
403
464
  const result = await execGit(['stash', 'drop', `stash@{${index}}`], cwd);
404
465
  if (result.exitCode !== 0) {
405
466
  throw new Error(`git stash drop failed: ${result.stderr}`);
@@ -435,13 +496,18 @@ export class GitService {
435
496
  }
436
497
 
437
498
  async createTag(cwd: string, name: string, message?: string, commitHash?: string): Promise<void> {
499
+ assertSafeGitRevish(name, 'tag name');
438
500
  const args = ['tag'];
439
501
  if (message) {
502
+ assertSafeGitCommitMessage(message);
440
503
  args.push('-a', name, '-m', message);
441
504
  } else {
442
505
  args.push(name);
443
506
  }
444
- if (commitHash) args.push(commitHash);
507
+ if (commitHash) {
508
+ assertSafeGitRevish(commitHash, 'tag target');
509
+ args.push(commitHash);
510
+ }
445
511
  const result = await execGit(args, cwd);
446
512
  if (result.exitCode !== 0) {
447
513
  throw new Error(`git tag failed: ${result.stderr}`);
@@ -449,6 +515,7 @@ export class GitService {
449
515
  }
450
516
 
451
517
  async deleteTag(cwd: string, name: string): Promise<void> {
518
+ assertSafeGitRevish(name, 'tag name');
452
519
  const result = await execGit(['tag', '-d', name], cwd);
453
520
  if (result.exitCode !== 0) {
454
521
  throw new Error(`git tag -d failed: ${result.stderr}`);
@@ -456,6 +523,8 @@ export class GitService {
456
523
  }
457
524
 
458
525
  async pushTag(cwd: string, name: string, remote = 'origin'): Promise<{ success: boolean; message: string }> {
526
+ assertSafeGitRemoteName(remote);
527
+ assertSafeGitRevish(name, 'tag name');
459
528
  const result = await execGit(['push', remote, name], cwd, 60000);
460
529
  return {
461
530
  success: result.exitCode === 0,
@@ -492,6 +561,7 @@ export class GitService {
492
561
  resolution: 'ours' | 'theirs' | 'custom',
493
562
  customContent?: string
494
563
  ): Promise<void> {
564
+ assertSafeGitPathOperand(filePath, 'conflict path');
495
565
  if (resolution === 'custom' && customContent !== undefined) {
496
566
  // Write custom content
497
567
  const { writeFile } = await import('node:fs/promises');
@@ -0,0 +1,75 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import {
3
+ assertSafeGitCommitMessage,
4
+ assertSafeGitPathOperand,
5
+ assertSafeGitRemoteName,
6
+ assertSafeGitRemoteUrl,
7
+ assertSafeGitRevish,
8
+ assertSafeGitShowRef
9
+ } from './git-spawn-validation';
10
+
11
+ describe('assertSafeGitRevish', () => {
12
+ test('accepts typical branch and hash tokens', () => {
13
+ expect(() => assertSafeGitRevish('main', 'x')).not.toThrow();
14
+ expect(() => assertSafeGitRevish('feature/foo-bar', 'x')).not.toThrow();
15
+ expect(() => assertSafeGitRevish('abc123deadbeef', 'x')).not.toThrow();
16
+ expect(() => assertSafeGitRevish('HEAD', 'x')).not.toThrow();
17
+ });
18
+
19
+ test('rejects option-shaped values', () => {
20
+ expect(() => assertSafeGitRevish('--output=/tmp/pwn', 'branch')).toThrow(/must not start/);
21
+ expect(() => assertSafeGitRevish('-c', 'branch')).toThrow(/must not start/);
22
+ });
23
+
24
+ test('rejects NUL and newlines', () => {
25
+ expect(() => assertSafeGitRevish('a\nb', 'branch')).toThrow();
26
+ expect(() => assertSafeGitRevish('a\0b', 'branch')).toThrow();
27
+ });
28
+ });
29
+
30
+ describe('assertSafeGitRemoteName', () => {
31
+ test('accepts origin', () => {
32
+ expect(() => assertSafeGitRemoteName('origin')).not.toThrow();
33
+ });
34
+
35
+ test('rejects spaces and specials', () => {
36
+ expect(() => assertSafeGitRemoteName('my remote')).toThrow(/Invalid git remote name/);
37
+ expect(() => assertSafeGitRemoteName('-bad')).toThrow();
38
+ });
39
+ });
40
+
41
+ describe('assertSafeGitRemoteUrl', () => {
42
+ test('accepts normal https url', () => {
43
+ expect(() => assertSafeGitRemoteUrl('https://github.com/foo/bar.git')).not.toThrow();
44
+ });
45
+
46
+ test('rejects argv injection prefix', () => {
47
+ expect(() => assertSafeGitRemoteUrl('-force evil')).toThrow();
48
+ });
49
+ });
50
+
51
+ describe('assertSafeGitShowRef', () => {
52
+ test('rejects colon in ref', () => {
53
+ expect(() => assertSafeGitShowRef('HEAD:readme')).toThrow(/must not contain/);
54
+ });
55
+ });
56
+
57
+ describe('assertSafeGitPathOperand', () => {
58
+ test('allows normal relative paths', () => {
59
+ expect(() => assertSafeGitPathOperand('src/index.ts')).not.toThrow();
60
+ });
61
+
62
+ test('rejects newlines', () => {
63
+ expect(() => assertSafeGitPathOperand('a\nb')).toThrow();
64
+ });
65
+ });
66
+
67
+ describe('assertSafeGitCommitMessage', () => {
68
+ test('allows multiline messages', () => {
69
+ expect(() => assertSafeGitCommitMessage('line1\nline2')).not.toThrow();
70
+ });
71
+
72
+ test('rejects NUL', () => {
73
+ expect(() => assertSafeGitCommitMessage('a\0b')).toThrow();
74
+ });
75
+ });
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Guards for values passed into git CLI argv arrays.
3
+ *
4
+ * Bun.spawn / execGit use argv mode (no shell), but git itself still parses
5
+ * leading `-` tokens as options. User-controlled branch / remote / ref names
6
+ * must therefore be rejected when they look like flags.
7
+ */
8
+
9
+ const MAX_GIT_ARG = 8192;
10
+ const MAX_COMMIT_MESSAGE = 256 * 1024;
11
+
12
+ /** Branch names, tag names, commit-ish, remote names in refspecs, etc. */
13
+ export function assertSafeGitRevish(value: string, label: string): void {
14
+ if (value.length === 0) {
15
+ throw new Error(`${label}: value must not be empty`);
16
+ }
17
+ if (value.length > MAX_GIT_ARG) {
18
+ throw new Error(`${label}: value too long`);
19
+ }
20
+ if (/[\0\n\r]/.test(value)) {
21
+ throw new Error(`${label}: invalid control characters`);
22
+ }
23
+ if (value.startsWith('-')) {
24
+ throw new Error(`${label}: must not start with '-' (git option injection)`);
25
+ }
26
+ }
27
+
28
+ /** `git remote` names are a small charset in practice; keep strict. */
29
+ export function assertSafeGitRemoteName(name: string): void {
30
+ assertSafeGitRevish(name, 'remote name');
31
+ if (!/^[A-Za-z0-9._-]+$/.test(name)) {
32
+ throw new Error('Invalid git remote name');
33
+ }
34
+ }
35
+
36
+ /** `git remote add <name> <url>` — avoid NUL/newline and argv-shaped URLs. */
37
+ export function assertSafeGitRemoteUrl(url: string): void {
38
+ if (url.length === 0) {
39
+ throw new Error('remote URL must not be empty');
40
+ }
41
+ if (url.length > MAX_GIT_ARG * 8) {
42
+ throw new Error('remote URL too long');
43
+ }
44
+ if (/[\0\n\r]/.test(url)) {
45
+ throw new Error('remote URL contains invalid characters');
46
+ }
47
+ if (url.startsWith('-')) {
48
+ throw new Error('remote URL must not start with "-"');
49
+ }
50
+ }
51
+
52
+ /** Paths appended after `--` in git argv (still reject NUL / newlines). */
53
+ export function assertSafeGitPathOperand(path: string, label = 'path'): void {
54
+ if (path.length > MAX_GIT_ARG) {
55
+ throw new Error(`${label}: path too long`);
56
+ }
57
+ if (/[\0\n\r]/.test(path)) {
58
+ throw new Error(`${label}: invalid path characters`);
59
+ }
60
+ }
61
+
62
+ export function assertSafeGitCommitMessage(message: string): void {
63
+ if (message.length > MAX_COMMIT_MESSAGE) {
64
+ throw new Error('commit message too long');
65
+ }
66
+ if (message.includes('\0')) {
67
+ throw new Error('commit message contains NUL byte');
68
+ }
69
+ }
70
+
71
+ /** `ref` side of `git show rev:path` — disallow `:` so `rev` stays unambiguous. */
72
+ export function assertSafeGitShowRef(ref: string): void {
73
+ assertSafeGitRevish(ref, 'git ref');
74
+ if (ref.includes(':')) {
75
+ throw new Error('git ref for show must not contain ":"');
76
+ }
77
+ }
package/backend/index.ts CHANGED
@@ -37,6 +37,7 @@ import { handleMcpRequest, closeMcpServer } from './mcp/remote-server';
37
37
  // Auth middleware
38
38
  import { checkRouteAccess } from './auth/permissions';
39
39
  import { authRateLimiter } from './auth';
40
+ import { sessionCleanupScheduler } from './auth/session-cleanup';
40
41
  import { ws as wsServer } from './utils/ws';
41
42
 
42
43
  // Register auth gate on WebSocket router — blocks unauthenticated/unauthorized access
@@ -141,6 +142,8 @@ async function startServer() {
141
142
  try {
142
143
  await initializeDatabase();
143
144
  debug.log('database', '✅ Database initialized successfully');
145
+ // Start expired session cleanup now that the database is ready
146
+ sessionCleanupScheduler.start();
144
147
  } catch (error) {
145
148
  debug.warn('database', '⚠️ Database initialization failed:', error);
146
149
  }
@@ -189,6 +192,8 @@ async function gracefulShutdown() {
189
192
  app.stop();
190
193
  // Dispose rate limiter timer
191
194
  authRateLimiter.dispose();
195
+ // Dispose expired session cleanup timer
196
+ sessionCleanupScheduler.dispose();
192
197
  // Close MCP remote server (before engines, as they may still reference it)
193
198
  await closeMcpServer();
194
199
  // Cleanup browser preview sessions
@@ -44,6 +44,7 @@ export class BrowserTabManager extends EventEmitter {
44
44
  // Tab activity tracking for cleanup
45
45
  private tabActivity = new Map<string, number>();
46
46
  private cleanupInterval: NodeJS.Timeout | null = null;
47
+ private signalHandlers: { sigterm: () => void; sigint: () => void } | null = null;
47
48
 
48
49
  // Audio capture manager
49
50
  private audioCapture = new BrowserAudioCapture();
@@ -1038,14 +1039,30 @@ export class BrowserTabManager extends EventEmitter {
1038
1039
  this.performCleanup();
1039
1040
  }, CLEANUP_INTERVAL);
1040
1041
 
1041
- // Cleanup on shutdown
1042
+ // Cleanup on shutdown — track references so we can remove them later
1043
+ // and prevent duplicate listeners if multiple BrowserTabManager
1044
+ // instances are created.
1042
1045
  const cleanup = () => {
1043
1046
  if (this.cleanupInterval) clearInterval(this.cleanupInterval);
1047
+ this.cleanupInterval = null;
1044
1048
  this.tabActivity.clear();
1049
+ this.removeSignalHandlers();
1045
1050
  };
1046
1051
 
1047
- process.on('SIGTERM', cleanup);
1048
- process.on('SIGINT', cleanup);
1052
+ this.signalHandlers = { sigterm: cleanup, sigint: cleanup };
1053
+ process.on('SIGTERM', this.signalHandlers.sigterm);
1054
+ process.on('SIGINT', this.signalHandlers.sigint);
1055
+ }
1056
+
1057
+ /**
1058
+ * Remove previously registered signal handlers to prevent leaks
1059
+ * when multiple BrowserTabManager instances are created.
1060
+ */
1061
+ private removeSignalHandlers(): void {
1062
+ if (!this.signalHandlers) return;
1063
+ process.off('SIGTERM', this.signalHandlers.sigterm);
1064
+ process.off('SIGINT', this.signalHandlers.sigint);
1065
+ this.signalHandlers = null;
1049
1066
  }
1050
1067
 
1051
1068
  /**
@@ -1148,6 +1165,9 @@ export class BrowserTabManager extends EventEmitter {
1148
1165
  this.cleanupInterval = null;
1149
1166
  }
1150
1167
 
1168
+ // Remove signal handlers to prevent leaks
1169
+ this.removeSignalHandlers();
1170
+
1151
1171
  const tabIds = Array.from(this.tabs.keys());
1152
1172
 
1153
1173
  if (tabIds.length > 0) {
@@ -11,6 +11,7 @@
11
11
  import fs from 'fs/promises';
12
12
  import path from 'path';
13
13
  import { debug } from '$shared/utils/logger';
14
+ import { execGit } from '../git/git-executor';
14
15
 
15
16
  /**
16
17
  * Safety-net directories to always exclude regardless of .gitignore.
@@ -49,15 +50,9 @@ async function scanWithGit(dirPath: string): Promise<string[] | null> {
49
50
  }
50
51
 
51
52
  try {
52
- const proc = Bun.spawn(
53
- ['git', 'ls-files', '-co', '--exclude-standard'],
54
- { cwd: dirPath, stdout: 'pipe', stderr: 'pipe' }
55
- );
56
-
57
- const output = await new Response(proc.stdout).text();
58
- const exitCode = await proc.exited;
59
-
60
- if (exitCode !== 0) return null;
53
+ const result = await execGit(['ls-files', '-co', '--exclude-standard'], dirPath, 60_000);
54
+ if (result.exitCode !== 0) return null;
55
+ const output = result.stdout;
61
56
 
62
57
  const files: string[] = [];
63
58
  for (const line of output.split('\n')) {
@@ -16,7 +16,7 @@
16
16
  import { existsSync, mkdirSync, createWriteStream, chmodSync, unlinkSync, renameSync } from 'fs';
17
17
  import { join, dirname } from 'path';
18
18
  import { platform, arch } from 'os';
19
- import { execSync } from 'child_process';
19
+ import { execFileSync } from 'child_process';
20
20
  import { getClopenDir } from '../../utils/paths';
21
21
  import { resolveBinary } from '../../utils/cli';
22
22
  import { debug } from '$shared/utils/logger';
@@ -148,7 +148,7 @@ export async function installBinary(version = 'latest'): Promise<string> {
148
148
  // macOS: download .tgz, extract, rename
149
149
  const tgzPath = `${binPath}.tgz`;
150
150
  await download(url, tgzPath);
151
- execSync(`tar -xzf ${tgzPath}`, { cwd: dirname(binPath) });
151
+ execFileSync('tar', ['-xzf', tgzPath], { cwd: dirname(binPath), stdio: 'pipe' });
152
152
  unlinkSync(tgzPath);
153
153
  // tar extracts as "cloudflared" in the same directory
154
154
  const extractedPath = join(dirname(binPath), 'cloudflared');
@@ -195,7 +195,9 @@ class GlobalTunnelManager {
195
195
  if (instance.autoStopTimer) clearTimeout(instance.autoStopTimer);
196
196
  try {
197
197
  instance.tunnel.stop();
198
- } catch { /* ignore */ }
198
+ } catch (err) {
199
+ debug.warn('tunnel', `Failed to stop quick tunnel on port ${port}:`, err);
200
+ }
199
201
  this.quickTunnels.delete(port);
200
202
  debug.log('tunnel', `Quick tunnel stopped on port ${port}`);
201
203
  this.notifyStatusChanged();
@@ -297,7 +299,9 @@ class GlobalTunnelManager {
297
299
 
298
300
  try {
299
301
  instance.tunnel.stop();
300
- } catch { /* ignore */ }
302
+ } catch (err) {
303
+ debug.warn('tunnel', `Failed to stop remote tunnel ${instance.label}:`, err);
304
+ }
301
305
  this.remoteTunnels.delete(configId);
302
306
  debug.log('tunnel', `Remote tunnel stopped: ${instance.label}`);
303
307
  this.notifyStatusChanged();
@@ -548,7 +552,9 @@ class GlobalTunnelManager {
548
552
 
549
553
  try {
550
554
  instance.tunnel.stop();
551
- } catch { /* ignore */ }
555
+ } catch (err) {
556
+ debug.warn('tunnel', `Failed to stop local tunnel ${instance.name}:`, err);
557
+ }
552
558
  this.localTunnels.delete(configId);
553
559
  debug.log('tunnel', `Local tunnel stopped: ${instance.name}`);
554
560
  this.notifyStatusChanged();
@@ -182,7 +182,11 @@ class WSServer {
182
182
  // Run all registered cleanup functions
183
183
  if (state?.cleanups.size) {
184
184
  for (const cleanup of state.cleanups) {
185
- try { cleanup(); } catch { /* ignore cleanup errors */ }
185
+ try {
186
+ cleanup();
187
+ } catch (err) {
188
+ debug.warn('websocket', `Cleanup error for connection ${id}:`, err);
189
+ }
186
190
  }
187
191
  debug.log('websocket', `Ran ${state.cleanups.size} cleanup(s) for connection ${id}`);
188
192
  }
@@ -7,12 +7,12 @@ export function requireProjectAccess(conn: WSConnection, projectId: string): Pro
7
7
  const userId = ws.getUserId(conn);
8
8
  const hasAccess = projectQueries.userHasProject(userId, projectId);
9
9
  if (!hasAccess) {
10
- throw new Error('Project not found');
10
+ throw new Error('Access denied');
11
11
  }
12
12
 
13
13
  const project = projectQueries.getById(projectId);
14
14
  if (!project) {
15
- throw new Error('Project not found');
15
+ throw new Error('Access denied');
16
16
  }
17
17
 
18
18
  return project;
@@ -32,13 +32,13 @@ export function requireCurrentProjectAccess(conn: WSConnection): {
32
32
  export function requireSessionAccess(conn: WSConnection, sessionId: string): ChatSession {
33
33
  const session = sessionQueries.getById(sessionId);
34
34
  if (!session) {
35
- throw new Error('Session not found');
35
+ throw new Error('Access denied');
36
36
  }
37
37
 
38
38
  const userId = ws.getUserId(conn);
39
39
  const hasAccess = projectQueries.userHasProject(userId, session.project_id);
40
40
  if (!hasAccess) {
41
- throw new Error('Session not found');
41
+ throw new Error('Access denied');
42
42
  }
43
43
 
44
44
  return session;
@@ -47,7 +47,7 @@ export function requireSessionAccess(conn: WSConnection, sessionId: string): Cha
47
47
  export function requireMessageAccess(conn: WSConnection, messageId: string): DatabaseMessage {
48
48
  const message = messageQueries.getById(messageId);
49
49
  if (!message) {
50
- throw new Error('Message not found');
50
+ throw new Error('Access denied');
51
51
  }
52
52
 
53
53
  // Message access inherits session access controls.