@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,297 @@
1
+ /**
2
+ * Integration account + projection queries.
3
+ *
4
+ * `integration_accounts` is the ONLY place a third-party credential lives.
5
+ * `credentials` is a JSON object sealed at rest by the crypto layer, so callers
6
+ * here hand in and receive a plain object and never see an envelope.
7
+ *
8
+ * `integration_projections` links an account to the rows it derived on other
9
+ * surfaces. Nothing outside `backend/integrations/projections/` should write to
10
+ * it — a projection created by hand is a projection nothing will ever clean up.
11
+ */
12
+
13
+ import { getDatabase } from '../index';
14
+ import { openRow, sealFor } from '../crypto';
15
+ import type { IntegrationAuthMethod, IntegrationCapability, IntegrationStatus, IntegrationTargetKind } from '$shared/types/integrations';
16
+
17
+ const TABLE = 'integration_accounts';
18
+
19
+ export interface IntegrationAccountRow {
20
+ id: string;
21
+ provider: string;
22
+ label: string;
23
+ project_id: string | null;
24
+ auth_method: IntegrationAuthMethod;
25
+ /** Sealed on disk, plain JSON string here. Null when the key could not open it. */
26
+ credentials: string | null;
27
+ capabilities: string;
28
+ status: IntegrationStatus;
29
+ status_detail: string | null;
30
+ checked_at: string | null;
31
+ is_enabled: number;
32
+ created_at: string;
33
+ updated_at: string;
34
+ }
35
+
36
+ export interface IntegrationProjectionRow {
37
+ account_id: string;
38
+ capability: IntegrationCapability;
39
+ target_kind: IntegrationTargetKind;
40
+ target_id: string;
41
+ adopted: number;
42
+ restore_json: string | null;
43
+ created_at: string;
44
+ }
45
+
46
+ export interface IntegrationAccountInput {
47
+ provider: string;
48
+ label: string;
49
+ projectId?: string | null;
50
+ authMethod: IntegrationAuthMethod;
51
+ credentials: Record<string, string>;
52
+ capabilities: IntegrationCapability[];
53
+ }
54
+
55
+ /** Parse a JSON column, falling back rather than throwing on a value we could not open. */
56
+ function parse<T>(raw: string | null, fallback: T): T {
57
+ if (!raw) return fallback;
58
+ try {
59
+ const parsed = JSON.parse(raw);
60
+ return (parsed ?? fallback) as T;
61
+ } catch {
62
+ return fallback;
63
+ }
64
+ }
65
+
66
+ function openAccount<T extends IntegrationAccountRow | null>(row: T): T {
67
+ return (row ? openRow(TABLE, row) : row) as T;
68
+ }
69
+
70
+ export const integrationAccountQueries = {
71
+ getAll(): IntegrationAccountRow[] {
72
+ const db = getDatabase();
73
+ return (db.prepare(
74
+ `SELECT * FROM integration_accounts ORDER BY provider ASC, label ASC`
75
+ ).all() as IntegrationAccountRow[]).map((row) => openAccount(row));
76
+ },
77
+
78
+ getById(id: string): IntegrationAccountRow | null {
79
+ const db = getDatabase();
80
+ return openAccount(
81
+ db.prepare(`SELECT * FROM integration_accounts WHERE id = ?`).get(id) as IntegrationAccountRow | null
82
+ );
83
+ },
84
+
85
+ getByProvider(provider: string): IntegrationAccountRow[] {
86
+ const db = getDatabase();
87
+ return (db.prepare(
88
+ `SELECT * FROM integration_accounts WHERE provider = ? ORDER BY label ASC`
89
+ ).all(provider) as IntegrationAccountRow[]).map((row) => openAccount(row));
90
+ },
91
+
92
+ /**
93
+ * Enabled accounts for one provider, preferring a project-bound account over
94
+ * a global one. This is the lookup an inbound webhook and a surface both
95
+ * make, and preferring the bound account is what lets two projects point at
96
+ * two different orgs of the same service.
97
+ */
98
+ getEnabledForProvider(provider: string, projectId?: string | null): IntegrationAccountRow[] {
99
+ return this.getByProvider(provider)
100
+ .filter((row) => row.is_enabled === 1)
101
+ .sort((a, b) => {
102
+ const aBound = a.project_id === projectId ? 0 : 1;
103
+ const bBound = b.project_id === projectId ? 0 : 1;
104
+ return aBound - bBound;
105
+ });
106
+ },
107
+
108
+ /** Decoded credentials. Empty object when the active key could not open them. */
109
+ credentialsOf(row: IntegrationAccountRow): Record<string, string> {
110
+ return parse<Record<string, string>>(row.credentials, {});
111
+ },
112
+
113
+ capabilitiesOf(row: IntegrationAccountRow): IntegrationCapability[] {
114
+ return parse<IntegrationCapability[]>(row.capabilities, []);
115
+ },
116
+
117
+ create(input: IntegrationAccountInput): IntegrationAccountRow {
118
+ const db = getDatabase();
119
+ const id = crypto.randomUUID();
120
+ const now = new Date().toISOString();
121
+
122
+ db.prepare(`
123
+ INSERT INTO integration_accounts (
124
+ id, provider, label, project_id, auth_method,
125
+ credentials, capabilities, status, is_enabled, created_at, updated_at
126
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 'unknown', 1, ?, ?)
127
+ `).run(
128
+ id,
129
+ input.provider,
130
+ input.label,
131
+ input.projectId ?? null,
132
+ input.authMethod,
133
+ sealFor(TABLE, 'credentials', JSON.stringify(input.credentials)),
134
+ JSON.stringify(input.capabilities),
135
+ now,
136
+ now
137
+ );
138
+
139
+ return this.getById(id)!;
140
+ },
141
+
142
+ /**
143
+ * Replace the stored credentials.
144
+ *
145
+ * The caller merges — an empty value from the form means "the field was not
146
+ * re-typed", not "clear it", the same rule the db-client and SSH forms use.
147
+ */
148
+ setCredentials(id: string, credentials: Record<string, string>): void {
149
+ const db = getDatabase();
150
+ db.prepare(`UPDATE integration_accounts SET credentials = ?, updated_at = ? WHERE id = ?`).run(
151
+ sealFor(TABLE, 'credentials', JSON.stringify(credentials)),
152
+ new Date().toISOString(),
153
+ id
154
+ );
155
+ },
156
+
157
+ /**
158
+ * Rename an account.
159
+ *
160
+ * `(provider, label)` is the identity, so this can collide — the UNIQUE
161
+ * constraint refuses it, and the caller turns that into a readable message
162
+ * rather than letting a raw SQLite error reach the dialog.
163
+ */
164
+ setLabel(id: string, label: string): void {
165
+ const db = getDatabase();
166
+ db.prepare(`UPDATE integration_accounts SET label = ?, updated_at = ? WHERE id = ?`).run(
167
+ label,
168
+ new Date().toISOString(),
169
+ id
170
+ );
171
+ },
172
+
173
+ setCapabilities(id: string, capabilities: IntegrationCapability[]): void {
174
+ const db = getDatabase();
175
+ db.prepare(`UPDATE integration_accounts SET capabilities = ?, updated_at = ? WHERE id = ?`).run(
176
+ JSON.stringify(capabilities),
177
+ new Date().toISOString(),
178
+ id
179
+ );
180
+ },
181
+
182
+ setEnabled(id: string, enabled: boolean): void {
183
+ const db = getDatabase();
184
+ db.prepare(`UPDATE integration_accounts SET is_enabled = ?, updated_at = ? WHERE id = ?`).run(
185
+ enabled ? 1 : 0,
186
+ new Date().toISOString(),
187
+ id
188
+ );
189
+ },
190
+
191
+ setProject(id: string, projectId: string | null): void {
192
+ const db = getDatabase();
193
+ db.prepare(`UPDATE integration_accounts SET project_id = ?, updated_at = ? WHERE id = ?`).run(
194
+ projectId,
195
+ new Date().toISOString(),
196
+ id
197
+ );
198
+ },
199
+
200
+ setStatus(id: string, status: IntegrationStatus, detail: string | null): void {
201
+ const db = getDatabase();
202
+ db.prepare(
203
+ `UPDATE integration_accounts SET status = ?, status_detail = ?, checked_at = ? WHERE id = ?`
204
+ ).run(status, detail, new Date().toISOString(), id);
205
+ },
206
+
207
+ remove(id: string): void {
208
+ const db = getDatabase();
209
+ db.prepare(`DELETE FROM integration_accounts WHERE id = ?`).run(id);
210
+ }
211
+ };
212
+
213
+ export const integrationProjectionQueries = {
214
+ getForAccount(accountId: string): IntegrationProjectionRow[] {
215
+ const db = getDatabase();
216
+ return db.prepare(
217
+ `SELECT * FROM integration_projections WHERE account_id = ?`
218
+ ).all(accountId) as IntegrationProjectionRow[];
219
+ },
220
+
221
+ getAll(): IntegrationProjectionRow[] {
222
+ const db = getDatabase();
223
+ return db.prepare(`SELECT * FROM integration_projections`).all() as IntegrationProjectionRow[];
224
+ },
225
+
226
+ /** Who, if anyone, owns this surface row. Used to badge it read-only. */
227
+ getByTarget(targetKind: IntegrationTargetKind, targetId: string): IntegrationProjectionRow | null {
228
+ const db = getDatabase();
229
+ return db.prepare(
230
+ `SELECT * FROM integration_projections WHERE target_kind = ? AND target_id = ?`
231
+ ).get(targetKind, targetId) as IntegrationProjectionRow | null;
232
+ },
233
+
234
+ upsert(input: {
235
+ accountId: string;
236
+ capability: IntegrationCapability;
237
+ targetKind: IntegrationTargetKind;
238
+ targetId: string;
239
+ adopted: boolean;
240
+ restore: unknown | null;
241
+ }): void {
242
+ const db = getDatabase();
243
+ db.prepare(`
244
+ INSERT INTO integration_projections (account_id, capability, target_kind, target_id, adopted, restore_json, created_at)
245
+ VALUES (?, ?, ?, ?, ?, ?, ?)
246
+ ON CONFLICT (account_id, capability, target_kind) DO UPDATE SET
247
+ target_id = excluded.target_id,
248
+ adopted = excluded.adopted
249
+ `).run(
250
+ input.accountId,
251
+ input.capability,
252
+ input.targetKind,
253
+ input.targetId,
254
+ input.adopted ? 1 : 0,
255
+ input.restore === null ? null : JSON.stringify(input.restore),
256
+ new Date().toISOString()
257
+ );
258
+ },
259
+
260
+ remove(accountId: string, capability: IntegrationCapability, targetKind: IntegrationTargetKind): void {
261
+ const db = getDatabase();
262
+ db.prepare(
263
+ `DELETE FROM integration_projections WHERE account_id = ? AND capability = ? AND target_kind = ?`
264
+ ).run(accountId, capability, targetKind);
265
+ },
266
+
267
+ /** The snapshot taken when an existing row was adopted, or null. */
268
+ restoreOf<T>(row: IntegrationProjectionRow): T | null {
269
+ return parse<T | null>(row.restore_json, null);
270
+ }
271
+ };
272
+
273
+ export const integrationWebhookQueries = {
274
+ /**
275
+ * Record a delivery, returning false when it has already been seen.
276
+ *
277
+ * The UNIQUE constraint IS the replay check. A read-then-write would let two
278
+ * concurrent deliveries of the same event both pass the read and both run.
279
+ */
280
+ claimDelivery(provider: string, deliveryId: string): boolean {
281
+ const db = getDatabase();
282
+ const result = db.prepare(`
283
+ INSERT OR IGNORE INTO integration_webhook_deliveries (provider, delivery_id, received_at)
284
+ VALUES (?, ?, ?)
285
+ `).run(provider, deliveryId, new Date().toISOString()) as { changes: number };
286
+ return result.changes > 0;
287
+ },
288
+
289
+ /** Drop delivery ids older than the retention window so the table stays bounded. */
290
+ pruneBefore(isoTimestamp: string): number {
291
+ const db = getDatabase();
292
+ const result = db.prepare(
293
+ `DELETE FROM integration_webhook_deliveries WHERE received_at < ?`
294
+ ).run(isoTimestamp) as { changes: number };
295
+ return result.changes;
296
+ }
297
+ };
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { getDatabase } from '../index';
17
+ import { openRow, sealFor } from '../crypto';
17
18
  import type { EngineType } from '$shared/types/unified';
18
19
 
19
20
  export type McpTransport = 'stdio' | 'http' | 'sse';
@@ -90,30 +91,56 @@ export interface McpServerInput {
90
91
  source?: McpSource;
91
92
  }
92
93
 
94
+ // `env`, `headers` and `oauth` are sealed at rest (see backend/database/crypto).
95
+ // Every read below opens them again, so `resolveServerRow()` and every
96
+ // per-engine config builder keep reading exactly what they always read.
97
+ const TABLE = 'mcp_servers';
98
+
99
+ /**
100
+ * Open one row's sealed columns.
101
+ *
102
+ * `env` and `headers` are NOT NULL JSON maps, so a value the active key cannot
103
+ * open becomes `'{}'` rather than `null`: downstream, an empty map is exactly
104
+ * "this server has no credentials", which is the same degradation a missing
105
+ * secret gets everywhere else. Handing `null` down instead would turn a lost
106
+ * key into a TypeError inside every per-engine config builder.
107
+ */
108
+ function openServerRow(row: McpServerRow): McpServerRow {
109
+ const opened = openRow(TABLE, row);
110
+ return {
111
+ ...opened,
112
+ env: opened.env ?? '{}',
113
+ headers: opened.headers ?? '{}'
114
+ };
115
+ }
116
+
117
+ const openServer = (row: McpServerRow | null): McpServerRow | null =>
118
+ row ? openServerRow(row) : null;
119
+
93
120
  export const mcpServerQueries = {
94
121
  getAll(): McpServerRow[] {
95
122
  const db = getDatabase();
96
- return db.prepare(`SELECT * FROM mcp_servers ORDER BY created_at ASC`).all() as McpServerRow[];
123
+ return (db.prepare(`SELECT * FROM mcp_servers ORDER BY created_at ASC`).all() as McpServerRow[]).map(openServerRow);
97
124
  },
98
125
 
99
126
  getEnabled(): McpServerRow[] {
100
127
  const db = getDatabase();
101
- return db.prepare(`SELECT * FROM mcp_servers WHERE is_enabled = 1 ORDER BY created_at ASC`).all() as McpServerRow[];
128
+ return (db.prepare(`SELECT * FROM mcp_servers WHERE is_enabled = 1 ORDER BY created_at ASC`).all() as McpServerRow[]).map(openServerRow);
102
129
  },
103
130
 
104
131
  getById(id: number): McpServerRow | null {
105
132
  const db = getDatabase();
106
- return db.prepare(`SELECT * FROM mcp_servers WHERE id = ?`).get(id) as McpServerRow | null;
133
+ return openServer(db.prepare(`SELECT * FROM mcp_servers WHERE id = ?`).get(id) as McpServerRow | null);
107
134
  },
108
135
 
109
136
  getBySlug(slug: string): McpServerRow | null {
110
137
  const db = getDatabase();
111
- return db.prepare(`SELECT * FROM mcp_servers WHERE slug = ?`).get(slug) as McpServerRow | null;
138
+ return openServer(db.prepare(`SELECT * FROM mcp_servers WHERE slug = ?`).get(slug) as McpServerRow | null);
112
139
  },
113
140
 
114
141
  getBySource(source: McpSource): McpServerRow[] {
115
142
  const db = getDatabase();
116
- return db.prepare(`SELECT * FROM mcp_servers WHERE source = ? ORDER BY created_at ASC`).all(source) as McpServerRow[];
143
+ return (db.prepare(`SELECT * FROM mcp_servers WHERE source = ? ORDER BY created_at ASC`).all(source) as McpServerRow[]).map(openServerRow);
117
144
  },
118
145
 
119
146
  insert(input: McpServerInput): McpServerRow {
@@ -131,9 +158,9 @@ export const mcpServerQueries = {
131
158
  input.transport,
132
159
  input.command ?? null,
133
160
  JSON.stringify(input.args ?? []),
134
- JSON.stringify(input.env ?? {}),
161
+ sealFor(TABLE, 'env', JSON.stringify(input.env ?? {})),
135
162
  input.url ?? null,
136
- JSON.stringify(input.headers ?? {}),
163
+ sealFor(TABLE, 'headers', JSON.stringify(input.headers ?? {})),
137
164
  JSON.stringify(input.configSchema ?? []),
138
165
  input.source ?? 'registry'
139
166
  ) as { lastInsertRowid: number | bigint };
@@ -149,15 +176,15 @@ export const mcpServerQueries = {
149
176
  /** Update the stored env (e.g. user-provided API keys) for a server. */
150
177
  updateEnv(id: number, env: Record<string, string>): void {
151
178
  const db = getDatabase();
152
- db.prepare(`UPDATE mcp_servers SET env = ? WHERE id = ?`).run(JSON.stringify(env), id);
179
+ db.prepare(`UPDATE mcp_servers SET env = ? WHERE id = ?`).run(sealFor(TABLE, 'env', JSON.stringify(env)), id);
153
180
  },
154
181
 
155
182
  /** Update both env (stdio) and headers (remote auth) for a server. */
156
183
  updateConfig(id: number, env: Record<string, string>, headers: Record<string, string>): void {
157
184
  const db = getDatabase();
158
185
  db.prepare(`UPDATE mcp_servers SET env = ?, headers = ? WHERE id = ?`).run(
159
- JSON.stringify(env),
160
- JSON.stringify(headers),
186
+ sealFor(TABLE, 'env', JSON.stringify(env)),
187
+ sealFor(TABLE, 'headers', JSON.stringify(headers)),
161
188
  id
162
189
  );
163
190
  },
@@ -179,7 +206,7 @@ export const mcpServerQueries = {
179
206
  /** Store (or clear with null) the managed OAuth state JSON for a server. */
180
207
  setOAuth(id: number, oauth: string | null): void {
181
208
  const db = getDatabase();
182
- db.prepare(`UPDATE mcp_servers SET oauth = ? WHERE id = ?`).run(oauth, id);
209
+ db.prepare(`UPDATE mcp_servers SET oauth = ? WHERE id = ?`).run(sealFor(TABLE, 'oauth', oauth), id);
183
210
  },
184
211
 
185
212
  /** Persist the per-tool + per-engine exposure overrides for a server. */
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Tests for the note query layer.
3
+ *
4
+ * The scope of a note is the scope of its collection and nothing else, so the
5
+ * cases that matter are the ones where those two could drift apart: a global
6
+ * collection must never carry a project id, a project collection must always
7
+ * carry one, and the cascade has to reach notes and images through it.
8
+ */
9
+
10
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
11
+ import { randomUUID } from 'node:crypto';
12
+
13
+ import { initializeDatabase, closeDatabase } from '../index';
14
+ import { projectQueries } from './project-queries';
15
+ import {
16
+ noteQueries,
17
+ noteCollectionQueries,
18
+ noteImageQueries,
19
+ DEFAULT_COLLECTION_NAME
20
+ } from './note-queries';
21
+
22
+ let projectId: string;
23
+ let collectionId: string;
24
+
25
+ function makeProject(name: string): string {
26
+ return projectQueries.create({
27
+ name,
28
+ // `projects.path` is unique, so a fixed path collides with whatever an
29
+ // earlier run left behind in the test data dir.
30
+ path: `/tmp/${name}-${randomUUID()}`,
31
+ created_at: new Date().toISOString(),
32
+ last_opened_at: new Date().toISOString()
33
+ }).id;
34
+ }
35
+
36
+ beforeAll(async () => {
37
+ await initializeDatabase();
38
+ projectId = makeProject('note-query-test');
39
+ collectionId = noteCollectionQueries.create({
40
+ name: 'General',
41
+ scope: 'project',
42
+ projectId
43
+ }).id;
44
+ });
45
+
46
+ afterAll(() => {
47
+ // Global collections outlive every project, so this suite cleans up its own.
48
+ for (const c of noteCollectionQueries.listByScope('global')) noteCollectionQueries.delete(c.id);
49
+ projectQueries.deleteProject(projectId);
50
+ closeDatabase();
51
+ });
52
+
53
+ describe('noteCollectionQueries', () => {
54
+ it('drops a project id handed to a global collection instead of failing the CHECK', () => {
55
+ const global = noteCollectionQueries.create({
56
+ name: 'Runbooks',
57
+ scope: 'global',
58
+ projectId
59
+ });
60
+ expect(global.scope).toBe('global');
61
+ expect(global.project_id).toBeNull();
62
+ noteCollectionQueries.delete(global.id);
63
+ });
64
+
65
+ it('keeps each scope’s collections out of the other’s list', () => {
66
+ const global = noteCollectionQueries.create({ name: 'Shared', scope: 'global' });
67
+
68
+ const projectIds = noteCollectionQueries.listByScope('project', projectId).map((c) => c.id);
69
+ const globalIds = noteCollectionQueries.listByScope('global').map((c) => c.id);
70
+
71
+ expect(projectIds).toContain(collectionId);
72
+ expect(projectIds).not.toContain(global.id);
73
+ expect(globalIds).toContain(global.id);
74
+ expect(globalIds).not.toContain(collectionId);
75
+
76
+ noteCollectionQueries.delete(global.id);
77
+ });
78
+
79
+ it('does not leak one project’s collections into another’s', () => {
80
+ const otherId = makeProject('note-query-other');
81
+ expect(noteCollectionQueries.listByScope('project', otherId)).toEqual([]);
82
+ projectQueries.deleteProject(otherId);
83
+ });
84
+
85
+ it('resolves the collection a note belongs to, which is where its access comes from', () => {
86
+ const note = noteQueries.create({ collectionId, content: 'body' });
87
+ expect(noteCollectionQueries.getForNote(note.id)?.id).toBe(collectionId);
88
+ noteQueries.delete(note.id);
89
+ });
90
+
91
+ it('returns null for a note that does not exist rather than a stray collection', () => {
92
+ expect(noteCollectionQueries.getForNote('missing-note')).toBeNull();
93
+ });
94
+
95
+ it('creates a default collection on first use, then reuses it', () => {
96
+ const emptyProject = makeProject('note-query-default');
97
+ const first = noteCollectionQueries.ensureDefault('project', emptyProject, null);
98
+ expect(first.name).toBe(DEFAULT_COLLECTION_NAME);
99
+ expect(noteCollectionQueries.ensureDefault('project', emptyProject, null).id).toBe(first.id);
100
+ projectQueries.deleteProject(emptyProject);
101
+ });
102
+
103
+ it('cascades its notes away when deleted', () => {
104
+ const doomed = noteCollectionQueries.create({ name: 'Doomed', scope: 'project', projectId });
105
+ const note = noteQueries.create({ collectionId: doomed.id, content: 'bye' });
106
+ noteCollectionQueries.delete(doomed.id);
107
+ expect(noteQueries.getRawById(note.id)).toBeNull();
108
+ });
109
+ });
110
+
111
+ describe('noteQueries', () => {
112
+ it('attaches each note its own images and nothing else', () => {
113
+ const withImages = noteQueries.create({ collectionId, content: 'has images' });
114
+ const withoutImages = noteQueries.create({ collectionId, content: 'no images' });
115
+
116
+ for (const name of ['a.png', 'b.png']) {
117
+ noteImageQueries.create({
118
+ noteId: withImages.id,
119
+ fileName: name,
120
+ mimeType: 'image/png',
121
+ size: 1,
122
+ storagePath: `notes/${collectionId}/${withImages.id}/${name}`
123
+ });
124
+ }
125
+
126
+ const byId = new Map(noteQueries.listByCollection(collectionId).map((n) => [n.id, n]));
127
+ expect(byId.get(withImages.id)?.images.map((i) => i.file_name).sort()).toEqual(['a.png', 'b.png']);
128
+ expect(byId.get(withoutImages.id)?.images).toEqual([]);
129
+
130
+ noteQueries.delete(withImages.id);
131
+ noteQueries.delete(withoutImages.id);
132
+ });
133
+
134
+ it('lists across several collections in one call', () => {
135
+ const other = noteCollectionQueries.create({ name: 'Specs', scope: 'project', projectId });
136
+ const a = noteQueries.create({ collectionId, content: 'a' });
137
+ const b = noteQueries.create({ collectionId: other.id, content: 'b' });
138
+
139
+ expect(noteQueries.listByCollections([collectionId, other.id]).map((n) => n.id).sort()).toEqual(
140
+ [a.id, b.id].sort()
141
+ );
142
+ // An empty set must not turn into "every note in the database".
143
+ expect(noteQueries.listByCollections([])).toEqual([]);
144
+
145
+ noteCollectionQueries.delete(other.id);
146
+ noteQueries.delete(a.id);
147
+ });
148
+
149
+ it('truncates oversized content on create and on update', () => {
150
+ const note = noteQueries.create({ collectionId, content: 'x'.repeat(250_000) });
151
+ expect(note.content.length).toBe(200_000);
152
+ expect(noteQueries.getById(note.id)?.content.length).toBe(200_000);
153
+
154
+ expect(noteQueries.update(note.id, { content: 'y'.repeat(250_000) })?.content.length).toBe(200_000);
155
+ noteQueries.delete(note.id);
156
+ });
157
+
158
+ it('leaves untouched fields alone when the patch omits them', () => {
159
+ const note = noteQueries.create({ collectionId, title: 'Keep me', content: 'original' });
160
+ const updated = noteQueries.update(note.id, { content: 'replaced' });
161
+ expect(updated?.title).toBe('Keep me');
162
+ expect(updated?.content).toBe('replaced');
163
+ expect(updated?.collection_id).toBe(collectionId);
164
+ noteQueries.delete(note.id);
165
+ });
166
+
167
+ it('moves a note between collections, which is what changes who can read it', () => {
168
+ const target = noteCollectionQueries.create({ name: 'Moved', scope: 'global' });
169
+ const note = noteQueries.create({ collectionId, content: 'travelling' });
170
+
171
+ expect(noteQueries.update(note.id, { collectionId: target.id })?.collection_id).toBe(target.id);
172
+ expect(noteCollectionQueries.getForNote(note.id)?.scope).toBe('global');
173
+
174
+ noteCollectionQueries.delete(target.id);
175
+ });
176
+
177
+ it('cascades image rows away with the note', () => {
178
+ const note = noteQueries.create({ collectionId, content: 'doomed' });
179
+ const image = noteImageQueries.create({
180
+ noteId: note.id,
181
+ fileName: 'c.png',
182
+ mimeType: 'image/png',
183
+ size: 3,
184
+ storagePath: `notes/${collectionId}/${note.id}/c.png`
185
+ });
186
+
187
+ noteQueries.delete(note.id);
188
+ expect(noteImageQueries.getById(image.id)).toBeNull();
189
+ });
190
+ });