@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,107 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { isSealed, open, seal, SECRET_COLUMNS } from '../crypto';
3
+ import { debug } from '$shared/utils/logger';
4
+
5
+ export const description = 'Re-encrypt every stored secret with the AES-256-GCM envelope';
6
+
7
+ /**
8
+ * Seal the secrets that were written before the crypto layer existed.
9
+ *
10
+ * THIS MUST USE RAW SQL. The query modules now seal on write and open on read,
11
+ * so routing this through them would encrypt an already-encrypted value on the
12
+ * way in and hand back plaintext on the way out — the migration would appear to
13
+ * do nothing while corrupting every row it touched.
14
+ *
15
+ * Two properties of the envelope make the pass safe to interrupt and safe to
16
+ * repeat: an unprefixed value is pre-migration plaintext and gets sealed, and a
17
+ * value that already carries the prefix is left exactly as it is. A half-applied
18
+ * migration therefore reads correctly, and a re-run cannot double-encrypt.
19
+ *
20
+ * `integration_accounts` is deliberately absent: migration 073 creates it, and
21
+ * everything written to it is sealed from the first insert.
22
+ */
23
+ const TABLES: Record<string, readonly string[]> = {
24
+ mcp_servers: SECRET_COLUMNS.mcp_servers!,
25
+ db_client_connections: SECRET_COLUMNS.db_client_connections!,
26
+ ssh_connections: SECRET_COLUMNS.ssh_connections!,
27
+ engine_accounts: SECRET_COLUMNS.engine_accounts!
28
+ };
29
+
30
+ function existingTables(db: DatabaseConnection): Set<string> {
31
+ const rows = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table'`).all() as { name: string }[];
32
+ return new Set(rows.map((row) => row.name));
33
+ }
34
+
35
+ /**
36
+ * Walk one column and rewrite each value through `transform`.
37
+ *
38
+ * Targeted by `rowid` rather than a primary key: the four tables use three
39
+ * different key names and types, and `rowid` is identical on all of them.
40
+ */
41
+ function rewriteColumn(
42
+ db: DatabaseConnection,
43
+ table: string,
44
+ column: string,
45
+ transform: (value: string) => string | null
46
+ ): number {
47
+ const rows = db.prepare(
48
+ `SELECT rowid AS rid, ${column} AS value FROM ${table} WHERE ${column} IS NOT NULL AND ${column} != ''`
49
+ ).all() as { rid: number; value: unknown }[];
50
+
51
+ const update = db.prepare(`UPDATE ${table} SET ${column} = ? WHERE rowid = ?`);
52
+ let changed = 0;
53
+
54
+ for (const row of rows) {
55
+ if (typeof row.value !== 'string') continue;
56
+ const next = transform(row.value);
57
+ if (next === null || next === row.value) continue;
58
+ update.run(next, row.rid);
59
+ changed += 1;
60
+ }
61
+
62
+ return changed;
63
+ }
64
+
65
+ export const up = (db: DatabaseConnection): void => {
66
+ debug.log('migration', 'Sealing stored secrets...');
67
+
68
+ const present = existingTables(db);
69
+ let total = 0;
70
+
71
+ for (const [table, columns] of Object.entries(TABLES)) {
72
+ if (!present.has(table)) continue;
73
+ for (const column of columns) {
74
+ total += rewriteColumn(db, table, column, (value) => (isSealed(value) ? null : seal(value)));
75
+ }
76
+ }
77
+
78
+ debug.log('migration', `Sealed ${total} secret value(s)`);
79
+ };
80
+
81
+ /**
82
+ * Unseal everything back to plaintext.
83
+ *
84
+ * A rollback that left ciphertext behind would be data loss the moment the key
85
+ * file went away, so `down()` has to be a real decryption pass rather than a
86
+ * no-op. A value the active key cannot open is left untouched: overwriting it
87
+ * with null would destroy the only copy, and leaving the envelope in place at
88
+ * least keeps it recoverable once the right key comes back.
89
+ */
90
+ export const down = (db: DatabaseConnection): void => {
91
+ debug.log('migration', 'Unsealing stored secrets...');
92
+
93
+ const present = existingTables(db);
94
+ let total = 0;
95
+
96
+ for (const [table, columns] of Object.entries(TABLES)) {
97
+ if (!present.has(table)) continue;
98
+ for (const column of columns) {
99
+ total += rewriteColumn(db, table, column, (value) => {
100
+ if (!isSealed(value)) return null;
101
+ return open(value);
102
+ });
103
+ }
104
+ }
105
+
106
+ debug.log('migration', `Unsealed ${total} secret value(s)`);
107
+ };
@@ -0,0 +1,119 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create integration_accounts, integration_projections and integration_webhook_deliveries';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating integration_accounts table...');
8
+
9
+ // One row per connected third-party account, and the ONLY place that
10
+ // account's credential lives. Everything that talks to the service reads
11
+ // through here instead of keeping its own copy.
12
+ //
13
+ // `(provider, label)` is the identity: two projects pointing at different
14
+ // orgs of the same service are two accounts with two labels, not one row
15
+ // scoped twice. `project_id` is a BINDING on top of that identity — null
16
+ // means the account is available to every project.
17
+ //
18
+ // `credentials` is sealed at rest by the query layer (see
19
+ // backend/database/crypto). It is a JSON object because the shape differs
20
+ // per provider, and the whole blob is sealed rather than field-by-field.
21
+ db.exec(`
22
+ CREATE TABLE IF NOT EXISTS integration_accounts (
23
+ id TEXT PRIMARY KEY,
24
+ provider TEXT NOT NULL,
25
+ label TEXT NOT NULL,
26
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
27
+ auth_method TEXT NOT NULL,
28
+ credentials TEXT NOT NULL DEFAULT '{}',
29
+ capabilities TEXT NOT NULL DEFAULT '[]',
30
+ status TEXT NOT NULL DEFAULT 'unknown'
31
+ CHECK (status IN ('unknown','ok','needs_auth','needs_config','error')),
32
+ status_detail TEXT,
33
+ checked_at TEXT,
34
+ is_enabled INTEGER NOT NULL DEFAULT 1,
35
+ created_at TEXT NOT NULL,
36
+ updated_at TEXT NOT NULL,
37
+ UNIQUE (provider, label)
38
+ )
39
+ `);
40
+
41
+ db.exec(`
42
+ CREATE INDEX IF NOT EXISTS idx_integration_accounts_provider
43
+ ON integration_accounts(provider)
44
+ `);
45
+
46
+ db.exec(`
47
+ CREATE INDEX IF NOT EXISTS idx_integration_accounts_project
48
+ ON integration_accounts(project_id)
49
+ `);
50
+
51
+ debug.log('migration', 'Creating integration_projections table...');
52
+
53
+ // A projection is a row on another surface that was DERIVED from an account
54
+ // — an `mcp_servers` row for the agent-tools capability, a
55
+ // `db_client_connections` row for a database one. This table is the link,
56
+ // and it is what makes re-projection and cleanup possible without any
57
+ // surface having to know accounts exist.
58
+ //
59
+ // `adopted` is the whole reason this is a table rather than a naming
60
+ // convention: when a projection lands on a slug the user had already
61
+ // installed by hand, we take ownership of the EXISTING row instead of
62
+ // creating a sibling, and mark it adopted so disconnecting releases it
63
+ // rather than deleting what the user built.
64
+ //
65
+ // `restore_json` is what makes that release honest. Adopting a row
66
+ // overwrites the credential the user had configured on it; without a
67
+ // snapshot, "we left your row intact" would mean leaving behind a row
68
+ // pointing at a credential we just deleted.
69
+ db.exec(`
70
+ CREATE TABLE IF NOT EXISTS integration_projections (
71
+ account_id TEXT NOT NULL REFERENCES integration_accounts(id) ON DELETE CASCADE,
72
+ capability TEXT NOT NULL,
73
+ target_kind TEXT NOT NULL,
74
+ target_id TEXT NOT NULL,
75
+ adopted INTEGER NOT NULL DEFAULT 0,
76
+ restore_json TEXT,
77
+ created_at TEXT NOT NULL,
78
+ PRIMARY KEY (account_id, capability, target_kind)
79
+ )
80
+ `);
81
+
82
+ db.exec(`
83
+ CREATE INDEX IF NOT EXISTS idx_integration_projections_target
84
+ ON integration_projections(target_kind, target_id)
85
+ `);
86
+
87
+ debug.log('migration', 'Creating integration_webhook_deliveries table...');
88
+
89
+ // Replay rejection. The UNIQUE key is the check: an INSERT that violates it
90
+ // IS the duplicate detection, atomically. A read-then-write would let two
91
+ // concurrent deliveries of the same event both pass the read.
92
+ db.exec(`
93
+ CREATE TABLE IF NOT EXISTS integration_webhook_deliveries (
94
+ provider TEXT NOT NULL,
95
+ delivery_id TEXT NOT NULL,
96
+ received_at TEXT NOT NULL,
97
+ PRIMARY KEY (provider, delivery_id)
98
+ )
99
+ `);
100
+
101
+ db.exec(`
102
+ CREATE INDEX IF NOT EXISTS idx_integration_webhook_received
103
+ ON integration_webhook_deliveries(received_at)
104
+ `);
105
+
106
+ debug.log('migration', 'integration tables created');
107
+ };
108
+
109
+ export const down = (db: DatabaseConnection): void => {
110
+ debug.log('migration', 'Dropping integration tables...');
111
+ db.exec('DROP INDEX IF EXISTS idx_integration_webhook_received');
112
+ db.exec('DROP TABLE IF EXISTS integration_webhook_deliveries');
113
+ db.exec('DROP INDEX IF EXISTS idx_integration_projections_target');
114
+ db.exec('DROP TABLE IF EXISTS integration_projections');
115
+ db.exec('DROP INDEX IF EXISTS idx_integration_accounts_project');
116
+ db.exec('DROP INDEX IF EXISTS idx_integration_accounts_provider');
117
+ db.exec('DROP TABLE IF EXISTS integration_accounts');
118
+ debug.log('migration', 'integration tables dropped');
119
+ };
@@ -0,0 +1,94 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create work_bindings and work_links for the Issues & PRs surface';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating work_bindings table...');
8
+
9
+ // Which remote project a Clopen project is looking at, through one account.
10
+ //
11
+ // This belongs to the SURFACE, not to the account layer: an account is
12
+ // instance-wide (one GitHub token), while "which repo is this project" is
13
+ // per project. Two projects sharing one token is the normal case, and it is
14
+ // exactly the case a column on `integration_accounts` could not express.
15
+ //
16
+ // `locator` is provider-specific and opaque here — `owner/repo` for GitHub,
17
+ // a team key for a tracker. `detected` records that nobody chose it; it was
18
+ // read off the git remote. Keeping that flag is what lets the UI say "from
19
+ // your origin remote" instead of presenting a guess as a decision.
20
+ //
21
+ // `config_json` holds the per-binding behaviour: which state to move an item
22
+ // to on start-work and on PR open, and the branch template. It is NOT a
23
+ // secret and is stored in plain JSON.
24
+ db.exec(`
25
+ CREATE TABLE IF NOT EXISTS work_bindings (
26
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
27
+ account_id TEXT NOT NULL REFERENCES integration_accounts(id) ON DELETE CASCADE,
28
+ locator TEXT NOT NULL,
29
+ detected INTEGER NOT NULL DEFAULT 0,
30
+ default_branch TEXT,
31
+ config_json TEXT NOT NULL DEFAULT '{}',
32
+ created_at TEXT NOT NULL,
33
+ updated_at TEXT NOT NULL,
34
+ PRIMARY KEY (project_id, account_id)
35
+ )
36
+ `);
37
+
38
+ db.exec(`
39
+ CREATE INDEX IF NOT EXISTS idx_work_bindings_account
40
+ ON work_bindings(account_id)
41
+ `);
42
+
43
+ debug.log('migration', 'Creating work_links table...');
44
+
45
+ // The link between a remote work item and the local work started for it.
46
+ //
47
+ // This is the ONLY thing about a work item that is persisted. Titles, bodies
48
+ // and comments are never copied into the database: they go stale, they turn
49
+ // a read-only surface into a cache that has to be invalidated, and the
50
+ // provider is always the truthful answer. What cannot be re-derived is which
51
+ // worktree and session someone opened for issue 123 — so that, and only
52
+ // that, is stored.
53
+ //
54
+ // Both foreign keys are ON DELETE SET NULL rather than CASCADE: deleting the
55
+ // worktree after applying its changes must not erase the record that this
56
+ // branch belongs to that issue, because the PR composer reads it to prefill
57
+ // "Closes #123" long after the worktree is gone.
58
+ db.exec(`
59
+ CREATE TABLE IF NOT EXISTS work_links (
60
+ id TEXT PRIMARY KEY,
61
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
62
+ account_id TEXT NOT NULL REFERENCES integration_accounts(id) ON DELETE CASCADE,
63
+ item_kind TEXT NOT NULL CHECK (item_kind IN ('issue','pull-request')),
64
+ item_identifier TEXT NOT NULL,
65
+ item_title TEXT,
66
+ item_url TEXT,
67
+ worktree_id TEXT REFERENCES worktrees(id) ON DELETE SET NULL,
68
+ session_id TEXT REFERENCES chat_sessions(id) ON DELETE SET NULL,
69
+ branch TEXT,
70
+ created_at TEXT NOT NULL,
71
+ UNIQUE (project_id, account_id, item_kind, item_identifier)
72
+ )
73
+ `);
74
+
75
+ db.exec(`
76
+ CREATE INDEX IF NOT EXISTS idx_work_links_project
77
+ ON work_links(project_id)
78
+ `);
79
+
80
+ // The PR composer's lookup is "which item does this branch belong to", so
81
+ // that is the index it gets.
82
+ db.exec(`
83
+ CREATE INDEX IF NOT EXISTS idx_work_links_branch
84
+ ON work_links(project_id, branch)
85
+ `);
86
+
87
+ debug.log('migration', 'Work tables created');
88
+ };
89
+
90
+ export const down = (db: DatabaseConnection): void => {
91
+ debug.log('migration', 'Dropping work tables...');
92
+ db.exec('DROP TABLE IF EXISTS work_links');
93
+ db.exec('DROP TABLE IF EXISTS work_bindings');
94
+ };
@@ -69,6 +69,10 @@ import * as migration067 from './067_add_memory_graph_layout';
69
69
  import * as migration068 from './068_create_engine_config_revision';
70
70
  import * as migration069 from './069_create_ssh_client_tables';
71
71
  import * as migration070 from './070_create_worktrees_table';
72
+ import * as migration071 from './071_create_notes_tables';
73
+ import * as migration072 from './072_encrypt_stored_secrets';
74
+ import * as migration073 from './073_create_integration_tables';
75
+ import * as migration074 from './074_create_work_tables';
72
76
 
73
77
  // Export all migrations in order
74
78
  export const migrations = [
@@ -491,6 +495,30 @@ export const migrations = [
491
495
  description: migration070.description,
492
496
  up: migration070.up,
493
497
  down: migration070.down
498
+ },
499
+ {
500
+ id: '071',
501
+ description: migration071.description,
502
+ up: migration071.up,
503
+ down: migration071.down
504
+ },
505
+ {
506
+ id: '072',
507
+ description: migration072.description,
508
+ up: migration072.up,
509
+ down: migration072.down
510
+ },
511
+ {
512
+ id: '073',
513
+ description: migration073.description,
514
+ up: migration073.up,
515
+ down: migration073.down
516
+ },
517
+ {
518
+ id: '074',
519
+ description: migration074.description,
520
+ up: migration074.up,
521
+ down: migration074.down
494
522
  }
495
523
  ];
496
524
 
@@ -1,4 +1,5 @@
1
1
  import { getDatabase } from '../index';
2
+ import { openRow, sealFor } from '../crypto';
2
3
  import type { DBDbClientConnectionRow } from '$shared/types/database/schema';
3
4
  import type {
4
5
  DbClientConnection,
@@ -9,6 +10,16 @@ import type {
9
10
  DbSslMode
10
11
  } from '$shared/types/db-client';
11
12
 
13
+ // Passwords, SSH passwords, private keys and passphrases are sealed at rest
14
+ // (see backend/database/crypto). Every read below opens them first, so the
15
+ // drivers and the panel keep seeing plaintext exactly as before.
16
+ const TABLE = 'db_client_connections';
17
+
18
+ /** Open the sealed columns on a row straight out of SQLite. */
19
+ function openConnectionRow<T extends DBDbClientConnectionRow | null>(row: T): T {
20
+ return (row ? openRow(TABLE, row) : row) as T;
21
+ }
22
+
12
23
  const DEFAULT_SSH: DbClientSshConfig = {
13
24
  enabled: false,
14
25
  connectionId: null,
@@ -136,9 +147,9 @@ function normalizeInput(input: DbClientConnectionInput, ownerUserId: string | nu
136
147
 
137
148
  function getRowById(id: string): DBDbClientConnectionRow | null {
138
149
  const db = getDatabase();
139
- return db.prepare(`
150
+ return openConnectionRow(db.prepare(`
140
151
  SELECT * FROM db_client_connections WHERE id = ?
141
- `).get(id) as DBDbClientConnectionRow | null;
152
+ `).get(id) as DBDbClientConnectionRow | null);
142
153
  }
143
154
 
144
155
  function insertConnection(input: DbClientConnectionInput, ownerUserId: string | null): DbClientConnection {
@@ -169,16 +180,16 @@ function insertConnection(input: DbClientConnectionInput, ownerUserId: string |
169
180
  )
170
181
  `).run(
171
182
  id, params.name, params.driver,
172
- params.host, params.port, params.username, params.password, params.database,
183
+ params.host, params.port, params.username, sealFor(TABLE, 'password', params.password), params.database,
173
184
  params.sslMode, params.sslCa,
174
185
  params.ssh.enabled ? 1 : 0,
175
186
  params.ssh.host || null,
176
187
  params.ssh.port,
177
188
  params.ssh.username || null,
178
189
  params.ssh.authMethod,
179
- params.ssh.password || null,
180
- params.ssh.privateKey || null,
181
- params.ssh.passphrase || null,
190
+ sealFor(TABLE, 'ssh_password', params.ssh.password || null),
191
+ sealFor(TABLE, 'ssh_private_key', params.ssh.privateKey || null),
192
+ sealFor(TABLE, 'ssh_passphrase', params.ssh.passphrase || null),
182
193
  params.ssh.connectionId || null,
183
194
  JSON.stringify(params.options),
184
195
  params.color,
@@ -207,7 +218,7 @@ export const dbClientConnectionQueries = {
207
218
  ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
208
219
  `).all(userId)) as DBDbClientConnectionRow[];
209
220
 
210
- return rows.map((row) => redactConnectionSecrets(rowToConnection(row)));
221
+ return rows.map((row) => redactConnectionSecrets(rowToConnection(openConnectionRow(row))));
211
222
  },
212
223
 
213
224
  getForUser(id: string, userId: string, isAdmin: boolean): DbClientConnection | null {
@@ -232,7 +243,7 @@ export const dbClientConnectionQueries = {
232
243
  SELECT * FROM db_client_connections
233
244
  ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
234
245
  `).all() as DBDbClientConnectionRow[];
235
- return rows.map(rowToConnection);
246
+ return rows.map((row) => rowToConnection(openConnectionRow(row)));
236
247
  },
237
248
 
238
249
  get(id: string): DbClientConnection | null {
@@ -268,7 +279,7 @@ export const dbClientConnectionQueries = {
268
279
  if (patch.host !== undefined) push('host', patch.host || null);
269
280
  if (patch.port !== undefined) push('port', patch.port ?? null);
270
281
  if (patch.username !== undefined) push('username', patch.username || null);
271
- if (patch.password !== undefined && patch.password !== '') push('password', patch.password);
282
+ if (patch.password !== undefined && patch.password !== '') push('password', sealFor(TABLE, 'password', patch.password));
272
283
  if (patch.database !== undefined) push('database', patch.database || null);
273
284
  if (patch.sslMode !== undefined) push('ssl_mode', patch.sslMode);
274
285
  if (patch.sslCa !== undefined) push('ssl_ca', patch.sslCa || null);
@@ -297,9 +308,9 @@ export const dbClientConnectionQueries = {
297
308
  push('ssh_port', merged.port);
298
309
  push('ssh_username', merged.username || null);
299
310
  push('ssh_auth_method', merged.authMethod);
300
- push('ssh_password', sshPassword);
301
- push('ssh_private_key', sshPrivateKey);
302
- push('ssh_passphrase', sshPassphrase);
311
+ push('ssh_password', sealFor(TABLE, 'ssh_password', sshPassword));
312
+ push('ssh_private_key', sealFor(TABLE, 'ssh_private_key', sshPrivateKey));
313
+ push('ssh_passphrase', sealFor(TABLE, 'ssh_passphrase', sshPassphrase));
303
314
  push('ssh_connection_id', merged.connectionId || null);
304
315
  }
305
316
 
@@ -15,6 +15,7 @@
15
15
 
16
16
  import type { EngineType } from '$shared/types/unified';
17
17
  import { getDatabase } from '../index';
18
+ import { openRow, sealFor } from '../crypto';
18
19
 
19
20
  // ============================================================================
20
21
  // Types
@@ -50,6 +51,15 @@ export interface EngineProviderWithAccounts extends EngineProvider {
50
51
  // Queries
51
52
  // ============================================================================
52
53
 
54
+ // `engine_accounts.credential` is sealed at rest (see backend/database/crypto).
55
+ // Every account read opens it, so the adapters keep receiving the raw token.
56
+ const ACCOUNTS_TABLE = 'engine_accounts';
57
+
58
+ /** Open the sealed credential on a row straight out of SQLite. */
59
+ function openAccount<T extends EngineAccount | null>(row: T): T {
60
+ return (row ? openRow(ACCOUNTS_TABLE, row) : row) as T;
61
+ }
62
+
53
63
  export const engineQueries = {
54
64
  // ------------------------------------------------------------------
55
65
  // Providers
@@ -150,21 +160,21 @@ export const engineQueries = {
150
160
 
151
161
  getAccount(id: number): EngineAccount | null {
152
162
  const db = getDatabase();
153
- return db.prepare(`SELECT * FROM engine_accounts WHERE id = ?`).get(id) as EngineAccount | null;
163
+ return openAccount(db.prepare(`SELECT * FROM engine_accounts WHERE id = ?`).get(id) as EngineAccount | null);
154
164
  },
155
165
 
156
166
  getAccountsByProvider(providerId: number): EngineAccount[] {
157
167
  const db = getDatabase();
158
- return db.prepare(
168
+ return (db.prepare(
159
169
  `SELECT * FROM engine_accounts WHERE provider_id = ? ORDER BY created_at ASC`
160
- ).all(providerId) as EngineAccount[];
170
+ ).all(providerId) as EngineAccount[]).map((row) => openAccount(row));
161
171
  },
162
172
 
163
173
  getActiveAccount(providerId: number): EngineAccount | null {
164
174
  const db = getDatabase();
165
- return db.prepare(
175
+ return openAccount(db.prepare(
166
176
  `SELECT * FROM engine_accounts WHERE provider_id = ? AND is_active = 1`
167
- ).get(providerId) as EngineAccount | null;
177
+ ).get(providerId) as EngineAccount | null);
168
178
  },
169
179
 
170
180
  /**
@@ -173,14 +183,14 @@ export const engineQueries = {
173
183
  */
174
184
  getActiveAccountForEngine(engineType: EngineType): EngineAccount | null {
175
185
  const db = getDatabase();
176
- return db.prepare(`
186
+ return openAccount(db.prepare(`
177
187
  SELECT a.*
178
188
  FROM engine_accounts a
179
189
  JOIN engine_providers p ON p.id = a.provider_id
180
190
  WHERE p.engine_type = ? AND p.is_enabled = 1 AND a.is_active = 1
181
191
  ORDER BY p.created_at ASC, a.created_at ASC
182
192
  LIMIT 1
183
- `).get(engineType) as EngineAccount | null;
193
+ `).get(engineType) as EngineAccount | null);
184
194
  },
185
195
 
186
196
  createAccount(providerId: number, name: string, credential: string): EngineAccount {
@@ -195,10 +205,10 @@ export const engineQueries = {
195
205
  const result = db.prepare(`
196
206
  INSERT INTO engine_accounts (provider_id, name, credential, is_active)
197
207
  VALUES (?, ?, ?, ?)
198
- `).run(providerId, name, credential, isActive) as { lastInsertRowid: number | bigint };
208
+ `).run(providerId, name, sealFor(ACCOUNTS_TABLE, 'credential', credential), isActive) as { lastInsertRowid: number | bigint };
199
209
 
200
210
  const id = Number(result.lastInsertRowid);
201
- return db.prepare(`SELECT * FROM engine_accounts WHERE id = ?`).get(id) as EngineAccount;
211
+ return openAccount(db.prepare(`SELECT * FROM engine_accounts WHERE id = ?`).get(id) as EngineAccount);
202
212
  },
203
213
 
204
214
  switchAccount(accountId: number): void {
@@ -242,7 +252,10 @@ export const engineQueries = {
242
252
  */
243
253
  updateAccountCredential(accountId: number, credential: string): void {
244
254
  const db = getDatabase();
245
- db.prepare(`UPDATE engine_accounts SET credential = ? WHERE id = ?`).run(credential, accountId);
255
+ db.prepare(`UPDATE engine_accounts SET credential = ? WHERE id = ?`).run(
256
+ sealFor(ACCOUNTS_TABLE, 'credential', credential),
257
+ accountId
258
+ );
246
259
  },
247
260
 
248
261
  // ------------------------------------------------------------------
@@ -31,4 +31,9 @@ export type { PermissionSet, PermissionScope } from './permission-set-queries';
31
31
  export { graphQueries, deriveDigest, entityKeyFor, DIGEST_VERSION } from './graph-queries';
32
32
  export { memoryQueueQueries, type QueuedExtraction } from './memory-queue-queries';
33
33
  export { profileQueries, PROFILE_ITEM_TYPES } from './profile-queries';
34
- export type { ProfileRow, ProfileItemRow, ProfileInput, ProfileItemInput, ProfileItemType } from './profile-queries';
34
+ export type { ProfileRow, ProfileItemRow, ProfileInput, ProfileItemInput, ProfileItemType } from './profile-queries';
35
+ export { noteQueries, noteCollectionQueries, noteImageQueries } from './note-queries';
36
+ export { integrationAccountQueries, integrationProjectionQueries, integrationWebhookQueries } from './integration-queries';
37
+ export type { IntegrationAccountRow, IntegrationAccountInput, IntegrationProjectionRow } from './integration-queries';
38
+ export { workBindingQueries, workLinkQueries, parseBindingConfig } from './work-queries';
39
+ export type { WorkBindingRow, WorkLinkRow } from './work-queries';