@myrialabs/clopen 0.4.37 → 0.4.39

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 (193) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +39 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/chat/stream-manager.ts +1 -1
  5. package/backend/database/crypto/envelope.test.ts +93 -0
  6. package/backend/database/crypto/envelope.ts +127 -0
  7. package/backend/database/crypto/index.ts +22 -0
  8. package/backend/database/crypto/master-key.ts +129 -0
  9. package/backend/database/crypto/secret-columns.ts +151 -0
  10. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  11. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  12. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  13. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  14. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  15. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  16. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  17. package/backend/database/migrations/index.ts +49 -0
  18. package/backend/database/queries/db-client-connection-queries.ts +42 -12
  19. package/backend/database/queries/deploy-queries.ts +124 -0
  20. package/backend/database/queries/engine-queries.ts +23 -10
  21. package/backend/database/queries/graph-queries.ts +291 -247
  22. package/backend/database/queries/index.ts +10 -1
  23. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  24. package/backend/database/queries/integration-queries.ts +325 -0
  25. package/backend/database/queries/mcp-server-queries.ts +38 -11
  26. package/backend/database/queries/note-queries.test.ts +190 -0
  27. package/backend/database/queries/note-queries.ts +269 -0
  28. package/backend/database/queries/profile-queries.ts +1 -1
  29. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  30. package/backend/database/queries/work-queries.ts +210 -0
  31. package/backend/db-client/integrations/index.ts +37 -0
  32. package/backend/db-client/integrations/links.ts +533 -0
  33. package/backend/db-client/integrations/projector.test.ts +280 -0
  34. package/backend/db-client/integrations/projector.ts +256 -0
  35. package/backend/db-client/integrations/supabase-service.ts +266 -0
  36. package/backend/db-client/providers/registry.ts +27 -0
  37. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  38. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  39. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  40. package/backend/db-client/providers/supabase/client.ts +259 -0
  41. package/backend/db-client/providers/supabase/features.ts +502 -0
  42. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  43. package/backend/db-client/providers/supabase/local.ts +137 -0
  44. package/backend/db-client/providers/types.ts +137 -0
  45. package/backend/deployments/bindings.test.ts +43 -0
  46. package/backend/deployments/bindings.ts +216 -0
  47. package/backend/deployments/index.ts +53 -0
  48. package/backend/deployments/log-streams.ts +214 -0
  49. package/backend/deployments/prompts.ts +70 -0
  50. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  51. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  52. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  53. package/backend/deployments/providers/vercel/client.ts +203 -0
  54. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  55. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  56. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  57. package/backend/deployments/providers/vercel/types.ts +104 -0
  58. package/backend/deployments/registry.ts +27 -0
  59. package/backend/deployments/service.ts +458 -0
  60. package/backend/deployments/types.ts +278 -0
  61. package/backend/engine/docs/artifacts.md +22 -9
  62. package/backend/files/os-clipboard.test.ts +209 -0
  63. package/backend/files/os-clipboard.ts +567 -0
  64. package/backend/http/integration-hooks.ts +42 -0
  65. package/backend/http/notes-images.test.ts +228 -0
  66. package/backend/http/notes-images.ts +196 -0
  67. package/backend/index.ts +13 -0
  68. package/backend/integrations/accounts.ts +229 -0
  69. package/backend/integrations/health.ts +146 -0
  70. package/backend/integrations/index.ts +36 -0
  71. package/backend/integrations/projections/index.ts +0 -0
  72. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  73. package/backend/integrations/projections/mcp-projector.ts +163 -0
  74. package/backend/integrations/projections/types.ts +63 -0
  75. package/backend/integrations/registry/define.ts +38 -0
  76. package/backend/integrations/registry/index.ts +60 -0
  77. package/backend/integrations/registry/providers/context7.ts +44 -0
  78. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  79. package/backend/integrations/registry/providers/github.ts +78 -0
  80. package/backend/integrations/registry/providers/supabase.ts +61 -0
  81. package/backend/integrations/registry/providers/vercel.ts +46 -0
  82. package/backend/integrations/registry/types.ts +96 -0
  83. package/backend/integrations/webhooks/gateway.ts +160 -0
  84. package/backend/integrations/webhooks/verify.ts +65 -0
  85. package/backend/mcp/README.md +25 -3
  86. package/backend/mcp/external/config.ts +35 -1
  87. package/backend/mcp/index.ts +1 -1
  88. package/backend/mcp/internal/config.ts +1 -1
  89. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  90. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  91. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  92. package/backend/memory/README.md +57 -34
  93. package/backend/memory/compose.test.ts +3 -3
  94. package/backend/memory/compose.ts +6 -9
  95. package/backend/memory/config.ts +0 -5
  96. package/backend/memory/consolidate.ts +1 -2
  97. package/backend/memory/context.test.ts +8 -54
  98. package/backend/memory/context.ts +19 -25
  99. package/backend/memory/extract/episodic.ts +10 -12
  100. package/backend/memory/extract/index.ts +23 -52
  101. package/backend/memory/extract/scheduler.ts +3 -6
  102. package/backend/memory/index.ts +6 -5
  103. package/backend/memory/invalidate.ts +36 -48
  104. package/backend/memory/layout.ts +319 -130
  105. package/backend/memory/retention.ts +12 -42
  106. package/backend/memory/retrieval.eval.test.ts +2 -2
  107. package/backend/memory/retrieval.test.ts +228 -183
  108. package/backend/memory/retrieval.ts +22 -21
  109. package/backend/memory/revise.test.ts +62 -116
  110. package/backend/memory/revise.ts +0 -1
  111. package/backend/memory/view.ts +8 -5
  112. package/backend/notes/access.test.ts +82 -0
  113. package/backend/notes/access.ts +27 -0
  114. package/backend/notes/storage.test.ts +77 -0
  115. package/backend/notes/storage.ts +114 -0
  116. package/backend/permissions/service.ts +2 -2
  117. package/backend/profiles/service.ts +1 -1
  118. package/backend/projects/project-cleanup.ts +6 -0
  119. package/backend/snapshot/helpers.ts +35 -41
  120. package/backend/snapshot/snapshot-service.ts +90 -0
  121. package/backend/snapshot/turn-changes.test.ts +163 -0
  122. package/backend/snapshot/turn-changes.ts +131 -0
  123. package/backend/work/bindings.ts +124 -0
  124. package/backend/work/index.ts +42 -0
  125. package/backend/work/prompts.ts +150 -0
  126. package/backend/work/providers/github/actions-logs.ts +180 -0
  127. package/backend/work/providers/github/adapter.test.ts +88 -0
  128. package/backend/work/providers/github/adapter.ts +1255 -0
  129. package/backend/work/providers/github/client.ts +280 -0
  130. package/backend/work/providers/github/list-range.test.ts +158 -0
  131. package/backend/work/providers/github/token-kind.test.ts +42 -0
  132. package/backend/work/pull-requests.ts +242 -0
  133. package/backend/work/registry.ts +27 -0
  134. package/backend/work/service.ts +436 -0
  135. package/backend/work/start-work.test.ts +71 -0
  136. package/backend/work/start-work.ts +232 -0
  137. package/backend/work/types.ts +180 -0
  138. package/backend/ws/db-client/accounts.ts +225 -0
  139. package/backend/ws/db-client/connections.ts +34 -3
  140. package/backend/ws/db-client/context.ts +37 -0
  141. package/backend/ws/db-client/index.ts +20 -1
  142. package/backend/ws/db-client/supabase.ts +188 -0
  143. package/backend/ws/deployments/actions.ts +360 -0
  144. package/backend/ws/deployments/context.ts +43 -0
  145. package/backend/ws/deployments/crud.ts +152 -0
  146. package/backend/ws/deployments/index.ts +15 -0
  147. package/backend/ws/deployments/schemas.ts +183 -0
  148. package/backend/ws/files/clipboard.ts +78 -0
  149. package/backend/ws/files/index.ts +5 -0
  150. package/backend/ws/git/diff-budget.ts +70 -11
  151. package/backend/ws/index.ts +16 -2
  152. package/backend/ws/integrations/crud.ts +219 -0
  153. package/backend/ws/integrations/index.ts +22 -0
  154. package/backend/ws/mcp/crud.ts +25 -1
  155. package/backend/ws/memory/crud.ts +4 -16
  156. package/backend/ws/notes/index.ts +278 -0
  157. package/backend/ws/profiles/crud.ts +1 -1
  158. package/backend/ws/snapshot/changes.ts +279 -0
  159. package/backend/ws/snapshot/index.ts +4 -3
  160. package/backend/ws/work/actions.ts +206 -0
  161. package/backend/ws/work/context.ts +51 -0
  162. package/backend/ws/work/crud.ts +347 -0
  163. package/backend/ws/work/index.ts +17 -0
  164. package/backend/ws/work/pull-requests.ts +177 -0
  165. package/backend/ws/work/schemas.ts +226 -0
  166. package/dist/assets/{index-sJmS_CCm.js → index-BrF6nqld.js} +1 -1
  167. package/dist/assets/{index-Bik9TCBi.js → index-C8Gi-b6U.js} +1 -1
  168. package/dist/assets/main-Bd3gb79F.css +1 -0
  169. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  170. package/dist/index.html +2 -2
  171. package/package.json +1 -1
  172. package/shared/constants/engine-tools.ts +1 -1
  173. package/shared/constants/tool-icons.ts +42 -0
  174. package/shared/types/database/schema.ts +41 -0
  175. package/shared/types/db-client/connection.ts +6 -0
  176. package/shared/types/db-client/index.ts +2 -0
  177. package/shared/types/db-client/integrations.ts +174 -0
  178. package/shared/types/db-client/supabase.ts +131 -0
  179. package/shared/types/deployments.ts +382 -0
  180. package/shared/types/integrations.ts +140 -0
  181. package/shared/types/memory.ts +34 -51
  182. package/shared/types/stores/settings.ts +8 -0
  183. package/shared/types/ui/components.ts +1 -1
  184. package/shared/types/work.ts +426 -0
  185. package/shared/utils/diff-calculator.test.ts +89 -0
  186. package/shared/utils/diff-calculator.ts +30 -65
  187. package/shared/utils/logger.ts +4 -0
  188. package/backend/memory/extract/languages.ts +0 -176
  189. package/backend/memory/extract/structural.test.ts +0 -215
  190. package/backend/memory/extract/structural.ts +0 -364
  191. package/backend/ws/snapshot/content.ts +0 -85
  192. package/dist/assets/main-DLqolBI2.css +0 -1
  193. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -31,4 +31,13 @@ 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 { integrationDbLinkQueries } from './integration-db-link-queries';
39
+ export type { IntegrationDbLinkRow, IntegrationDbLinkInput } from './integration-db-link-queries';
40
+ export { workBindingQueries, workLinkQueries, parseBindingConfig } from './work-queries';
41
+ export type { WorkBindingRow, WorkLinkRow } from './work-queries';
42
+ export { deployBindingQueries, parseDeployConfig } from './deploy-queries';
43
+ export type { DeployBindingRow } from './deploy-queries';
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Which remote databases an account brought into DB Client.
3
+ *
4
+ * A link is the answer to "which one", asked once per database rather than once
5
+ * per credential. It is the database counterpart of `deploy_bindings`: the
6
+ * account holds the token, and everything that varies per remote database —
7
+ * which project, which connection mode, and the password the provider will not
8
+ * hand back — lives here.
9
+ *
10
+ * `secrets` is sealed at rest by the crypto layer, so callers here hand in and
11
+ * receive a plain object and never see an envelope. A blob that the active key
12
+ * cannot open reads as `{}`, which the projector treats exactly as it treats a
13
+ * link whose password was never entered: it projects a connection that cannot
14
+ * log in and says so, rather than throwing on every read path.
15
+ */
16
+
17
+ import { getDatabase } from '../index';
18
+ import { openRow, sealFor } from '../crypto';
19
+ import type { DbDriver } from '$shared/types/db-client';
20
+
21
+ const TABLE = 'integration_db_links';
22
+
23
+ export interface IntegrationDbLinkRow {
24
+ id: string;
25
+ account_id: string;
26
+ /** The provider's own id for the database — a Supabase project ref. */
27
+ remote_ref: string;
28
+ label: string;
29
+ driver: DbDriver;
30
+ mode: string;
31
+ /** Sealed on disk, plain JSON string here. Null when the key could not open it. */
32
+ secrets: string | null;
33
+ config_json: string;
34
+ detected: number;
35
+ created_at: string;
36
+ updated_at: string;
37
+ }
38
+
39
+ export interface IntegrationDbLinkInput {
40
+ accountId: string;
41
+ remoteRef: string;
42
+ label: string;
43
+ driver: DbDriver;
44
+ mode: string;
45
+ secrets: Record<string, string>;
46
+ config: Record<string, unknown>;
47
+ detected?: boolean;
48
+ }
49
+
50
+ function parse<T>(raw: string | null, fallback: T): T {
51
+ if (!raw) return fallback;
52
+ try {
53
+ const parsed = JSON.parse(raw);
54
+ return (parsed ?? fallback) as T;
55
+ } catch {
56
+ return fallback;
57
+ }
58
+ }
59
+
60
+ function openLink<T extends IntegrationDbLinkRow | null>(row: T): T {
61
+ return (row ? openRow(TABLE, row) : row) as T;
62
+ }
63
+
64
+ export const integrationDbLinkQueries = {
65
+ getForAccount(accountId: string): IntegrationDbLinkRow[] {
66
+ const db = getDatabase();
67
+ return (db.prepare(
68
+ `SELECT * FROM integration_db_links WHERE account_id = ? ORDER BY label ASC`
69
+ ).all(accountId) as IntegrationDbLinkRow[]).map((row) => openLink(row));
70
+ },
71
+
72
+ getById(id: string): IntegrationDbLinkRow | null {
73
+ const db = getDatabase();
74
+ return openLink(
75
+ db.prepare(`SELECT * FROM integration_db_links WHERE id = ?`).get(id) as IntegrationDbLinkRow | null
76
+ );
77
+ },
78
+
79
+ getByRef(accountId: string, remoteRef: string): IntegrationDbLinkRow | null {
80
+ const db = getDatabase();
81
+ return openLink(
82
+ db.prepare(
83
+ `SELECT * FROM integration_db_links WHERE account_id = ? AND remote_ref = ?`
84
+ ).get(accountId, remoteRef) as IntegrationDbLinkRow | null
85
+ );
86
+ },
87
+
88
+ secretsOf(row: IntegrationDbLinkRow): Record<string, string> {
89
+ return parse<Record<string, string>>(row.secrets, {});
90
+ },
91
+
92
+ configOf<T = Record<string, unknown>>(row: IntegrationDbLinkRow): T {
93
+ return parse<T>(row.config_json, {} as T);
94
+ },
95
+
96
+ create(input: IntegrationDbLinkInput): IntegrationDbLinkRow {
97
+ const db = getDatabase();
98
+ const id = crypto.randomUUID();
99
+ const now = new Date().toISOString();
100
+
101
+ db.prepare(`
102
+ INSERT INTO integration_db_links (
103
+ id, account_id, remote_ref, label, driver, mode,
104
+ secrets, config_json, detected, created_at, updated_at
105
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
106
+ `).run(
107
+ id,
108
+ input.accountId,
109
+ input.remoteRef,
110
+ input.label,
111
+ input.driver,
112
+ input.mode,
113
+ sealFor(TABLE, 'secrets', JSON.stringify(input.secrets)),
114
+ JSON.stringify(input.config),
115
+ input.detected ? 1 : 0,
116
+ now,
117
+ now
118
+ );
119
+
120
+ return this.getById(id)!;
121
+ },
122
+
123
+ /**
124
+ * Patch a link.
125
+ *
126
+ * `secrets` is REPLACED rather than merged, and the caller merges — an empty
127
+ * password field means "not re-typed", not "clear it", the same rule the
128
+ * db-client and SSH forms already use.
129
+ */
130
+ update(
131
+ id: string,
132
+ patch: { label?: string; mode?: string; secrets?: Record<string, string>; config?: Record<string, unknown> }
133
+ ): IntegrationDbLinkRow | null {
134
+ const db = getDatabase();
135
+ const sets: string[] = [];
136
+ const values: unknown[] = [];
137
+
138
+ if (patch.label !== undefined) {
139
+ sets.push('label = ?');
140
+ values.push(patch.label);
141
+ }
142
+ if (patch.mode !== undefined) {
143
+ sets.push('mode = ?');
144
+ values.push(patch.mode);
145
+ }
146
+ if (patch.secrets !== undefined) {
147
+ sets.push('secrets = ?');
148
+ values.push(sealFor(TABLE, 'secrets', JSON.stringify(patch.secrets)));
149
+ }
150
+ if (patch.config !== undefined) {
151
+ sets.push('config_json = ?');
152
+ values.push(JSON.stringify(patch.config));
153
+ }
154
+
155
+ if (sets.length === 0) return this.getById(id);
156
+
157
+ sets.push('updated_at = ?');
158
+ values.push(new Date().toISOString(), id);
159
+
160
+ db.prepare(`UPDATE integration_db_links SET ${sets.join(', ')} WHERE id = ?`).run(...values);
161
+ return this.getById(id);
162
+ },
163
+
164
+ remove(id: string): void {
165
+ const db = getDatabase();
166
+ db.prepare(`DELETE FROM integration_db_links WHERE id = ?`).run(id);
167
+ }
168
+ };
@@ -0,0 +1,325 @@
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
+ /**
235
+ * Every projection of one kind, keyed by target id.
236
+ *
237
+ * The badge on a db-client connection needs to answer "is this row managed,
238
+ * and by whom" for a whole list at once. Asking `getByTarget` per row would
239
+ * be one statement per connection on every list call.
240
+ */
241
+ getAllByKind(targetKind: IntegrationTargetKind): IntegrationProjectionRow[] {
242
+ const db = getDatabase();
243
+ return db.prepare(
244
+ `SELECT * FROM integration_projections WHERE target_kind = ?`
245
+ ).all(targetKind) as IntegrationProjectionRow[];
246
+ },
247
+
248
+ upsert(input: {
249
+ accountId: string;
250
+ capability: IntegrationCapability;
251
+ targetKind: IntegrationTargetKind;
252
+ targetId: string;
253
+ adopted: boolean;
254
+ restore: unknown | null;
255
+ }): void {
256
+ const db = getDatabase();
257
+ // The conflict target is the full key: one account can own SEVERAL rows of
258
+ // the same kind for the same capability (a database account with two
259
+ // linked projects), so `target_id` identifies the row rather than being
260
+ // something an upsert overwrites.
261
+ //
262
+ // `restore_json` is deliberately NOT updated on conflict. It is the
263
+ // snapshot of what the row looked like before we adopted it, and
264
+ // re-projecting must never replace it with a picture of our own
265
+ // credential — that is the bug the MCP projector's comment describes.
266
+ db.prepare(`
267
+ INSERT INTO integration_projections (account_id, capability, target_kind, target_id, adopted, restore_json, created_at)
268
+ VALUES (?, ?, ?, ?, ?, ?, ?)
269
+ ON CONFLICT (account_id, capability, target_kind, target_id) DO UPDATE SET
270
+ adopted = excluded.adopted
271
+ `).run(
272
+ input.accountId,
273
+ input.capability,
274
+ input.targetKind,
275
+ input.targetId,
276
+ input.adopted ? 1 : 0,
277
+ input.restore === null ? null : JSON.stringify(input.restore),
278
+ new Date().toISOString()
279
+ );
280
+ },
281
+
282
+ remove(
283
+ accountId: string,
284
+ capability: IntegrationCapability,
285
+ targetKind: IntegrationTargetKind,
286
+ targetId: string
287
+ ): void {
288
+ const db = getDatabase();
289
+ db.prepare(
290
+ `DELETE FROM integration_projections
291
+ WHERE account_id = ? AND capability = ? AND target_kind = ? AND target_id = ?`
292
+ ).run(accountId, capability, targetKind, targetId);
293
+ },
294
+
295
+ /** The snapshot taken when an existing row was adopted, or null. */
296
+ restoreOf<T>(row: IntegrationProjectionRow): T | null {
297
+ return parse<T | null>(row.restore_json, null);
298
+ }
299
+ };
300
+
301
+ export const integrationWebhookQueries = {
302
+ /**
303
+ * Record a delivery, returning false when it has already been seen.
304
+ *
305
+ * The UNIQUE constraint IS the replay check. A read-then-write would let two
306
+ * concurrent deliveries of the same event both pass the read and both run.
307
+ */
308
+ claimDelivery(provider: string, deliveryId: string): boolean {
309
+ const db = getDatabase();
310
+ const result = db.prepare(`
311
+ INSERT OR IGNORE INTO integration_webhook_deliveries (provider, delivery_id, received_at)
312
+ VALUES (?, ?, ?)
313
+ `).run(provider, deliveryId, new Date().toISOString()) as { changes: number };
314
+ return result.changes > 0;
315
+ },
316
+
317
+ /** Drop delivery ids older than the retention window so the table stays bounded. */
318
+ pruneBefore(isoTimestamp: string): number {
319
+ const db = getDatabase();
320
+ const result = db.prepare(
321
+ `DELETE FROM integration_webhook_deliveries WHERE received_at < ?`
322
+ ).run(isoTimestamp) as { changes: number };
323
+ return result.changes;
324
+ }
325
+ };
@@ -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. */