@myrialabs/clopen 0.4.32 → 0.4.34

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 (102) hide show
  1. package/backend/auth/permissions.ts +3 -0
  2. package/backend/auth/rate-limiter.test.ts +115 -0
  3. package/backend/auth/rate-limiter.ts +25 -12
  4. package/backend/chat/stream-manager.ts +4 -1
  5. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  8. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  9. package/backend/database/queries/index.ts +3 -0
  10. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  11. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  12. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  13. package/backend/db-client/connection-manager.ts +21 -1
  14. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  15. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  16. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  17. package/backend/engine/adapters/codex/stream.ts +33 -4
  18. package/backend/engine/adapters/copilot/stream.ts +1 -1
  19. package/backend/engine/adapters/cursor/stream.ts +1 -1
  20. package/backend/engine/adapters/qwen/stream.ts +1 -1
  21. package/backend/engine/docs/adapter-contract.md +7 -0
  22. package/backend/files/file-watcher.ts +283 -51
  23. package/backend/files/git-events.test.ts +110 -0
  24. package/backend/git/git-dirs.test.ts +132 -0
  25. package/backend/git/git-dirs.ts +0 -0
  26. package/backend/git/nested-repos.test.ts +108 -5
  27. package/backend/git/nested-repos.ts +103 -18
  28. package/backend/http/audio.ts +5 -32
  29. package/backend/http/bearer-auth.ts +47 -0
  30. package/backend/http/files-download.test.ts +146 -0
  31. package/backend/http/files-download.ts +109 -0
  32. package/backend/http/files-upload.ts +3 -29
  33. package/backend/http/ssh-sftp.ts +133 -0
  34. package/backend/index.ts +25 -2
  35. package/backend/mcp/README.md +34 -6
  36. package/backend/mcp/index.ts +8 -8
  37. package/backend/mcp/internal/config.ts +69 -19
  38. package/backend/mcp/internal/project-context.test.ts +40 -0
  39. package/backend/mcp/internal/project-context.ts +80 -7
  40. package/backend/mcp/internal/remote-server.test.ts +17 -2
  41. package/backend/mcp/internal/remote-server.ts +36 -3
  42. package/backend/mcp/internal/servers/helper.ts +48 -18
  43. package/backend/middleware/security.test.ts +95 -0
  44. package/backend/middleware/security.ts +114 -0
  45. package/backend/ports/attribute.test.ts +231 -0
  46. package/backend/ports/attribute.ts +444 -0
  47. package/backend/ports/kill.ts +203 -0
  48. package/backend/ports/monitor.ts +365 -0
  49. package/backend/ports/processes.test.ts +98 -0
  50. package/backend/ports/processes.ts +374 -0
  51. package/backend/ports/registry.ts +165 -0
  52. package/backend/ports/runner.ts +195 -0
  53. package/backend/ports/scan-host.ts +260 -0
  54. package/backend/ports/scan.test.ts +341 -0
  55. package/backend/ports/scan.ts +687 -0
  56. package/backend/ports/ssh-lineage.ts +318 -0
  57. package/backend/preview/browser/browser-video-capture.ts +51 -4
  58. package/backend/ssh/client-pool.ts +196 -0
  59. package/backend/ssh/connect.ts +375 -0
  60. package/backend/ssh/disk-usage.test.ts +134 -0
  61. package/backend/ssh/disk-usage.ts +214 -0
  62. package/backend/ssh/forwards.ts +340 -0
  63. package/backend/ssh/health.ts +141 -0
  64. package/backend/ssh/known-hosts.ts +96 -0
  65. package/backend/ssh/pty-backend.ts +215 -0
  66. package/backend/ssh/ptykit.ts +66 -0
  67. package/backend/ssh/sftp.test.ts +242 -0
  68. package/backend/ssh/sftp.ts +967 -0
  69. package/backend/ssh/socks5.test.ts +167 -0
  70. package/backend/ssh/socks5.ts +164 -0
  71. package/backend/ssh/tunnel.ts +87 -0
  72. package/backend/ws/auth/device.ts +1 -1
  73. package/backend/ws/auth/login.ts +8 -4
  74. package/backend/ws/db-client/connections.ts +1 -0
  75. package/backend/ws/files/watch.ts +5 -1
  76. package/backend/ws/index.ts +6 -0
  77. package/backend/ws/ports/index.ts +19 -0
  78. package/backend/ws/ports/kill.ts +80 -0
  79. package/backend/ws/ports/list.ts +60 -0
  80. package/backend/ws/ssh/access.ts +31 -0
  81. package/backend/ws/ssh/connections.ts +224 -0
  82. package/backend/ws/ssh/forwards.ts +109 -0
  83. package/backend/ws/ssh/index.ts +18 -0
  84. package/backend/ws/ssh/sftp.ts +259 -0
  85. package/backend/ws/ssh/tunnel.ts +93 -0
  86. package/dist/assets/{index-hu17G6tX.js → index-gGTMFUa8.js} +1 -1
  87. package/dist/assets/{index-DSvGoxp2.js → index-vW2RpdHu.js} +1 -1
  88. package/dist/assets/main-CYCMEbXB.css +1 -0
  89. package/dist/assets/{main-BccclZsC.js → main-ZCojSzvW.js} +506 -477
  90. package/dist/index.html +2 -2
  91. package/package.json +1 -1
  92. package/shared/types/database/schema.ts +49 -0
  93. package/shared/types/db-client/connection.ts +6 -0
  94. package/shared/types/ports/index.ts +5 -0
  95. package/shared/types/ports/port.ts +192 -0
  96. package/shared/types/ssh/connection.ts +80 -0
  97. package/shared/types/ssh/forward.ts +46 -0
  98. package/shared/types/ssh/index.ts +8 -0
  99. package/shared/types/ssh/known-host.ts +19 -0
  100. package/shared/types/ssh/sftp.ts +141 -0
  101. package/shared/utils/logger.ts +2 -0
  102. package/dist/assets/main-Ciuw0wF0.css +0 -1
@@ -7,10 +7,14 @@ import { findNestedRepoPaths, findRepoForFile } from './nested-repos';
7
7
 
8
8
  /**
9
9
  * Sub-repo detection used to walk the whole tree and report every directory
10
- * with a `.git` inside it. On an iOS project that meant Swift Package
11
- * Manager's `build/…/SourcePackages/checkouts/*` — thousands of foreign
12
- * changes in the Changes tab. These cover both sides of the policy: package
13
- * caches stay out, repos the user actually embedded stay in.
10
+ * with a `.git` inside it — on an iOS project, Swift Package Manager's
11
+ * `build/…/SourcePackages/checkouts/*` put thousands of foreign changes in the
12
+ * Changes tab. Pruning by directory name fixed that case and nothing more:
13
+ * `plugins/` is where tmux clones its packages *and* where a WordPress
14
+ * developer keeps their own plugin repos, so no denylist can be right on both
15
+ * sides. The policy these tests pin down is structural instead — inside a tree
16
+ * the project ignores, a sub-repo is reported only if it holds local work or
17
+ * is a declared submodule.
14
18
  */
15
19
 
16
20
  let root: string;
@@ -31,6 +35,15 @@ async function initRepo(dir: string) {
31
35
  await git(dir, 'config', 'commit.gpgsign', 'false');
32
36
  }
33
37
 
38
+ /**
39
+ * Give a repo something the Git panel could show. An untracked file is what an
40
+ * agent writing into a sub-repo produces, and it is what tells a repo the user
41
+ * works in apart from a package manager's pristine checkout.
42
+ */
43
+ async function addLocalWork(dir: string) {
44
+ await writeFile(path.join(dir, 'index.php'), '<?php // edited\n');
45
+ }
46
+
34
47
  /** Paths relative to the project root, for readable assertions. */
35
48
  async function detected(): Promise<string[]> {
36
49
  const paths = await findNestedRepoPaths(root);
@@ -78,17 +91,107 @@ describe('findNestedRepoPaths', () => {
78
91
  expect(await detected()).toEqual(['wp-content/themes/mytheme']);
79
92
  });
80
93
 
81
- test('detects a repo sitting directly under an ignored parent', async () => {
94
+ test('detects a worked-in repo sitting directly under an ignored parent', async () => {
95
+ await writeFile(path.join(root, '.gitignore'), 'themes/\n');
96
+ await initRepo(path.join(root, 'themes/mytheme'));
97
+ await addLocalWork(path.join(root, 'themes/mytheme'));
98
+
99
+ expect(await detected()).toEqual(['themes/mytheme']);
100
+ });
101
+
102
+ test('leaves a pristine repo under an ignored parent out until it changes', async () => {
103
+ // The deliberate trade-off: with nothing to show, a repo inside an
104
+ // ignored tree is indistinguishable from a package checkout. It comes
105
+ // back the moment there is a change — which is when the panel needs it.
106
+ await writeFile(path.join(root, '.gitignore'), 'themes/\n');
107
+ await initRepo(path.join(root, 'themes/mytheme'));
108
+
109
+ expect(await detected()).toEqual([]);
110
+
111
+ await addLocalWork(path.join(root, 'themes/mytheme'));
112
+ expect(await detected()).toEqual(['themes/mytheme']);
113
+ });
114
+
115
+ test.each([
116
+ ['elixir mix', '/deps/\n', ['deps/daisyui', 'deps/heroicons']],
117
+ ['openwrt feeds', 'feeds/\n', ['feeds/packages', 'feeds/luci']],
118
+ ['vim pathogen', 'bundle/\n', ['bundle/vim-fugitive']],
119
+ ['tmux tpm', 'plugins/\n', ['plugins/tpm']],
120
+ ['ansible galaxy', 'roles/\n', ['roles/geerlingguy.nginx']],
121
+ ['puppet librarian', 'modules/\n', ['modules/stdlib']],
122
+ ['chef berkshelf', 'berks-cookbooks/\n', ['berks-cookbooks/nginx']],
123
+ ['zephyr west', 'west-modules/\n', ['west-modules/hal_stm32']],
124
+ ['composer source install', 'vendor/\n', ['vendor/acme/lib']],
125
+ ['cmake fetchcontent', 'build/\n', ['build/_deps/googletest-src']]
126
+ ])(
127
+ 'ignores %s checkouts inside an ignored tree',
128
+ async (_name, gitignore, repos) => {
129
+ // Every one of these clones into an ignored directory, several of
130
+ // them exactly one level down where the peek looks. They are all
131
+ // pristine, which is the only thing the policy needs to know —
132
+ // `plugins/` and `modules/` appear on the user's side of the fence
133
+ // too, so their names cannot be the signal.
134
+ await writeFile(path.join(root, '.gitignore'), gitignore);
135
+ for (const repo of repos) await initRepo(path.join(root, repo));
136
+
137
+ expect(await detected()).toEqual([]);
138
+ }
139
+ );
140
+
141
+ test('reports the user plugin repo under an ignored dir that tmux also uses', async () => {
142
+ // Same directory name as the tmux case above, opposite verdict.
143
+ await writeFile(path.join(root, '.gitignore'), 'wp-content/plugins/\n');
144
+ await initRepo(path.join(root, 'wp-content/plugins/my-plugin'));
145
+ await addLocalWork(path.join(root, 'wp-content/plugins/my-plugin'));
146
+
147
+ expect(await detected()).toEqual(['wp-content/plugins/my-plugin']);
148
+ });
149
+
150
+ test('reports a declared submodule inside an ignored tree even when pristine', async () => {
151
+ // `.gitmodules` is the user naming the sub-repo themselves, which
152
+ // outranks anything its working tree could tell us.
82
153
  await writeFile(path.join(root, '.gitignore'), 'themes/\n');
154
+ await writeFile(
155
+ path.join(root, '.gitmodules'),
156
+ '[submodule "themes/mytheme"]\n\tpath = themes/mytheme\n\turl = https://example.com/t.git\n'
157
+ );
83
158
  await initRepo(path.join(root, 'themes/mytheme'));
84
159
 
85
160
  expect(await detected()).toEqual(['themes/mytheme']);
86
161
  });
87
162
 
163
+ test('a repo inside a rejected checkout cannot launder itself', async () => {
164
+ // Entering a repo resets the ignore budget, so without inheriting the
165
+ // "inside an ignored tree" flag the vendored repo would be treated as
166
+ // part of `pkg`'s own tracked structure and reported unconditionally.
167
+ await writeFile(path.join(root, '.gitignore'), '/deps/\n');
168
+ const pkg = path.join(root, 'deps/pkg');
169
+ await initRepo(pkg);
170
+ // Committed, so `pkg` itself stays pristine — otherwise the vendored
171
+ // directory would show up as untracked work and this would test nothing.
172
+ await writeFile(path.join(pkg, '.gitignore'), 'vendored/\n');
173
+ await git(pkg, 'add', '-A');
174
+ await git(pkg, 'commit', '-m', 'init');
175
+ await initRepo(path.join(pkg, 'vendored'));
176
+
177
+ expect(await detected()).toEqual([]);
178
+ });
179
+
180
+ test('still reports an ignored build dir that is itself a repo', async () => {
181
+ // A `dist/` deploy worktree is a repo the user works in; only the
182
+ // contents of a dependency-named dir are off limits, not the dir itself.
183
+ await writeFile(path.join(root, '.gitignore'), 'dist/\n');
184
+ await initRepo(path.join(root, 'dist'));
185
+
186
+ expect(await detected()).toEqual(['dist']);
187
+ });
188
+
88
189
  test('does not report repos generated deep inside an ignored tree', async () => {
89
190
  await writeFile(path.join(root, '.gitignore'), 'themes/\n');
90
191
  await initRepo(path.join(root, 'themes/mytheme'));
192
+ await addLocalWork(path.join(root, 'themes/mytheme'));
91
193
  await initRepo(path.join(root, 'themes/cache/vendor/dep/checkout'));
194
+ await addLocalWork(path.join(root, 'themes/cache/vendor/dep/checkout'));
92
195
 
93
196
  expect(await detected()).toEqual(['themes/mytheme']);
94
197
  });
@@ -18,15 +18,31 @@
18
18
  * are machine-generated, the user never commits them, and listing them floods
19
19
  * the Changes tab with thousands of foreign files.
20
20
  *
21
- * Two signals separate the two, both applied while walking:
21
+ * Names alone cannot separate the two. `plugins/` holds tmux's cloned packages
22
+ * and a WordPress developer's own plugin repos; `modules/` holds Puppet's
23
+ * librarian checkouts and hand-written modules. Any denylist of directory
24
+ * names is wrong on one side of those, and every new package manager adds
25
+ * another name to chase. So the policy leans on structure instead:
22
26
  *
23
- * 1. **Name** — directories in `HARD_SKIP_DIRS` are dependency/build caches by
24
- * definition; never descend into them.
27
+ * 1. **Name, for cost only** — `HARD_SKIP_DIRS` are caches so large that
28
+ * walking them is wasteful. Pruning them is an optimisation, not the policy.
25
29
  * 2. **Ignore state** — a directory the enclosing repo ignores is not part of
26
30
  * the project's own structure. We still peek `IGNORED_DESCENT_LEVELS` level
27
31
  * into it, because an embedded repo is commonly placed directly under an
28
- * ignored parent (`wp-content/themes/` ignored, the theme repo inside it),
29
- * but generated checkouts always sit much deeper.
32
+ * ignored parent (`wp-content/plugins/` ignored, the plugin repo inside it).
33
+ * 3. **Local work** — a repo found inside an ignored tree is reported only if
34
+ * it has something to show: uncommitted changes, or a `.gitmodules` entry
35
+ * declaring it. A package manager's checkout is pristine by construction —
36
+ * it is a clone at a pinned ref that nobody edits — so this drops Mix's
37
+ * `deps/*`, OpenWrt's `feeds/*`, Vim's `bundle/*` and every future
38
+ * equivalent without naming any of them. A repo the user actually works in
39
+ * appears the moment there is a change to see, which is exactly when the
40
+ * Changes tab needs it.
41
+ *
42
+ * Repos in the project's own tracked structure are never subject to (3): they
43
+ * are listed whether or not they are clean. That includes a repo whose own
44
+ * path is ignored while its parents are tracked — a directory that is itself a
45
+ * repo is recognised before its ignore state is ever consulted.
30
46
  *
31
47
  * A repo found this way resets the ignore budget: its own contents are then
32
48
  * judged by its own `.gitignore`, not the outer repo's.
@@ -38,10 +54,11 @@ import { debug } from '$shared/utils/logger';
38
54
  import { execGit } from './git-executor';
39
55
 
40
56
  /**
41
- * Directories that never hold a user's own repo — VCS internals, dependency
42
- * caches, and package-manager checkout dirs. Pruned by name at any depth,
43
- * whether or not the enclosing repo ignores them (a project may well commit
44
- * its `Pods/`, and it still isn't where sub-repos live).
57
+ * Directories large enough that walking them is pure waste — VCS internals and
58
+ * the big dependency caches. Pruned by name at any depth, whether or not the
59
+ * enclosing repo ignores them. This list is a cost guard, not the policy: what
60
+ * keeps package checkouts out of the panel is rule (3) above, so a name
61
+ * missing from here costs a little walking, not a wrong answer.
45
62
  */
46
63
  const HARD_SKIP_DIRS = new Set([
47
64
  '.git', '.svn', '.hg',
@@ -77,6 +94,13 @@ interface WalkEntry {
77
94
  * when this directory is part of the enclosing repo's own structure.
78
95
  */
79
96
  ignoredBudget: number | null;
97
+ /**
98
+ * True once the walk has crossed into a tree the project ignores. Repos
99
+ * found from here on must prove they hold local work before being
100
+ * reported, and the flag is inherited so a repo nested inside a rejected
101
+ * package checkout does not slip through on its own clean ignore state.
102
+ */
103
+ insideIgnored: boolean;
80
104
  }
81
105
 
82
106
  /**
@@ -108,6 +132,25 @@ async function filterIgnored(repoRoot: string, relPaths: string[]): Promise<Set<
108
132
  return ignored;
109
133
  }
110
134
 
135
+ /**
136
+ * Whether `repoPath` has anything the Git panel could show — staged, unstaged,
137
+ * untracked or conflicted entries. This is what separates a repo the user
138
+ * works in from a package manager's checkout, which is a clone at a pinned ref
139
+ * that nobody edits and so reports nothing.
140
+ *
141
+ * A repo we cannot read is reported as having work: hiding a sub-repo the user
142
+ * edits is a far worse failure than showing one they do not care about.
143
+ */
144
+ async function hasLocalWork(repoPath: string): Promise<boolean> {
145
+ try {
146
+ const result = await execGit(['status', '--porcelain', '-z'], repoPath, { timeout: 15000 });
147
+ if (result.exitCode !== 0) return true;
148
+ return result.stdout.length > 0;
149
+ } catch {
150
+ return true;
151
+ }
152
+ }
153
+
111
154
  /** Whether `dirPath` is a git repo (`.git` is a dir for clones, a file for worktrees/submodules). */
112
155
  async function isRepoDir(dirPath: string): Promise<boolean> {
113
156
  try {
@@ -125,7 +168,11 @@ async function isRepoDir(dirPath: string): Promise<boolean> {
125
168
  */
126
169
  export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
127
170
  const found: string[] = [];
128
- let level: WalkEntry[] = [{ dirPath: rootPath, repoRoot: rootPath, ignoredBudget: null }];
171
+ /** Repos found inside an ignored tree — reported only if they prove local work. */
172
+ const provisional: string[] = [];
173
+ let level: WalkEntry[] = [
174
+ { dirPath: rootPath, repoRoot: rootPath, ignoredBudget: null, insideIgnored: false }
175
+ ];
129
176
  let truncated = false;
130
177
 
131
178
  for (let depth = 0; depth < MAX_DEPTH && level.length > 0 && !truncated; depth++) {
@@ -172,13 +219,27 @@ export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
172
219
  const next: WalkEntry[] = [];
173
220
  candidates.forEach((c, i) => {
174
221
  if (repoFlags[i]) {
175
- if (found.length >= MAX_REPOS) {
176
- truncated = true;
177
- return;
222
+ if (c.parent.insideIgnored) {
223
+ // Candidates from an ignored tree get their own budget, so a
224
+ // directory full of package checkouts bounds the `git status`
225
+ // work without blinding the rest of the walk to real sub-repos.
226
+ if (provisional.length >= MAX_REPOS) return;
227
+ provisional.push(c.fullPath);
228
+ } else {
229
+ if (found.length >= MAX_REPOS) {
230
+ truncated = true;
231
+ return;
232
+ }
233
+ found.push(c.fullPath);
178
234
  }
179
- found.push(c.fullPath);
180
- // Inside a repo, its own ignore rules apply from scratch.
181
- next.push({ dirPath: c.fullPath, repoRoot: c.fullPath, ignoredBudget: null });
235
+ // Inside a repo, its own ignore rules apply from scratch — but a
236
+ // repo buried in an ignored tree cannot launder its children.
237
+ next.push({
238
+ dirPath: c.fullPath,
239
+ repoRoot: c.fullPath,
240
+ ignoredBudget: null,
241
+ insideIgnored: c.parent.insideIgnored
242
+ });
182
243
  return;
183
244
  }
184
245
 
@@ -187,7 +248,12 @@ export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
187
248
  const ignored = ignoredByRepo.get(c.parent.repoRoot);
188
249
  if (!ignored?.has(c.relPath)) {
189
250
  // Part of the project's own structure — descend freely.
190
- next.push({ dirPath: c.fullPath, repoRoot: c.parent.repoRoot, ignoredBudget: null });
251
+ next.push({
252
+ dirPath: c.fullPath,
253
+ repoRoot: c.parent.repoRoot,
254
+ ignoredBudget: null,
255
+ insideIgnored: c.parent.insideIgnored
256
+ });
191
257
  return;
192
258
  }
193
259
  budget = IGNORED_DESCENT_LEVELS;
@@ -196,7 +262,12 @@ export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
196
262
  }
197
263
  // Inside an ignored tree: keep looking only while the budget lasts.
198
264
  if (budget > 0) {
199
- next.push({ dirPath: c.fullPath, repoRoot: c.parent.repoRoot, ignoredBudget: budget });
265
+ next.push({
266
+ dirPath: c.fullPath,
267
+ repoRoot: c.parent.repoRoot,
268
+ ignoredBudget: budget,
269
+ insideIgnored: true
270
+ });
200
271
  }
201
272
  });
202
273
 
@@ -207,6 +278,20 @@ export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
207
278
  debug.warn('git', `Nested repo scan of ${rootPath} stopped at ${MAX_REPOS} repos`);
208
279
  }
209
280
 
281
+ if (provisional.length > 0) {
282
+ // A submodule is the user declaring the sub-repo themselves, which
283
+ // outranks anything we could infer from its working tree.
284
+ const submodulePaths = await findSubmodulePaths(rootPath);
285
+ const isDeclared = (repoPath: string) =>
286
+ submodulePaths.has(path.relative(rootPath, repoPath).replace(/\\/g, '/'));
287
+ const verdicts = await Promise.all(
288
+ provisional.map(async (repoPath) => isDeclared(repoPath) || (await hasLocalWork(repoPath)))
289
+ );
290
+ provisional.forEach((repoPath, i) => {
291
+ if (verdicts[i]) found.push(repoPath);
292
+ });
293
+ }
294
+
210
295
  found.sort();
211
296
  return found;
212
297
  }
@@ -12,41 +12,14 @@ import { join } from 'node:path';
12
12
  import { mkdir, readdir, rename, stat, unlink } from 'node:fs/promises';
13
13
 
14
14
  import { debug } from '$shared/utils/logger';
15
- import { hashToken } from '../auth/tokens';
16
- import { authQueries } from '../database/queries';
17
15
  import { getClopenDir } from '../utils/paths';
16
+ import { authenticateRequest, type AuthIdentity } from './bearer-auth';
18
17
  import {
19
18
  NOTIFICATION_SOUND_ALLOWED_EXTS,
20
19
  NOTIFICATION_SOUND_MAX_BYTES,
21
20
  isValidNotificationSoundExt
22
21
  } from '$shared/constants/notification-sounds';
23
22
 
24
- type AuthIdentity = { userId: string; role: string };
25
-
26
- function authenticate(request: Request): AuthIdentity {
27
- const header = request.headers.get('authorization') || request.headers.get('Authorization');
28
- if (!header || !header.toLowerCase().startsWith('bearer ')) {
29
- throw Object.assign(new Error('Authorization required'), { status: 401 });
30
- }
31
- const token = header.slice(7).trim();
32
- if (!token) {
33
- throw Object.assign(new Error('Authorization required'), { status: 401 });
34
- }
35
- const session = authQueries.getSessionByTokenHash(hashToken(token));
36
- if (!session) {
37
- throw Object.assign(new Error('Invalid session token'), { status: 401 });
38
- }
39
- if (new Date(session.expires_at) < new Date()) {
40
- throw Object.assign(new Error('Session expired'), { status: 401 });
41
- }
42
- const user = authQueries.getUserById(session.user_id);
43
- if (!user) {
44
- throw Object.assign(new Error('User not found'), { status: 401 });
45
- }
46
- authQueries.updateLastActive(session.id);
47
- return { userId: user.id, role: user.role };
48
- }
49
-
50
23
  function getUserAudioDir(userId: string): string {
51
24
  return join(getClopenDir(), 'audio', userId);
52
25
  }
@@ -78,7 +51,7 @@ export const audioRoute = new Elysia()
78
51
  .post('/api/audio/upload', async ({ request, query }) => {
79
52
  let identity: AuthIdentity;
80
53
  try {
81
- identity = authenticate(request);
54
+ identity = authenticateRequest(request);
82
55
  } catch (error) {
83
56
  const status = (error as { status?: number }).status ?? 401;
84
57
  const message = error instanceof Error ? error.message : 'Unauthorized';
@@ -173,7 +146,7 @@ export const audioRoute = new Elysia()
173
146
  .get('/api/audio/custom/meta', async ({ request }) => {
174
147
  let identity: AuthIdentity;
175
148
  try {
176
- identity = authenticate(request);
149
+ identity = authenticateRequest(request);
177
150
  } catch (error) {
178
151
  const status = (error as { status?: number }).status ?? 401;
179
152
  const message = error instanceof Error ? error.message : 'Unauthorized';
@@ -196,7 +169,7 @@ export const audioRoute = new Elysia()
196
169
  .get('/api/audio/custom', async ({ request }) => {
197
170
  let identity: AuthIdentity;
198
171
  try {
199
- identity = authenticate(request);
172
+ identity = authenticateRequest(request);
200
173
  } catch (error) {
201
174
  const status = (error as { status?: number }).status ?? 401;
202
175
  const message = error instanceof Error ? error.message : 'Unauthorized';
@@ -220,7 +193,7 @@ export const audioRoute = new Elysia()
220
193
  .delete('/api/audio/custom', async ({ request }) => {
221
194
  let identity: AuthIdentity;
222
195
  try {
223
- identity = authenticate(request);
196
+ identity = authenticateRequest(request);
224
197
  } catch (error) {
225
198
  const status = (error as { status?: number }).status ?? 401;
226
199
  const message = error instanceof Error ? error.message : 'Unauthorized';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Bearer-token authentication for the HTTP routes.
3
+ *
4
+ * The HTTP routes sit next to the WebSocket router rather than inside it, so
5
+ * they cannot lean on `WSConnection` for identity. They all accept the same
6
+ * `Authorization: Bearer <session-token>` the frontend already holds (issued
7
+ * by `auth:login`, stored in `localStorage`), which this module resolves to a
8
+ * user exactly once instead of once per route file.
9
+ */
10
+
11
+ import { hashToken } from '../auth/tokens';
12
+ import { authQueries } from '../database/queries';
13
+
14
+ export interface AuthIdentity {
15
+ userId: string;
16
+ role: string;
17
+ }
18
+
19
+ /**
20
+ * Resolve the caller from the request's bearer token.
21
+ *
22
+ * Throws an `Error` carrying a `status` property so a route can answer with
23
+ * the right code without re-deriving it.
24
+ */
25
+ export function authenticateRequest(request: Request): AuthIdentity {
26
+ const header = request.headers.get('authorization') || request.headers.get('Authorization');
27
+ if (!header || !header.toLowerCase().startsWith('bearer ')) {
28
+ throw Object.assign(new Error('Authorization required'), { status: 401 });
29
+ }
30
+ const token = header.slice(7).trim();
31
+ if (!token) {
32
+ throw Object.assign(new Error('Authorization required'), { status: 401 });
33
+ }
34
+ const session = authQueries.getSessionByTokenHash(hashToken(token));
35
+ if (!session) {
36
+ throw Object.assign(new Error('Invalid session token'), { status: 401 });
37
+ }
38
+ if (new Date(session.expires_at) < new Date()) {
39
+ throw Object.assign(new Error('Session expired'), { status: 401 });
40
+ }
41
+ const user = authQueries.getUserById(session.user_id);
42
+ if (!user) {
43
+ throw Object.assign(new Error('User not found'), { status: 401 });
44
+ }
45
+ authQueries.updateLastActive(session.id);
46
+ return { userId: user.id, role: user.role };
47
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Integration tests for the file download route.
3
+ *
4
+ * The point of this route is a streamed body with a real `Content-Length` —
5
+ * that header is what makes the browser's progress event computable, so it is
6
+ * asserted here rather than left to be noticed missing in the UI. Access
7
+ * control is exercised too: a path outside the caller's projects must not be
8
+ * readable just because the token is valid.
9
+ */
10
+
11
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
12
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ import { randomUUID } from 'node:crypto';
15
+
16
+ import { filesDownloadRoute } from './files-download';
17
+ import { authQueries } from '../database/queries';
18
+ import { hashToken } from '../auth/tokens';
19
+ import { projectQueries } from '../database/queries/project-queries';
20
+ import { initializeDatabase, closeDatabase } from '../database';
21
+
22
+ const TEST_DIR = join(import.meta.dir, '.test-download-integration');
23
+ const TEST_WORKSPACE = join(TEST_DIR, 'workspace');
24
+ const OUTSIDE_DIR = join(TEST_DIR, 'outside');
25
+
26
+ let testUserId: string;
27
+ let testToken: string;
28
+ let testProjectId: string;
29
+
30
+ function createMockDownloadRequest(path: string, token: string | null): Request {
31
+ const url = new URL('http://localhost/api/files/download');
32
+ url.searchParams.set('path', path);
33
+
34
+ return new Request(url.toString(), {
35
+ method: 'GET',
36
+ headers: token ? { authorization: `Bearer ${token}` } : {}
37
+ });
38
+ }
39
+
40
+ beforeAll(async () => {
41
+ await initializeDatabase();
42
+
43
+ await mkdir(TEST_WORKSPACE, { recursive: true });
44
+ await mkdir(OUTSIDE_DIR, { recursive: true });
45
+
46
+ testUserId = randomUUID();
47
+ authQueries.createUser({
48
+ id: testUserId,
49
+ name: 'Test User',
50
+ color: '#000000',
51
+ avatar: 'test',
52
+ role: 'member',
53
+ personal_access_token_hash: null,
54
+ created_at: new Date().toISOString()
55
+ });
56
+
57
+ testToken = randomUUID();
58
+ authQueries.createSession({
59
+ id: randomUUID(),
60
+ user_id: testUserId,
61
+ token_hash: hashToken(testToken),
62
+ expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
63
+ created_at: new Date().toISOString(),
64
+ last_active_at: new Date().toISOString(),
65
+ user_agent: null,
66
+ ip_address: null,
67
+ source: null
68
+ });
69
+
70
+ const project = projectQueries.create({
71
+ name: 'Test Project',
72
+ path: TEST_WORKSPACE,
73
+ created_at: new Date().toISOString(),
74
+ last_opened_at: new Date().toISOString()
75
+ });
76
+ testProjectId = project.id;
77
+ projectQueries.addUserProject(testUserId, testProjectId);
78
+ });
79
+
80
+ afterAll(async () => {
81
+ authQueries.deleteSessionsByUserId(testUserId);
82
+ authQueries.deleteUser(testUserId);
83
+ projectQueries.deleteProject(testProjectId);
84
+ closeDatabase();
85
+ await rm(TEST_DIR, { recursive: true, force: true });
86
+ });
87
+
88
+ describe('File download route', () => {
89
+ it('streams the file with a computable length and an attachment name', async () => {
90
+ const content = 'x'.repeat(10000);
91
+ const filePath = join(TEST_WORKSPACE, 'report card.txt');
92
+ await writeFile(filePath, content);
93
+
94
+ const response = await filesDownloadRoute.handle(createMockDownloadRequest(filePath, testToken));
95
+
96
+ expect(response.status).toBe(200);
97
+ // The client's progress bar prefers this over the size it already knows,
98
+ // so a file that grew since the listing still reports an honest total.
99
+ expect(response.headers.get('content-length')).toBe(String(content.length));
100
+ expect(response.headers.get('content-disposition')).toBe(
101
+ "attachment; filename*=UTF-8''report%20card.txt"
102
+ );
103
+ expect(await response.text()).toBe(content);
104
+ });
105
+
106
+ it('preserves bytes exactly for binary content', async () => {
107
+ const bytes = new Uint8Array([0, 1, 2, 253, 254, 255]);
108
+ const filePath = join(TEST_WORKSPACE, 'blob.bin');
109
+ await writeFile(filePath, bytes);
110
+
111
+ const response = await filesDownloadRoute.handle(createMockDownloadRequest(filePath, testToken));
112
+
113
+ expect(response.status).toBe(200);
114
+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(bytes);
115
+ });
116
+
117
+ it('rejects a path outside the caller projects', async () => {
118
+ const filePath = join(OUTSIDE_DIR, 'secret.txt');
119
+ await writeFile(filePath, 'secret');
120
+
121
+ const response = await filesDownloadRoute.handle(createMockDownloadRequest(filePath, testToken));
122
+
123
+ expect(response.status).toBe(403);
124
+ });
125
+
126
+ it('rejects an unauthenticated request', async () => {
127
+ const filePath = join(TEST_WORKSPACE, 'open.txt');
128
+ await writeFile(filePath, 'hello');
129
+
130
+ const response = await filesDownloadRoute.handle(createMockDownloadRequest(filePath, null));
131
+
132
+ expect(response.status).toBe(401);
133
+ });
134
+
135
+ it('reports a missing file as 404 and a directory as 400', async () => {
136
+ const missing = await filesDownloadRoute.handle(
137
+ createMockDownloadRequest(join(TEST_WORKSPACE, 'nope.txt'), testToken)
138
+ );
139
+ expect(missing.status).toBe(404);
140
+
141
+ const directory = await filesDownloadRoute.handle(
142
+ createMockDownloadRequest(TEST_WORKSPACE, testToken)
143
+ );
144
+ expect(directory.status).toBe(400);
145
+ });
146
+ });