@myrialabs/clopen 0.4.36 → 0.4.38

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 (115) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/git/conflict-state.test.ts +396 -0
  28. package/backend/git/git-executor.ts +6 -0
  29. package/backend/git/git-parser.ts +144 -48
  30. package/backend/git/git-service.ts +727 -57
  31. package/backend/git/push-target.test.ts +264 -0
  32. package/backend/http/integration-hooks.ts +42 -0
  33. package/backend/http/notes-images.test.ts +228 -0
  34. package/backend/http/notes-images.ts +196 -0
  35. package/backend/index.ts +9 -0
  36. package/backend/integrations/accounts.ts +229 -0
  37. package/backend/integrations/health.ts +146 -0
  38. package/backend/integrations/index.ts +36 -0
  39. package/backend/integrations/projections/index.ts +120 -0
  40. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  41. package/backend/integrations/projections/mcp-projector.ts +159 -0
  42. package/backend/integrations/projections/types.ts +51 -0
  43. package/backend/integrations/registry/define.ts +38 -0
  44. package/backend/integrations/registry/index.ts +56 -0
  45. package/backend/integrations/registry/providers/context7.ts +44 -0
  46. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  47. package/backend/integrations/registry/providers/github.ts +78 -0
  48. package/backend/integrations/registry/types.ts +96 -0
  49. package/backend/integrations/webhooks/gateway.ts +160 -0
  50. package/backend/integrations/webhooks/verify.ts +65 -0
  51. package/backend/mcp/README.md +25 -3
  52. package/backend/mcp/external/config.ts +35 -1
  53. package/backend/mcp/index.ts +1 -1
  54. package/backend/mcp/internal/config.ts +1 -1
  55. package/backend/notes/access.test.ts +82 -0
  56. package/backend/notes/access.ts +27 -0
  57. package/backend/notes/storage.test.ts +77 -0
  58. package/backend/notes/storage.ts +114 -0
  59. package/backend/permissions/service.ts +2 -2
  60. package/backend/profiles/service.ts +1 -1
  61. package/backend/project/status-manager.ts +20 -0
  62. package/backend/projects/project-cleanup.ts +6 -0
  63. package/backend/work/bindings.ts +124 -0
  64. package/backend/work/index.ts +42 -0
  65. package/backend/work/prompts.ts +150 -0
  66. package/backend/work/providers/github/actions-logs.ts +180 -0
  67. package/backend/work/providers/github/adapter.test.ts +88 -0
  68. package/backend/work/providers/github/adapter.ts +1255 -0
  69. package/backend/work/providers/github/client.ts +280 -0
  70. package/backend/work/providers/github/list-range.test.ts +158 -0
  71. package/backend/work/providers/github/token-kind.test.ts +42 -0
  72. package/backend/work/pull-requests.ts +242 -0
  73. package/backend/work/registry.ts +27 -0
  74. package/backend/work/service.ts +436 -0
  75. package/backend/work/start-work.test.ts +71 -0
  76. package/backend/work/start-work.ts +232 -0
  77. package/backend/work/types.ts +180 -0
  78. package/backend/ws/files/clipboard.ts +78 -0
  79. package/backend/ws/files/index.ts +5 -0
  80. package/backend/ws/git/branch-name.ts +6 -5
  81. package/backend/ws/git/branch.ts +43 -1
  82. package/backend/ws/git/commit-message.ts +13 -10
  83. package/backend/ws/git/conflict.ts +106 -3
  84. package/backend/ws/git/diff-budget.test.ts +125 -0
  85. package/backend/ws/git/diff-budget.ts +279 -0
  86. package/backend/ws/git/log.ts +25 -0
  87. package/backend/ws/git/remote.ts +75 -1
  88. package/backend/ws/index.ts +11 -1
  89. package/backend/ws/integrations/crud.ts +219 -0
  90. package/backend/ws/integrations/index.ts +22 -0
  91. package/backend/ws/mcp/crud.ts +25 -1
  92. package/backend/ws/notes/index.ts +278 -0
  93. package/backend/ws/profiles/crud.ts +1 -1
  94. package/backend/ws/work/actions.ts +206 -0
  95. package/backend/ws/work/context.ts +51 -0
  96. package/backend/ws/work/crud.ts +347 -0
  97. package/backend/ws/work/index.ts +17 -0
  98. package/backend/ws/work/pull-requests.ts +177 -0
  99. package/backend/ws/work/schemas.ts +226 -0
  100. package/dist/assets/{index-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
  101. package/dist/assets/{index-Cz4YpHVi.js → index-DSHIANSy.js} +1 -1
  102. package/dist/assets/main-D2IOjftb.css +1 -0
  103. package/dist/assets/main-DM-tHKbW.js +1152 -0
  104. package/dist/index.html +2 -2
  105. package/package.json +1 -1
  106. package/shared/constants/engine-tools.ts +1 -1
  107. package/shared/constants/tool-icons.ts +33 -0
  108. package/shared/types/database/schema.ts +41 -0
  109. package/shared/types/git.ts +123 -0
  110. package/shared/types/integrations.ts +140 -0
  111. package/shared/types/stores/settings.ts +8 -0
  112. package/shared/types/work.ts +426 -0
  113. package/shared/utils/logger.ts +3 -0
  114. package/dist/assets/main-9G7IpQpK.css +0 -1
  115. package/dist/assets/main-BofFsH8E.js +0 -1085
@@ -0,0 +1,264 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { execGit } from './git-executor';
6
+ import { gitService } from './git-service';
7
+
8
+ /**
9
+ * Reviewing a pull request from a fork is the case that broke.
10
+ *
11
+ * `gh pr checkout` records the contributor's repository in
12
+ * `branch.<name>.remote` — often as a bare URL — and their branch name in
13
+ * `branch.<name>.merge`. The panel ignored both and ran
14
+ * `git push <selectedRemote> <localName> -u`, which pushed the review commits
15
+ * into the maintainer's own repository as a new branch and then rewrote the
16
+ * branch's remote so every later push went there too.
17
+ */
18
+
19
+ let workspace: string;
20
+ /** Bare repo standing in for the maintainer's repository. */
21
+ let upstream: string;
22
+ /** Bare repo standing in for the contributor's fork. */
23
+ let fork: string;
24
+ /** Working clone, with `origin` pointing at `upstream`. */
25
+ let work: string;
26
+
27
+ async function git(cwd: string, ...args: string[]) {
28
+ const result = await execGit(args, cwd);
29
+ if (result.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr}`);
30
+ return result.stdout;
31
+ }
32
+
33
+ async function branchesOf(bareRepo: string): Promise<string[]> {
34
+ const out = await git(bareRepo, 'for-each-ref', '--format=%(refname:short)', 'refs/heads/');
35
+ return out.split('\n').map(l => l.trim()).filter(Boolean).sort();
36
+ }
37
+
38
+ async function identify(repo: string) {
39
+ await git(repo, 'config', 'user.email', 'test@example.com');
40
+ await git(repo, 'config', 'user.name', 'Test');
41
+ await git(repo, 'config', 'commit.gpgsign', 'false');
42
+ }
43
+
44
+ beforeEach(async () => {
45
+ workspace = await mkdtemp(path.join(tmpdir(), 'clopen-push-'));
46
+ upstream = path.join(workspace, 'upstream.git');
47
+ fork = path.join(workspace, 'fork.git');
48
+ work = path.join(workspace, 'work');
49
+
50
+ await git(workspace, 'init', '--bare', '-b', 'main', upstream);
51
+
52
+ // Seed `main` in the upstream repo.
53
+ const seed = path.join(workspace, 'seed');
54
+ await git(workspace, 'clone', '-q', upstream, seed);
55
+ await identify(seed);
56
+ await writeFile(path.join(seed, 'a.txt'), 'a\n');
57
+ await git(seed, 'add', '-A');
58
+ await git(seed, 'commit', '-m', 'init');
59
+ await git(seed, 'push', 'origin', 'main');
60
+
61
+ // The fork starts as a copy of upstream and gains the contributor's branch.
62
+ await git(workspace, 'clone', '--bare', '-q', upstream, fork);
63
+ const forkWork = path.join(workspace, 'forkwork');
64
+ await git(workspace, 'clone', '-q', fork, forkWork);
65
+ await identify(forkWork);
66
+ await git(forkWork, 'checkout', '-b', 'their-branch');
67
+ await writeFile(path.join(forkWork, 'contrib.txt'), 'contribution\n');
68
+ await git(forkWork, 'add', '-A');
69
+ await git(forkWork, 'commit', '-m', 'contribution');
70
+ await git(forkWork, 'push', 'origin', 'their-branch');
71
+
72
+ // The maintainer's clone.
73
+ await git(workspace, 'clone', '-q', upstream, work);
74
+ await identify(work);
75
+ });
76
+
77
+ afterEach(async () => {
78
+ await rm(workspace, { recursive: true, force: true });
79
+ });
80
+
81
+ /** Reproduce what `gh pr checkout` leaves behind for a fork PR. */
82
+ async function checkoutForkPr(localName = 'their-branch') {
83
+ await git(work, 'fetch', fork, 'their-branch');
84
+ await git(work, 'checkout', '-b', localName, 'FETCH_HEAD');
85
+ await git(work, 'config', `branch.${localName}.remote`, fork);
86
+ await git(work, 'config', `branch.${localName}.merge`, 'refs/heads/their-branch');
87
+ }
88
+
89
+ describe('getPushTarget', () => {
90
+ test('reports no upstream for a fresh local branch', async () => {
91
+ await git(work, 'checkout', '-b', 'brand-new');
92
+ const target = await gitService.getPushTarget(work);
93
+ expect(target.branch).toBe('brand-new');
94
+ expect(target.hasUpstream).toBe(false);
95
+ });
96
+
97
+ test('reports the tracking branch of a normal clone', async () => {
98
+ const target = await gitService.getPushTarget(work);
99
+ expect(target.hasUpstream).toBe(true);
100
+ expect(target.remote).toBe('origin');
101
+ expect(target.remoteBranch).toBe('main');
102
+ expect(target.isUrl).toBe(false);
103
+ });
104
+
105
+ test('resolves a fork PR to the fork, not to origin', async () => {
106
+ await checkoutForkPr();
107
+
108
+ const target = await gitService.getPushTarget(work);
109
+ expect(target.hasUpstream).toBe(true);
110
+ expect(target.remote).toBe(fork);
111
+ expect(target.remoteBranch).toBe('their-branch');
112
+ expect(target.isUrl).toBe(true);
113
+ });
114
+
115
+ test('keeps the remote branch name when the local branch was renamed', async () => {
116
+ // gh renames the local branch when the name would collide.
117
+ await checkoutForkPr('contributor-their-branch');
118
+
119
+ const target = await gitService.getPushTarget(work);
120
+ expect(target.branch).toBe('contributor-their-branch');
121
+ expect(target.remoteBranch).toBe('their-branch');
122
+ });
123
+
124
+ test('honours branch.<name>.pushRemote over branch.<name>.remote', async () => {
125
+ await git(work, 'remote', 'add', 'fork', fork);
126
+ await git(work, 'config', 'branch.main.pushRemote', 'fork');
127
+
128
+ const target = await gitService.getPushTarget(work);
129
+ expect(target.remote).toBe('fork');
130
+ expect(target.isUrl).toBe(false);
131
+ });
132
+ });
133
+
134
+ describe('push — fork pull request under review', () => {
135
+ test('sends the review commit to the fork and leaves origin untouched', async () => {
136
+ await checkoutForkPr();
137
+ await writeFile(path.join(work, 'review.txt'), 'review fix\n');
138
+ await git(work, 'add', '-A');
139
+ await git(work, 'commit', '-m', 'review fix');
140
+
141
+ // `remote` here is what the panel's dropdown would have supplied.
142
+ const result = await gitService.push(work, 'origin', 'their-branch');
143
+ expect(result.success).toBe(true);
144
+
145
+ // The fix landed on the contributor's branch...
146
+ const forkHead = await git(fork, 'log', '-1', '--format=%s', 'their-branch');
147
+ expect(forkHead.trim()).toBe('review fix');
148
+
149
+ // ...and the maintainer's repository gained nothing.
150
+ expect(await branchesOf(upstream)).toEqual(['main']);
151
+ });
152
+
153
+ test('does not rewrite the branch\'s configured remote', async () => {
154
+ await checkoutForkPr();
155
+ await writeFile(path.join(work, 'review.txt'), 'review fix\n');
156
+ await git(work, 'add', '-A');
157
+ await git(work, 'commit', '-m', 'review fix');
158
+
159
+ await gitService.push(work, 'origin', 'their-branch');
160
+
161
+ // The old `-u` replaced this with "origin", so every later push — including
162
+ // a manual `git push` — silently went to the wrong repository.
163
+ const configured = (await git(work, 'config', '--get', 'branch.their-branch.remote')).trim();
164
+ expect(configured).toBe(fork);
165
+ const merge = (await git(work, 'config', '--get', 'branch.their-branch.merge')).trim();
166
+ expect(merge).toBe('refs/heads/their-branch');
167
+ });
168
+
169
+ test('force push targets the fork rather than origin', async () => {
170
+ await checkoutForkPr();
171
+ await writeFile(path.join(work, 'review.txt'), 'review fix\n');
172
+ await git(work, 'add', '-A');
173
+ await git(work, 'commit', '-m', 'review fix');
174
+
175
+ const result = await gitService.pushAdvanced(work, 'force', 'origin', 'their-branch');
176
+ expect(result.success).toBe(true);
177
+
178
+ const forkHead = await git(fork, 'log', '-1', '--format=%s', 'their-branch');
179
+ expect(forkHead.trim()).toBe('review fix');
180
+ expect(await branchesOf(upstream)).toEqual(['main']);
181
+ });
182
+
183
+ test('explains why --force-with-lease cannot work against a URL upstream', async () => {
184
+ await checkoutForkPr();
185
+ await writeFile(path.join(work, 'review.txt'), 'review fix\n');
186
+ await git(work, 'add', '-A');
187
+ await git(work, 'commit', '-m', 'review fix');
188
+
189
+ // There is no remote-tracking ref for the lease to compare against, so git
190
+ // refuses with a bare "stale info". Say what that means instead.
191
+ const result = await gitService.pushAdvanced(work, 'force-lease', 'origin', 'their-branch');
192
+ expect(result.success).toBe(false);
193
+ expect(result.message).toMatch(/remote-tracking ref/i);
194
+ expect(await branchesOf(upstream)).toEqual(['main']);
195
+ });
196
+ });
197
+
198
+ describe('push — branch with no upstream', () => {
199
+ test('still creates the branch on the chosen remote and records it', async () => {
200
+ await git(work, 'checkout', '-b', 'feature/new');
201
+ await writeFile(path.join(work, 'f.txt'), 'f\n');
202
+ await git(work, 'add', '-A');
203
+ await git(work, 'commit', '-m', 'new work');
204
+
205
+ const result = await gitService.push(work, 'origin', 'feature/new');
206
+ expect(result.success).toBe(true);
207
+ expect(await branchesOf(upstream)).toEqual(['feature/new', 'main']);
208
+
209
+ // `-u` is correct here: there was no upstream to overwrite.
210
+ const target = await gitService.getPushTarget(work);
211
+ expect(target.hasUpstream).toBe(true);
212
+ expect(target.remote).toBe('origin');
213
+ });
214
+ });
215
+
216
+ describe('getBranches', () => {
217
+ test('exposes the upstream of a normal tracking branch', async () => {
218
+ const info = await gitService.getBranches(work, 'origin');
219
+ expect(info.local.find(b => b.name === 'main')?.upstream).toBe('origin/main');
220
+ });
221
+
222
+ test('exposes a URL upstream that git itself cannot name', async () => {
223
+ await checkoutForkPr();
224
+ const info = await gitService.getBranches(work, 'origin');
225
+ const branch = info.local.find(b => b.name === 'their-branch');
226
+ expect(branch?.upstream).toBe(`${fork}/their-branch`);
227
+ });
228
+
229
+ test('counts ahead against the real upstream, not <selected remote>/<name>', async () => {
230
+ await git(work, 'checkout', '-b', 'renamed-locally', 'main');
231
+ await git(work, 'branch', '--set-upstream-to=origin/main', 'renamed-locally');
232
+ await writeFile(path.join(work, 'x.txt'), 'x\n');
233
+ await git(work, 'add', '-A');
234
+ await git(work, 'commit', '-m', 'local work');
235
+
236
+ // `origin/renamed-locally` does not exist; the old code compared against it
237
+ // and reported nothing to push.
238
+ const info = await gitService.getBranches(work, 'origin');
239
+ expect(info.ahead).toBe(1);
240
+ });
241
+ });
242
+
243
+ describe('setUpstream / unsetUpstream', () => {
244
+ test('repoints a branch at a different remote branch', async () => {
245
+ await git(work, 'checkout', '-b', 'wip', 'main');
246
+ await gitService.setUpstream(work, 'wip', 'origin', 'main');
247
+
248
+ const target = await gitService.getPushTarget(work, 'wip');
249
+ expect(target.remote).toBe('origin');
250
+ expect(target.remoteBranch).toBe('main');
251
+ });
252
+
253
+ test('clears tracking so the next push has to choose', async () => {
254
+ await gitService.unsetUpstream(work, 'main');
255
+ const target = await gitService.getPushTarget(work, 'main');
256
+ expect(target.hasUpstream).toBe(false);
257
+ });
258
+
259
+ test('reports a remote-tracking ref that does not exist', async () => {
260
+ await expect(gitService.setUpstream(work, 'main', 'origin', 'nope')).rejects.toThrow(
261
+ /could not set upstream/i
262
+ );
263
+ });
264
+ });
@@ -0,0 +1,42 @@
1
+ /**
2
+ * `POST /api/integrations/hooks/<provider>` — the only unauthenticated route
3
+ * Clopen exposes on purpose.
4
+ *
5
+ * `parse: 'none'` is load-bearing. Elysia would otherwise parse the body for us
6
+ * and the handler would only ever see a re-serialised copy, whose bytes are not
7
+ * the bytes the provider signed. Reading `request.arrayBuffer()` ourselves is
8
+ * the only way to verify a signature honestly.
9
+ *
10
+ * The policy — deny by default, uniform 404s, size cap before parsing, replay
11
+ * rejection, rate limit — lives in `backend/integrations/webhooks/gateway.ts`.
12
+ * This file is the transport.
13
+ */
14
+
15
+ import { Elysia } from 'elysia';
16
+
17
+ import { handleInboundDelivery, MAX_BODY_BYTES } from '$backend/integrations';
18
+ import { debug } from '$shared/utils/logger';
19
+
20
+ export const integrationHooksRoute = new Elysia()
21
+ .post('/api/integrations/hooks/:provider', async ({ params, request }) => {
22
+ // Cap on the declared length first — cheap, and it rejects the obvious
23
+ // case before a single byte is read.
24
+ const declared = Number(request.headers.get('content-length') ?? '0');
25
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
26
+ debug.warn('integrations', `Rejected oversized ${params.provider} delivery (${declared} bytes)`);
27
+ return new Response('Not found', { status: 404 });
28
+ }
29
+
30
+ const raw = new Uint8Array(await request.arrayBuffer());
31
+
32
+ // And again on what actually arrived: `content-length` is a claim, and a
33
+ // chunked request does not carry one at all.
34
+ if (raw.byteLength > MAX_BODY_BYTES) {
35
+ debug.warn('integrations', `Rejected oversized ${params.provider} delivery (${raw.byteLength} bytes)`);
36
+ return new Response('Not found', { status: 404 });
37
+ }
38
+
39
+ return handleInboundDelivery(params.provider, raw, request.headers);
40
+ }, {
41
+ parse: 'none'
42
+ });
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Integration tests for the note image routes.
3
+ *
4
+ * The route reads the request body as a bounded stream rather than buffering
5
+ * it, sniffs the type from the bytes instead of trusting the client, and stores
6
+ * a path relative to the data dir. Each of those is load-bearing and silent
7
+ * when broken — a buffered body only shows up as memory growth under a hostile
8
+ * client, and an absolute path only shows up after the data dir moves — so they
9
+ * are pinned here.
10
+ */
11
+
12
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
13
+ import { randomUUID } from 'node:crypto';
14
+ import { rm } from 'node:fs/promises';
15
+
16
+ import { notesImagesRoute } from './notes-images';
17
+ import { authQueries } from '../database/queries';
18
+ import { hashToken } from '../auth/tokens';
19
+ import { projectQueries } from '../database/queries/project-queries';
20
+ import { noteQueries, noteCollectionQueries, noteImageQueries } from '../database/queries/note-queries';
21
+ import { initializeDatabase, closeDatabase } from '../database';
22
+ import { getCollectionNotesDir, resolveNoteImagePath } from '../notes/storage';
23
+
24
+ // Smallest valid GIF89a — `file-type` recognises it from the header alone.
25
+ const GIF_BYTES = new Uint8Array([
26
+ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xff, 0xff, 0xff,
27
+ 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
28
+ 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b
29
+ ]);
30
+
31
+ let userId: string;
32
+ let token: string;
33
+ let projectId: string;
34
+ let collectionId: string;
35
+ let noteId: string;
36
+
37
+ function uploadRequest(body: BodyInit, fileName: string, declaredSize: number, bearer = token): Request {
38
+ const url = new URL('http://localhost/api/notes/images/upload');
39
+ url.searchParams.set('noteId', noteId);
40
+ url.searchParams.set('fileName', fileName);
41
+ url.searchParams.set('fileSize', String(declaredSize));
42
+ return new Request(url.toString(), {
43
+ method: 'POST',
44
+ body,
45
+ headers: { authorization: `Bearer ${bearer}` }
46
+ });
47
+ }
48
+
49
+ beforeAll(async () => {
50
+ await initializeDatabase();
51
+
52
+ userId = randomUUID();
53
+ authQueries.createUser({
54
+ id: userId,
55
+ name: 'Notes Test User',
56
+ color: '#000000',
57
+ avatar: 'test',
58
+ role: 'admin',
59
+ personal_access_token_hash: null,
60
+ created_at: new Date().toISOString()
61
+ });
62
+
63
+ token = randomUUID();
64
+ authQueries.createSession({
65
+ id: randomUUID(),
66
+ user_id: userId,
67
+ token_hash: hashToken(token),
68
+ expires_at: new Date(Date.now() + 86_400_000).toISOString(),
69
+ created_at: new Date().toISOString(),
70
+ last_active_at: new Date().toISOString(),
71
+ user_agent: null,
72
+ ip_address: null,
73
+ source: null
74
+ });
75
+
76
+ const project = projectQueries.create({
77
+ name: 'Notes Test Project',
78
+ path: `/tmp/notes-test-project-${randomUUID()}`,
79
+ created_at: new Date().toISOString(),
80
+ last_opened_at: new Date().toISOString()
81
+ });
82
+ projectId = project.id;
83
+ projectQueries.addUserProject(userId, projectId);
84
+
85
+ collectionId = noteCollectionQueries.create({
86
+ name: 'General',
87
+ scope: 'project',
88
+ projectId,
89
+ createdBy: userId
90
+ }).id;
91
+ noteId = noteQueries.create({ collectionId, content: 'body', createdBy: userId }).id;
92
+ });
93
+
94
+ afterAll(async () => {
95
+ await rm(getCollectionNotesDir(collectionId), { recursive: true, force: true });
96
+ authQueries.deleteSessionsByUserId(userId);
97
+ authQueries.deleteUser(userId);
98
+ projectQueries.deleteProject(projectId);
99
+ closeDatabase();
100
+ });
101
+
102
+ describe('POST /api/notes/images/upload', () => {
103
+ it('stores an accepted image at a path relative to the data dir', async () => {
104
+ const res = await notesImagesRoute.handle(
105
+ uploadRequest(GIF_BYTES, 'holiday photo.gif', GIF_BYTES.length)
106
+ );
107
+ expect(res.status).toBe(200);
108
+
109
+ const body = (await res.json()) as { image: { id: string; storage_path: string; mime_type: string } };
110
+ expect(body.image.mime_type).toBe('image/gif');
111
+ // Relative + POSIX: an absolute path here would break the moment
112
+ // CLOPEN_DATA_DIR changes or the data dir is copied to another machine.
113
+ // The space in the uploaded name is sanitized away.
114
+ expect(body.image.storage_path).toMatch(
115
+ new RegExp(`^notes/${collectionId}/${noteId}/[0-9a-f-]{36}-holiday_photo\\.gif$`)
116
+ );
117
+
118
+ const absolute = resolveNoteImagePath(body.image.storage_path);
119
+ expect(absolute).not.toBeNull();
120
+ expect(await Bun.file(absolute!).exists()).toBe(true);
121
+ });
122
+
123
+ it('rejects a non-image announced with an image file name, and keeps no file', async () => {
124
+ const before = noteImageQueries.listByNote(noteId).length;
125
+ const payload = new TextEncoder().encode('<svg onload=alert(1)></svg>'.padEnd(5000, ' '));
126
+
127
+ const res = await notesImagesRoute.handle(uploadRequest(payload, 'payload.png', payload.length));
128
+ expect(res.status).toBe(400);
129
+ expect(await res.text()).toContain('Unsupported image type');
130
+ expect(noteImageQueries.listByNote(noteId).length).toBe(before);
131
+ });
132
+
133
+ it('stops reading once a body exceeds the size it declared', async () => {
134
+ // A client that under-declares its size is how an unbounded read turns
135
+ // into "one project member decides this process's memory ceiling".
136
+ const stream = new ReadableStream<Uint8Array>({
137
+ start(controller) {
138
+ controller.enqueue(new Uint8Array(64 * 1024));
139
+ controller.enqueue(new Uint8Array(64 * 1024));
140
+ controller.close();
141
+ }
142
+ });
143
+ const res = await notesImagesRoute.handle(uploadRequest(stream, 'big.png', 1024));
144
+ expect(res.status).toBe(400);
145
+ expect(await res.text()).toContain('more bytes than declared');
146
+ });
147
+
148
+ it('rejects a declared size over the 10 MB cap before reading anything', async () => {
149
+ const res = await notesImagesRoute.handle(uploadRequest(GIF_BYTES, 'huge.gif', 11 * 1024 * 1024));
150
+ expect(res.status).toBe(413);
151
+ });
152
+
153
+ it('requires a bearer token', async () => {
154
+ const url = new URL('http://localhost/api/notes/images/upload');
155
+ url.searchParams.set('noteId', noteId);
156
+ url.searchParams.set('fileSize', String(GIF_BYTES.length));
157
+ const res = await notesImagesRoute.handle(
158
+ new Request(url.toString(), { method: 'POST', body: GIF_BYTES })
159
+ );
160
+ expect(res.status).toBe(401);
161
+ });
162
+ });
163
+
164
+ describe('GET /api/notes/images/:id', () => {
165
+ it('serves the stored bytes to a project member', async () => {
166
+ const upload = await notesImagesRoute.handle(uploadRequest(GIF_BYTES, 'served.gif', GIF_BYTES.length));
167
+ const { image } = (await upload.json()) as { image: { id: string } };
168
+
169
+ const res = await notesImagesRoute.handle(
170
+ new Request(`http://localhost/api/notes/images/${image.id}`, {
171
+ headers: { authorization: `Bearer ${token}` }
172
+ })
173
+ );
174
+ expect(res.status).toBe(200);
175
+ expect(res.headers.get('content-type')).toBe('image/gif');
176
+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(GIF_BYTES);
177
+ });
178
+
179
+ it('does not accept the session token from the query string', async () => {
180
+ const upload = await notesImagesRoute.handle(uploadRequest(GIF_BYTES, 'query.gif', GIF_BYTES.length));
181
+ const { image } = (await upload.json()) as { image: { id: string } };
182
+
183
+ // A credential in a URL ends up in browser history, proxy logs and tunnel
184
+ // edge logs, so the route must not honour one.
185
+ const res = await notesImagesRoute.handle(
186
+ new Request(`http://localhost/api/notes/images/${image.id}?token=${token}`)
187
+ );
188
+ expect(res.status).toBe(401);
189
+ });
190
+
191
+ it('denies a user who is not a member of the project the collection belongs to', async () => {
192
+ const outsiderId = randomUUID();
193
+ authQueries.createUser({
194
+ id: outsiderId,
195
+ name: 'Outsider',
196
+ color: '#000000',
197
+ avatar: 'test',
198
+ role: 'member',
199
+ personal_access_token_hash: null,
200
+ created_at: new Date().toISOString()
201
+ });
202
+ const outsiderToken = randomUUID();
203
+ authQueries.createSession({
204
+ id: randomUUID(),
205
+ user_id: outsiderId,
206
+ token_hash: hashToken(outsiderToken),
207
+ expires_at: new Date(Date.now() + 86_400_000).toISOString(),
208
+ created_at: new Date().toISOString(),
209
+ last_active_at: new Date().toISOString(),
210
+ user_agent: null,
211
+ ip_address: null,
212
+ source: null
213
+ });
214
+
215
+ const upload = await notesImagesRoute.handle(uploadRequest(GIF_BYTES, 'private.gif', GIF_BYTES.length));
216
+ const { image } = (await upload.json()) as { image: { id: string } };
217
+
218
+ const res = await notesImagesRoute.handle(
219
+ new Request(`http://localhost/api/notes/images/${image.id}`, {
220
+ headers: { authorization: `Bearer ${outsiderToken}` }
221
+ })
222
+ );
223
+ expect(res.status).toBe(403);
224
+
225
+ authQueries.deleteSessionsByUserId(outsiderId);
226
+ authQueries.deleteUser(outsiderId);
227
+ });
228
+ });