@myrialabs/clopen 0.4.37 → 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 (101) 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/http/integration-hooks.ts +42 -0
  28. package/backend/http/notes-images.test.ts +228 -0
  29. package/backend/http/notes-images.ts +196 -0
  30. package/backend/index.ts +9 -0
  31. package/backend/integrations/accounts.ts +229 -0
  32. package/backend/integrations/health.ts +146 -0
  33. package/backend/integrations/index.ts +36 -0
  34. package/backend/integrations/projections/index.ts +120 -0
  35. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  36. package/backend/integrations/projections/mcp-projector.ts +159 -0
  37. package/backend/integrations/projections/types.ts +51 -0
  38. package/backend/integrations/registry/define.ts +38 -0
  39. package/backend/integrations/registry/index.ts +56 -0
  40. package/backend/integrations/registry/providers/context7.ts +44 -0
  41. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  42. package/backend/integrations/registry/providers/github.ts +78 -0
  43. package/backend/integrations/registry/types.ts +96 -0
  44. package/backend/integrations/webhooks/gateway.ts +160 -0
  45. package/backend/integrations/webhooks/verify.ts +65 -0
  46. package/backend/mcp/README.md +25 -3
  47. package/backend/mcp/external/config.ts +35 -1
  48. package/backend/mcp/index.ts +1 -1
  49. package/backend/mcp/internal/config.ts +1 -1
  50. package/backend/notes/access.test.ts +82 -0
  51. package/backend/notes/access.ts +27 -0
  52. package/backend/notes/storage.test.ts +77 -0
  53. package/backend/notes/storage.ts +114 -0
  54. package/backend/permissions/service.ts +2 -2
  55. package/backend/profiles/service.ts +1 -1
  56. package/backend/projects/project-cleanup.ts +6 -0
  57. package/backend/work/bindings.ts +124 -0
  58. package/backend/work/index.ts +42 -0
  59. package/backend/work/prompts.ts +150 -0
  60. package/backend/work/providers/github/actions-logs.ts +180 -0
  61. package/backend/work/providers/github/adapter.test.ts +88 -0
  62. package/backend/work/providers/github/adapter.ts +1255 -0
  63. package/backend/work/providers/github/client.ts +280 -0
  64. package/backend/work/providers/github/list-range.test.ts +158 -0
  65. package/backend/work/providers/github/token-kind.test.ts +42 -0
  66. package/backend/work/pull-requests.ts +242 -0
  67. package/backend/work/registry.ts +27 -0
  68. package/backend/work/service.ts +436 -0
  69. package/backend/work/start-work.test.ts +71 -0
  70. package/backend/work/start-work.ts +232 -0
  71. package/backend/work/types.ts +180 -0
  72. package/backend/ws/files/clipboard.ts +78 -0
  73. package/backend/ws/files/index.ts +5 -0
  74. package/backend/ws/git/diff-budget.ts +70 -11
  75. package/backend/ws/index.ts +11 -1
  76. package/backend/ws/integrations/crud.ts +219 -0
  77. package/backend/ws/integrations/index.ts +22 -0
  78. package/backend/ws/mcp/crud.ts +25 -1
  79. package/backend/ws/notes/index.ts +278 -0
  80. package/backend/ws/profiles/crud.ts +1 -1
  81. package/backend/ws/work/actions.ts +206 -0
  82. package/backend/ws/work/context.ts +51 -0
  83. package/backend/ws/work/crud.ts +347 -0
  84. package/backend/ws/work/index.ts +17 -0
  85. package/backend/ws/work/pull-requests.ts +177 -0
  86. package/backend/ws/work/schemas.ts +226 -0
  87. package/dist/assets/{index-sJmS_CCm.js → index-CyH7fSbR.js} +1 -1
  88. package/dist/assets/{index-Bik9TCBi.js → index-DSHIANSy.js} +1 -1
  89. package/dist/assets/main-D2IOjftb.css +1 -0
  90. package/dist/assets/main-DM-tHKbW.js +1152 -0
  91. package/dist/index.html +2 -2
  92. package/package.json +1 -1
  93. package/shared/constants/engine-tools.ts +1 -1
  94. package/shared/constants/tool-icons.ts +33 -0
  95. package/shared/types/database/schema.ts +41 -0
  96. package/shared/types/integrations.ts +140 -0
  97. package/shared/types/stores/settings.ts +8 -0
  98. package/shared/types/work.ts +426 -0
  99. package/shared/utils/logger.ts +3 -0
  100. package/dist/assets/main-DLqolBI2.css +0 -1
  101. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -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
+ });
@@ -0,0 +1,196 @@
1
+ /**
2
+ * HTTP routes for note image upload / download.
3
+ *
4
+ * They sit next to the WebSocket router for the same reason the file routes do:
5
+ * a base64 image on the socket costs a third more bytes and holds the whole
6
+ * attachment in memory at both ends, while HTTP streams it.
7
+ *
8
+ * Storage: `<DATA_DIR>/notes/<collectionId>/<noteId>/<uuid>-<name>`, recorded
9
+ * relative to the data dir — see `backend/notes/storage.ts`. The UUID prefix
10
+ * only has to make the name unique within the note, so two uploads of
11
+ * `screenshot.png` don't collide.
12
+ *
13
+ * Auth: `Authorization: Bearer <session-token>` on both routes, then the same
14
+ * collection rule the WebSocket handlers use, resolved through the image's
15
+ * note. The bytes must never be reachable under a weaker rule than the
16
+ * metadata.
17
+ */
18
+
19
+ import { Elysia } from 'elysia';
20
+ import { mkdir, rename, stat, unlink } from 'node:fs/promises';
21
+ import { join } from 'node:path';
22
+ import { fileTypeFromBuffer } from 'file-type';
23
+
24
+ import { debug } from '$shared/utils/logger';
25
+ import { authenticateRequest, type AuthIdentity } from './bearer-auth';
26
+ import { noteQueries, noteCollectionQueries, noteImageQueries } from '../database/queries/note-queries';
27
+ import { canAccessCollection } from '../notes/access';
28
+ import {
29
+ getNoteDir,
30
+ noteImageRelPath,
31
+ resolveNoteImagePath,
32
+ sanitizeImageFileName
33
+ } from '../notes/storage';
34
+
35
+ const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
36
+ const ALLOWED_MIMES = new Set(['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
37
+
38
+ /**
39
+ * Bytes `file-type` needs before it can name a format. Sniffing the content is
40
+ * what makes the allow-list meaningful: a client-declared `Content-Type` is
41
+ * just a string, and an SVG or HTML file announced as `image/png` would other-
42
+ * wise be stored and later served back with a type the browser will script.
43
+ */
44
+ const SNIFF_BYTES = 4100;
45
+
46
+ export const notesImagesRoute = new Elysia()
47
+ .post('/api/notes/images/upload', async ({ request, query }) => {
48
+ let identity: AuthIdentity;
49
+ try {
50
+ identity = authenticateRequest(request);
51
+ } catch (error) {
52
+ const status = (error as { status?: number }).status ?? 401;
53
+ const message = error instanceof Error ? error.message : 'Unauthorized';
54
+ return new Response(message, { status });
55
+ }
56
+
57
+ const noteId = typeof query.noteId === 'string' ? query.noteId : '';
58
+ const fileNameParam = typeof query.fileName === 'string' ? query.fileName : 'image';
59
+ const fileSizeParam = typeof query.fileSize === 'string' ? Number(query.fileSize) : NaN;
60
+
61
+ if (!noteId) return new Response('Missing required query parameter: noteId', { status: 400 });
62
+ if (!Number.isFinite(fileSizeParam) || fileSizeParam <= 0) {
63
+ return new Response('Invalid fileSize query parameter', { status: 400 });
64
+ }
65
+ if (fileSizeParam > MAX_IMAGE_SIZE) {
66
+ return new Response(`File too large. Max ${MAX_IMAGE_SIZE} bytes`, { status: 413 });
67
+ }
68
+
69
+ const note = noteQueries.getRawById(noteId);
70
+ if (!note) return new Response('Note not found', { status: 404 });
71
+
72
+ const collection = noteCollectionQueries.getById(note.collection_id);
73
+ if (!collection || !canAccessCollection(identity.userId, collection)) {
74
+ return new Response('Access denied', { status: 403 });
75
+ }
76
+
77
+ if (!request.body) return new Response('Request body is empty', { status: 400 });
78
+
79
+ const sanitized = sanitizeImageFileName(fileNameParam);
80
+ const storedName = `${crypto.randomUUID()}-${sanitized}`;
81
+ const dir = getNoteDir(collection.id, noteId);
82
+ await mkdir(dir, { recursive: true });
83
+ const finalPath = join(dir, storedName);
84
+ const tempPath = `${finalPath}.${crypto.randomUUID()}.partial`;
85
+
86
+ // Stream to a temp file with a hard ceiling instead of buffering the body.
87
+ // `fileSize` is a client claim: reading the whole request into memory first
88
+ // would let one member of one project decide how much RAM this process
89
+ // allocates, no matter what the query parameter said.
90
+ const writer = Bun.file(tempPath).writer();
91
+ const header: Uint8Array[] = [];
92
+ let headerBytes = 0;
93
+ let written = 0;
94
+
95
+ const discardTemp = async () => {
96
+ try { await writer.end(); } catch { /* best-effort */ }
97
+ await unlink(tempPath).catch(() => {});
98
+ };
99
+
100
+ try {
101
+ const reader = request.body.getReader();
102
+ while (true) {
103
+ const { done, value } = await reader.read();
104
+ if (done) break;
105
+ if (!value) continue;
106
+ written += value.byteLength;
107
+ if (written > fileSizeParam || written > MAX_IMAGE_SIZE) {
108
+ await discardTemp();
109
+ return new Response('Received more bytes than declared file size', { status: 400 });
110
+ }
111
+ if (headerBytes < SNIFF_BYTES) {
112
+ // `slice` copies: the chunk is handed to the writer next and must
113
+ // not be read again through a view once that buffer is recycled.
114
+ header.push(value.slice(0, SNIFF_BYTES - headerBytes));
115
+ headerBytes += Math.min(value.byteLength, SNIFF_BYTES - headerBytes);
116
+ }
117
+ writer.write(value);
118
+ }
119
+ await writer.end();
120
+ } catch (error) {
121
+ await discardTemp();
122
+ debug.error('notes', 'Image upload stream failed:', error);
123
+ return new Response('Failed to read upload', { status: 500 });
124
+ }
125
+
126
+ if (written !== fileSizeParam) {
127
+ await unlink(tempPath).catch(() => {});
128
+ return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, { status: 400 });
129
+ }
130
+
131
+ const detected = await fileTypeFromBuffer(Buffer.concat(header));
132
+ const mime = detected?.mime ?? '';
133
+ if (!ALLOWED_MIMES.has(mime)) {
134
+ await unlink(tempPath).catch(() => {});
135
+ return new Response(
136
+ `Unsupported image type. Allowed: ${Array.from(ALLOWED_MIMES).join(', ')}`,
137
+ { status: 400 }
138
+ );
139
+ }
140
+
141
+ try {
142
+ // Same-directory rename is atomic on POSIX and Windows alike, so the
143
+ // final path only ever appears with the complete file behind it.
144
+ await rename(tempPath, finalPath);
145
+ } catch (error) {
146
+ await unlink(tempPath).catch(() => {});
147
+ debug.error('notes', 'Failed to store note image:', error);
148
+ return new Response('Failed to save image', { status: 500 });
149
+ }
150
+
151
+ const record = noteImageQueries.create({
152
+ noteId,
153
+ fileName: sanitized,
154
+ mimeType: mime,
155
+ size: written,
156
+ storagePath: noteImageRelPath(collection.id, noteId, storedName)
157
+ });
158
+
159
+ return Response.json({ image: record, url: `/api/notes/images/${record.id}` });
160
+ })
161
+
162
+ .get('/api/notes/images/:id', async ({ request, params }) => {
163
+ let identity: AuthIdentity;
164
+ try {
165
+ identity = authenticateRequest(request);
166
+ } catch (error) {
167
+ const status = (error as { status?: number }).status ?? 401;
168
+ const message = error instanceof Error ? error.message : 'Unauthorized';
169
+ return new Response(message, { status });
170
+ }
171
+
172
+ const img = noteImageQueries.getById((params as { id: string }).id);
173
+ if (!img) return new Response('Image not found', { status: 404 });
174
+
175
+ const collection = noteCollectionQueries.getForNote(img.note_id);
176
+ if (!collection) return new Response('Image not found', { status: 404 });
177
+
178
+ if (!canAccessCollection(identity.userId, collection)) {
179
+ return new Response('Access denied', { status: 403 });
180
+ }
181
+
182
+ const absolute = resolveNoteImagePath(img.storage_path);
183
+ if (!absolute) return new Response('File not found', { status: 404 });
184
+
185
+ const stats = await stat(absolute).catch(() => null);
186
+ if (!stats || !stats.isFile()) return new Response('File not found', { status: 404 });
187
+
188
+ return new Response(Bun.file(absolute).stream(), {
189
+ headers: {
190
+ 'Content-Type': img.mime_type,
191
+ 'Content-Length': String(stats.size),
192
+ // Attachments are immutable — the id changes when the bytes do.
193
+ 'Cache-Control': 'private, max-age=3600'
194
+ }
195
+ });
196
+ });
package/backend/index.ts CHANGED
@@ -51,6 +51,8 @@ import { audioRoute } from './http/audio';
51
51
 
52
52
  // HTTP routes for SFTP transfer — same reason as the file upload route above.
53
53
  import { sshSftpRoute } from './http/ssh-sftp';
54
+ import { notesImagesRoute } from './http/notes-images';
55
+ import { integrationHooksRoute } from './http/integration-hooks';
54
56
 
55
57
  // Import browser preview manager for graceful shutdown
56
58
  import { browserPreviewServiceManager } from './preview';
@@ -198,6 +200,13 @@ const app = new Elysia()
198
200
  // SSH file transfer (SFTP download/upload).
199
201
  .use(sshSftpRoute)
200
202
 
203
+ // Notes images
204
+ .use(notesImagesRoute)
205
+
206
+ // Inbound third-party events. Unauthenticated by necessity — it verifies a
207
+ // per-provider signature over the raw bytes instead of a session.
208
+ .use(integrationHooksRoute)
209
+
201
210
  // Mount WebSocket router (all functionality now via WebSocket)
202
211
  .use(wsRouter.asPlugin('/ws'));
203
212
 
@@ -0,0 +1,229 @@
1
+ /**
2
+ * The account service — connect, reconfigure, disconnect.
3
+ *
4
+ * Every mutation ends in `reproject()`, so a surface row can never drift from
5
+ * the account it was derived from. Credential VALUES never leave this module:
6
+ * what the hub receives is which fields are set, never what they are set to.
7
+ */
8
+
9
+ import {
10
+ integrationAccountQueries,
11
+ integrationProjectionQueries,
12
+ type IntegrationAccountRow
13
+ } from '$backend/database/queries';
14
+ import type {
15
+ IntegrationAccountInfo,
16
+ IntegrationCapability,
17
+ IntegrationStatus
18
+ } from '$shared/types/integrations';
19
+ import { defaultCapabilitiesOf, getProvider, type IntegrationProvider } from './registry';
20
+ import { reproject, releaseAll } from './projections';
21
+ import { debug } from '$shared/utils/logger';
22
+
23
+ export interface ConnectInput {
24
+ provider: string;
25
+ label?: string;
26
+ projectId?: string | null;
27
+ credentials: Record<string, string>;
28
+ capabilities?: IntegrationCapability[];
29
+ }
30
+
31
+ function requireProvider(id: string): IntegrationProvider {
32
+ const provider = getProvider(id);
33
+ if (!provider) throw new Error(`Unknown integration provider "${id}"`);
34
+ return provider;
35
+ }
36
+
37
+ /**
38
+ * Reject a connect that is missing a required field.
39
+ *
40
+ * Done before the row is written rather than at first use: an account saved
41
+ * without its key looks connected in the hub and fails much later, somewhere
42
+ * with no useful place to report it.
43
+ */
44
+ function assertRequiredFields(provider: IntegrationProvider, credentials: Record<string, string>): void {
45
+ const missing = provider.credentialFields
46
+ .filter((field) => field.isRequired && !(credentials[field.name] ?? '').trim())
47
+ .map((field) => field.label);
48
+
49
+ if (missing.length > 0) {
50
+ throw new Error(`${provider.name} needs ${missing.join(', ')}`);
51
+ }
52
+ }
53
+
54
+ function assertKnownCapabilities(provider: IntegrationProvider, capabilities: IntegrationCapability[]): void {
55
+ const unknown = capabilities.filter((capability) => !provider.capabilities.includes(capability));
56
+ if (unknown.length > 0) {
57
+ throw new Error(`${provider.name} does not offer: ${unknown.join(', ')}`);
58
+ }
59
+ }
60
+
61
+ /**
62
+ * A label the user did not have to invent.
63
+ *
64
+ * `(provider, label)` is the identity, so a second account for the same
65
+ * provider needs a distinct one — "Firecrawl 2" is a better default than an
66
+ * error telling the user to think of a name.
67
+ */
68
+ function defaultLabel(provider: IntegrationProvider): string {
69
+ const taken = new Set(integrationAccountQueries.getByProvider(provider.id).map((row) => row.label));
70
+ if (!taken.has(provider.name)) return provider.name;
71
+ for (let n = 2; ; n += 1) {
72
+ const candidate = `${provider.name} ${n}`;
73
+ if (!taken.has(candidate)) return candidate;
74
+ }
75
+ }
76
+
77
+ /** Which credential fields hold a value. The values themselves stay here. */
78
+ function configuredFieldsOf(provider: IntegrationProvider, credentials: Record<string, string>): string[] {
79
+ return provider.credentialFields
80
+ .filter((field) => (credentials[field.name] ?? '').trim().length > 0)
81
+ .map((field) => field.name);
82
+ }
83
+
84
+ export function toAccountInfo(row: IntegrationAccountRow): IntegrationAccountInfo {
85
+ const provider = getProvider(row.provider);
86
+ const credentials = integrationAccountQueries.credentialsOf(row);
87
+
88
+ return {
89
+ id: row.id,
90
+ provider: row.provider,
91
+ label: row.label,
92
+ projectId: row.project_id,
93
+ authMethod: row.auth_method,
94
+ configuredFields: provider ? configuredFieldsOf(provider, credentials) : Object.keys(credentials),
95
+ capabilities: integrationAccountQueries.capabilitiesOf(row),
96
+ status: row.status,
97
+ statusDetail: row.status_detail,
98
+ checkedAt: row.checked_at,
99
+ isEnabled: row.is_enabled === 1,
100
+ createdAt: row.created_at,
101
+ updatedAt: row.updated_at,
102
+ projections: integrationProjectionQueries.getForAccount(row.id).map((projection) => ({
103
+ capability: projection.capability,
104
+ targetKind: projection.target_kind,
105
+ targetId: projection.target_id,
106
+ adopted: projection.adopted === 1
107
+ }))
108
+ };
109
+ }
110
+
111
+ export const integrationAccounts = {
112
+ list(): IntegrationAccountInfo[] {
113
+ return integrationAccountQueries.getAll().map(toAccountInfo);
114
+ },
115
+
116
+ get(id: string): IntegrationAccountInfo | null {
117
+ const row = integrationAccountQueries.getById(id);
118
+ return row ? toAccountInfo(row) : null;
119
+ },
120
+
121
+ connect(input: ConnectInput): IntegrationAccountInfo {
122
+ const provider = requireProvider(input.provider);
123
+ assertRequiredFields(provider, input.credentials);
124
+
125
+ const capabilities = input.capabilities ?? [...defaultCapabilitiesOf(provider)];
126
+ assertKnownCapabilities(provider, capabilities);
127
+
128
+ const row = integrationAccountQueries.create({
129
+ provider: provider.id,
130
+ label: (input.label ?? '').trim() || defaultLabel(provider),
131
+ projectId: input.projectId ?? null,
132
+ authMethod: provider.authMethod,
133
+ credentials: input.credentials,
134
+ capabilities
135
+ });
136
+
137
+ try {
138
+ reproject(row.id);
139
+ } catch (error) {
140
+ // A projection that cannot be made means the account is not usable, and
141
+ // a half-connected account is worse than none: it shows as connected in
142
+ // the hub while nothing behind it works.
143
+ integrationAccountQueries.remove(row.id);
144
+ throw error;
145
+ }
146
+
147
+ debug.log('integrations', `Connected ${provider.id} account "${row.label}"`);
148
+ return this.get(row.id)!;
149
+ },
150
+
151
+ /**
152
+ * Merge new credential values in.
153
+ *
154
+ * An empty value means "the form did not re-send this field", not "clear
155
+ * it" — the same rule the db-client and SSH forms follow, and the reason
156
+ * editing a label does not wipe a token.
157
+ */
158
+ updateCredentials(id: string, patch: Record<string, string>): IntegrationAccountInfo {
159
+ const row = integrationAccountQueries.getById(id);
160
+ if (!row) throw new Error('Integration account not found');
161
+ const provider = requireProvider(row.provider);
162
+
163
+ const merged = { ...integrationAccountQueries.credentialsOf(row) };
164
+ for (const [field, value] of Object.entries(patch)) {
165
+ if (value === '') continue;
166
+ merged[field] = value;
167
+ }
168
+ assertRequiredFields(provider, merged);
169
+
170
+ integrationAccountQueries.setCredentials(id, merged);
171
+ integrationAccountQueries.setStatus(id, 'unknown', null);
172
+ reproject(id);
173
+ return this.get(id)!;
174
+ },
175
+
176
+ /** Rename. The label is how a user tells two accounts of one service apart. */
177
+ setLabel(id: string, label: string): IntegrationAccountInfo {
178
+ const row = integrationAccountQueries.getById(id);
179
+ if (!row) throw new Error('Integration account not found');
180
+
181
+ const trimmed = label.trim();
182
+ if (!trimmed) throw new Error('A name is required');
183
+
184
+ const taken = integrationAccountQueries
185
+ .getByProvider(row.provider)
186
+ .some((other) => other.id !== id && other.label === trimmed);
187
+ if (taken) throw new Error(`Another ${row.provider} account is already called "${trimmed}"`);
188
+
189
+ integrationAccountQueries.setLabel(id, trimmed);
190
+ return this.get(id)!;
191
+ },
192
+
193
+ setCapabilities(id: string, capabilities: IntegrationCapability[]): IntegrationAccountInfo {
194
+ const row = integrationAccountQueries.getById(id);
195
+ if (!row) throw new Error('Integration account not found');
196
+ assertKnownCapabilities(requireProvider(row.provider), capabilities);
197
+
198
+ integrationAccountQueries.setCapabilities(id, capabilities);
199
+ reproject(id);
200
+ return this.get(id)!;
201
+ },
202
+
203
+ setEnabled(id: string, enabled: boolean): IntegrationAccountInfo {
204
+ if (!integrationAccountQueries.getById(id)) throw new Error('Integration account not found');
205
+ integrationAccountQueries.setEnabled(id, enabled);
206
+ reproject(id);
207
+ return this.get(id)!;
208
+ },
209
+
210
+ setProject(id: string, projectId: string | null): IntegrationAccountInfo {
211
+ if (!integrationAccountQueries.getById(id)) throw new Error('Integration account not found');
212
+ integrationAccountQueries.setProject(id, projectId);
213
+ reproject(id);
214
+ return this.get(id)!;
215
+ },
216
+
217
+ setStatus(id: string, status: IntegrationStatus, detail: string | null): void {
218
+ integrationAccountQueries.setStatus(id, status, detail);
219
+ },
220
+
221
+ /** Release every derived row, then drop the account. Order matters. */
222
+ disconnect(id: string): void {
223
+ const row = integrationAccountQueries.getById(id);
224
+ if (!row) return;
225
+ releaseAll(id);
226
+ integrationAccountQueries.remove(id);
227
+ debug.log('integrations', `Disconnected ${row.provider} account "${row.label}"`);
228
+ }
229
+ };