@myrialabs/clopen 0.4.38 → 0.4.40

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 (177) hide show
  1. package/backend/auth/permissions.ts +48 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +9 -1
  4. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  5. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  6. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  7. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  8. package/backend/database/migrations/index.ts +28 -0
  9. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  10. package/backend/database/queries/deploy-queries.ts +124 -0
  11. package/backend/database/queries/graph-queries.ts +291 -247
  12. package/backend/database/queries/index.ts +10 -0
  13. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  14. package/backend/database/queries/integration-queries.ts +34 -6
  15. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  16. package/backend/db-client/cloning.test.ts +161 -0
  17. package/backend/db-client/cloning.ts +672 -0
  18. package/backend/db-client/connection-url.test.ts +117 -0
  19. package/backend/db-client/connection-url.ts +126 -0
  20. package/backend/db-client/drivers/mongodb.ts +2 -14
  21. package/backend/db-client/drivers/mysql.ts +2 -8
  22. package/backend/db-client/drivers/postgres.ts +10 -13
  23. package/backend/db-client/drivers/redis.ts +2 -6
  24. package/backend/db-client/env/detect.ts +438 -0
  25. package/backend/db-client/env/diff.ts +94 -0
  26. package/backend/db-client/env/env.test.ts +574 -0
  27. package/backend/db-client/env/index.ts +15 -0
  28. package/backend/db-client/env/naming.ts +202 -0
  29. package/backend/db-client/env/service.ts +487 -0
  30. package/backend/db-client/integrations/index.ts +44 -0
  31. package/backend/db-client/integrations/links.ts +564 -0
  32. package/backend/db-client/integrations/projector.test.ts +280 -0
  33. package/backend/db-client/integrations/projector.ts +256 -0
  34. package/backend/db-client/integrations/supabase-service.ts +266 -0
  35. package/backend/db-client/providers/neon/adapter.ts +522 -0
  36. package/backend/db-client/providers/neon/api-types.ts +182 -0
  37. package/backend/db-client/providers/neon/client.ts +298 -0
  38. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  39. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  40. package/backend/db-client/providers/neon/list.test.ts +181 -0
  41. package/backend/db-client/providers/registry.ts +27 -0
  42. package/backend/db-client/providers/supabase/adapter.ts +523 -0
  43. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  44. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  45. package/backend/db-client/providers/supabase/client.ts +259 -0
  46. package/backend/db-client/providers/supabase/features.ts +502 -0
  47. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  48. package/backend/db-client/providers/supabase/local.ts +137 -0
  49. package/backend/db-client/providers/types.ts +194 -0
  50. package/backend/deployments/bindings.test.ts +43 -0
  51. package/backend/deployments/bindings.ts +216 -0
  52. package/backend/deployments/index.ts +53 -0
  53. package/backend/deployments/log-streams.ts +214 -0
  54. package/backend/deployments/prompts.ts +70 -0
  55. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  56. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  57. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  58. package/backend/deployments/providers/vercel/client.ts +203 -0
  59. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  60. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  61. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  62. package/backend/deployments/providers/vercel/types.ts +104 -0
  63. package/backend/deployments/registry.ts +27 -0
  64. package/backend/deployments/service.ts +458 -0
  65. package/backend/deployments/types.ts +278 -0
  66. package/backend/env-files/discovery.ts +48 -0
  67. package/backend/env-files/edit.ts +213 -0
  68. package/backend/env-files/env-files.test.ts +515 -0
  69. package/backend/env-files/git.ts +27 -0
  70. package/backend/env-files/index.ts +44 -0
  71. package/backend/env-files/keys.ts +69 -0
  72. package/backend/env-files/parse.ts +157 -0
  73. package/backend/env-files/write.ts +229 -0
  74. package/backend/index.ts +4 -0
  75. package/backend/integrations/health.ts +18 -4
  76. package/backend/integrations/projections/index.ts +0 -0
  77. package/backend/integrations/projections/mcp-projector.ts +7 -3
  78. package/backend/integrations/projections/types.ts +28 -9
  79. package/backend/integrations/registry/index.ts +8 -1
  80. package/backend/integrations/registry/providers/context7.ts +1 -0
  81. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  82. package/backend/integrations/registry/providers/github.ts +1 -0
  83. package/backend/integrations/registry/providers/neon.ts +55 -0
  84. package/backend/integrations/registry/providers/supabase.ts +62 -0
  85. package/backend/integrations/registry/providers/vercel.ts +47 -0
  86. package/backend/integrations/registry/types.ts +2 -0
  87. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  88. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  89. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  90. package/backend/memory/README.md +57 -34
  91. package/backend/memory/compose.test.ts +3 -3
  92. package/backend/memory/compose.ts +6 -9
  93. package/backend/memory/config.ts +0 -5
  94. package/backend/memory/consolidate.ts +1 -2
  95. package/backend/memory/context.test.ts +8 -54
  96. package/backend/memory/context.ts +19 -25
  97. package/backend/memory/extract/episodic.ts +10 -12
  98. package/backend/memory/extract/index.ts +23 -52
  99. package/backend/memory/extract/scheduler.ts +3 -6
  100. package/backend/memory/index.ts +6 -5
  101. package/backend/memory/invalidate.ts +36 -48
  102. package/backend/memory/layout.ts +319 -130
  103. package/backend/memory/retention.ts +12 -42
  104. package/backend/memory/retrieval.eval.test.ts +2 -2
  105. package/backend/memory/retrieval.test.ts +228 -183
  106. package/backend/memory/retrieval.ts +22 -21
  107. package/backend/memory/revise.test.ts +62 -116
  108. package/backend/memory/revise.ts +0 -1
  109. package/backend/memory/view.ts +8 -5
  110. package/backend/snapshot/helpers.ts +35 -41
  111. package/backend/snapshot/snapshot-service.ts +90 -0
  112. package/backend/snapshot/turn-changes.test.ts +163 -0
  113. package/backend/snapshot/turn-changes.ts +131 -0
  114. package/backend/work/start-work.ts +4 -0
  115. package/backend/worktrees/branching/engine.ts +557 -0
  116. package/backend/worktrees/branching/index.ts +56 -0
  117. package/backend/worktrees/branching/naming.test.ts +118 -0
  118. package/backend/worktrees/branching/naming.ts +97 -0
  119. package/backend/worktrees/branching/projector.test.ts +229 -0
  120. package/backend/worktrees/branching/projector.ts +139 -0
  121. package/backend/worktrees/branching/providers/neon.ts +220 -0
  122. package/backend/worktrees/branching/registry.ts +27 -0
  123. package/backend/worktrees/branching/service.ts +620 -0
  124. package/backend/worktrees/branching/suggest.test.ts +154 -0
  125. package/backend/worktrees/branching/suggest.ts +202 -0
  126. package/backend/worktrees/branching/types.ts +88 -0
  127. package/backend/worktrees/index.ts +7 -0
  128. package/backend/worktrees/service.ts +48 -1
  129. package/backend/ws/db-client/accounts.ts +225 -0
  130. package/backend/ws/db-client/connections.ts +34 -3
  131. package/backend/ws/db-client/context.ts +37 -0
  132. package/backend/ws/db-client/env.ts +142 -0
  133. package/backend/ws/db-client/index.ts +22 -1
  134. package/backend/ws/db-client/supabase.ts +188 -0
  135. package/backend/ws/deployments/actions.ts +360 -0
  136. package/backend/ws/deployments/context.ts +43 -0
  137. package/backend/ws/deployments/crud.ts +152 -0
  138. package/backend/ws/deployments/index.ts +15 -0
  139. package/backend/ws/deployments/schemas.ts +183 -0
  140. package/backend/ws/index.ts +6 -2
  141. package/backend/ws/memory/crud.ts +4 -16
  142. package/backend/ws/projects/index.ts +6 -1
  143. package/backend/ws/projects/info.ts +70 -6
  144. package/backend/ws/projects/overview.test.ts +108 -0
  145. package/backend/ws/projects/overview.ts +300 -0
  146. package/backend/ws/snapshot/changes.ts +279 -0
  147. package/backend/ws/snapshot/index.ts +4 -3
  148. package/backend/ws/system/device-info.ts +307 -76
  149. package/backend/ws/worktrees/branching.ts +212 -0
  150. package/backend/ws/worktrees/crud.ts +33 -7
  151. package/backend/ws/worktrees/index.ts +14 -0
  152. package/dist/assets/{index-DSHIANSy.js → index-D4igjF6e.js} +1 -1
  153. package/dist/assets/{index-CyH7fSbR.js → index-DONNwiXm.js} +1 -1
  154. package/dist/assets/main-BrfXH1bL.js +1205 -0
  155. package/dist/assets/main-CT1PygsW.css +1 -0
  156. package/dist/index.html +2 -2
  157. package/package.json +1 -1
  158. package/shared/constants/tool-icons.ts +13 -0
  159. package/shared/types/db-client/connection.ts +6 -0
  160. package/shared/types/db-client/env.ts +192 -0
  161. package/shared/types/db-client/index.ts +3 -0
  162. package/shared/types/db-client/integrations.ts +204 -0
  163. package/shared/types/db-client/supabase.ts +131 -0
  164. package/shared/types/deployments.ts +382 -0
  165. package/shared/types/integrations.ts +9 -0
  166. package/shared/types/memory.ts +34 -51
  167. package/shared/types/ui/components.ts +1 -1
  168. package/shared/types/worktree-branching.ts +315 -0
  169. package/shared/utils/diff-calculator.test.ts +89 -0
  170. package/shared/utils/diff-calculator.ts +30 -65
  171. package/shared/utils/logger.ts +2 -0
  172. package/backend/memory/extract/languages.ts +0 -176
  173. package/backend/memory/extract/structural.test.ts +0 -215
  174. package/backend/memory/extract/structural.ts +0 -364
  175. package/backend/ws/snapshot/content.ts +0 -85
  176. package/dist/assets/main-D2IOjftb.css +0 -1
  177. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -0,0 +1,225 @@
1
+ /**
2
+ * db-client — account-backed connections.
3
+ *
4
+ * db-client:providers database providers, for the link dialog
5
+ * db-client:accounts connected accounts that can supply one
6
+ * db-client:remote-databases what an account can reach
7
+ * db-client:create-options organisations and regions, for creating one
8
+ * db-client:create-group create the owning organisation
9
+ * db-client:create-database provision a new database and link it
10
+ * db-client:rename-database rename it at the provider
11
+ * db-client:delete-database destroy it at the provider, and unlink
12
+ * db-client:link bring one in
13
+ * db-client:update-link relabel / change mode / rotate the password
14
+ * db-client:unlink drop it, releasing the projected connection
15
+ * db-client:detect-local a `supabase start` stack in the working tree
16
+ * db-client:adopt-local turn that into an ordinary connection
17
+ *
18
+ * ADMIN-GATED, unlike the rest of this router. Linking projects a row that
19
+ * every admin sees, and it reads a credential belonging to the install rather
20
+ * than to the caller — the same reason `integrations:*` is admin-only. The
21
+ * ordinary connection routes stay open to members, who keep managing their own
22
+ * connections exactly as before.
23
+ */
24
+
25
+ import { t } from 'elysia';
26
+ import { createRouter } from '$shared/utils/ws-server';
27
+ import { initializeDatabase } from '../../database';
28
+ import { dbClientConnectionQueries } from '../../database/queries';
29
+ import { dbLinks, supabaseSurface } from '../../db-client/integrations';
30
+ import { localConnectionInput } from '../../db-client/providers/supabase/local';
31
+ import { ws as wsServer } from '$backend/utils/ws';
32
+ import { getDbClientPrincipal } from './access';
33
+ import { resolveDbClientProject } from './context';
34
+ import { debug } from '$shared/utils/logger';
35
+
36
+ /**
37
+ * Tell every client the connection list changed.
38
+ *
39
+ * Global rather than per-user: a projected connection is visible to every
40
+ * admin, so a client that only watched its own request would miss one appearing
41
+ * because a colleague linked it.
42
+ */
43
+ function announce(): void {
44
+ wsServer.emit.global('db-client:connections-changed', {});
45
+ }
46
+
47
+ export const accountsHandler = createRouter()
48
+ .http('db-client:providers', {
49
+ data: t.Object({}),
50
+ response: t.Object({
51
+ providers: t.Array(t.Any()),
52
+ accounts: t.Array(t.Any()),
53
+ links: t.Array(t.Any())
54
+ })
55
+ }, async () => {
56
+ await initializeDatabase();
57
+ return {
58
+ providers: dbLinks.providers(),
59
+ accounts: dbLinks.accounts(),
60
+ links: dbLinks.allLinks()
61
+ };
62
+ })
63
+
64
+ .http('db-client:remote-databases', {
65
+ data: t.Object({ accountId: t.String({ minLength: 1 }) }),
66
+ response: t.Array(t.Any())
67
+ }, async ({ data }) => {
68
+ return dbLinks.remoteDatabases(data.accountId);
69
+ })
70
+
71
+ .http('db-client:create-options', {
72
+ data: t.Object({ accountId: t.String({ minLength: 1 }) }),
73
+ response: t.Nullable(t.Any())
74
+ }, async ({ data }) => {
75
+ return dbLinks.createOptions(data.accountId);
76
+ })
77
+
78
+ .http('db-client:create-group', {
79
+ data: t.Object({
80
+ accountId: t.String({ minLength: 1 }),
81
+ name: t.String({ minLength: 1 })
82
+ }),
83
+ response: t.Object({ value: t.String(), label: t.String() })
84
+ }, async ({ data }) => {
85
+ await initializeDatabase();
86
+ return dbLinks.createGroup(data.accountId, data.name);
87
+ })
88
+
89
+ .http('db-client:create-database', {
90
+ data: t.Object({
91
+ accountId: t.String({ minLength: 1 }),
92
+ name: t.String({ minLength: 1 }),
93
+ group: t.String({ minLength: 1 }),
94
+ region: t.String({ minLength: 1 })
95
+ }),
96
+ response: t.Object({ link: t.Any(), ready: t.Boolean() })
97
+ }, async ({ data }) => {
98
+ await initializeDatabase();
99
+ // Provisioning plus the readiness wait runs past the default socket
100
+ // budget by design, so the call carries its own — a long budget, not an
101
+ // unbounded one, for the reason the Deployments surface settled on.
102
+ const result = await dbLinks.createDatabase(data);
103
+ announce();
104
+ return result;
105
+ })
106
+
107
+ .http('db-client:rename-database', {
108
+ data: t.Object({
109
+ accountId: t.String({ minLength: 1 }),
110
+ remoteRef: t.String({ minLength: 1 }),
111
+ name: t.String({ minLength: 1 })
112
+ }),
113
+ response: t.Object({ ok: t.Boolean() })
114
+ }, async ({ data }) => {
115
+ await dbLinks.renameDatabase(data.accountId, data.remoteRef, data.name);
116
+ return { ok: true };
117
+ })
118
+
119
+ .http('db-client:delete-database', {
120
+ data: t.Object({
121
+ accountId: t.String({ minLength: 1 }),
122
+ remoteRef: t.String({ minLength: 1 })
123
+ }),
124
+ response: t.Object({ ok: t.Boolean() })
125
+ }, async ({ data }) => {
126
+ await dbLinks.deleteDatabase(data.accountId, data.remoteRef);
127
+ announce();
128
+ return { ok: true };
129
+ })
130
+
131
+ .http('db-client:link', {
132
+ data: t.Object({
133
+ accountId: t.String({ minLength: 1 }),
134
+ remoteRef: t.String({ minLength: 1 }),
135
+ label: t.Optional(t.String()),
136
+ mode: t.Optional(t.String()),
137
+ secrets: t.Record(t.String(), t.String())
138
+ }),
139
+ response: t.Any()
140
+ }, async ({ data }) => {
141
+ await initializeDatabase();
142
+ const link = await dbLinks.create({
143
+ accountId: data.accountId,
144
+ remoteRef: data.remoteRef,
145
+ label: data.label,
146
+ mode: data.mode,
147
+ secrets: data.secrets
148
+ });
149
+ announce();
150
+ return link;
151
+ })
152
+
153
+ .http('db-client:update-link', {
154
+ data: t.Object({
155
+ linkId: t.String({ minLength: 1 }),
156
+ label: t.Optional(t.String()),
157
+ mode: t.Optional(t.String()),
158
+ secrets: t.Optional(t.Record(t.String(), t.String())),
159
+ refreshEndpoint: t.Optional(t.Boolean())
160
+ }),
161
+ response: t.Any()
162
+ }, async ({ data }) => {
163
+ const link = await dbLinks.update(data.linkId, {
164
+ label: data.label,
165
+ mode: data.mode,
166
+ secrets: data.secrets,
167
+ refreshEndpoint: data.refreshEndpoint
168
+ });
169
+ announce();
170
+ return link;
171
+ })
172
+
173
+ .http('db-client:unlink', {
174
+ data: t.Object({ linkId: t.String({ minLength: 1 }) }),
175
+ response: t.Object({ ok: t.Boolean() })
176
+ }, async ({ data }) => {
177
+ await dbLinks.remove(data.linkId);
178
+ announce();
179
+ return { ok: true };
180
+ })
181
+
182
+ .http('db-client:detect-local', {
183
+ data: t.Object({ projectId: t.Optional(t.String()) }),
184
+ response: t.Nullable(t.Any())
185
+ }, async ({ data, conn }) => {
186
+ const project = resolveDbClientProject(conn, data.projectId);
187
+ if (!project) return null;
188
+ const local = await supabaseSurface.detectLocal(project.root);
189
+ if (!local) return null;
190
+ return {
191
+ ref: local.ref,
192
+ configPath: local.configPath,
193
+ dbPort: local.dbPort,
194
+ // True when a connection to this stack already exists, so the panel
195
+ // offers "open" rather than "add" and never creates a duplicate.
196
+ alreadyAdded: dbClientConnectionQueries
197
+ .list()
198
+ .some((connection) => {
199
+ const marker = connection.options?.supabase as { ref?: string } | undefined;
200
+ return marker?.ref === local.ref;
201
+ })
202
+ };
203
+ })
204
+
205
+ .http('db-client:adopt-local', {
206
+ data: t.Object({ projectId: t.Optional(t.String()) }),
207
+ response: t.Any()
208
+ }, async ({ data, conn }) => {
209
+ await initializeDatabase();
210
+ const project = resolveDbClientProject(conn, data.projectId);
211
+ if (!project) throw new Error('No project is open');
212
+
213
+ const local = await supabaseSurface.detectLocal(project.root);
214
+ if (!local) throw new Error('No supabase/config.toml in this project');
215
+
216
+ // Owned by the caller, NOT by the install: a local stack is a developer's
217
+ // own database, and it is created from an ordinary member-visible route
218
+ // rather than from an account. It is not a projection and nothing
219
+ // re-derives it.
220
+ const { userId } = getDbClientPrincipal(conn);
221
+ const created = dbClientConnectionQueries.createForUser(localConnectionInput(local), userId);
222
+ debug.log('db-client', `Adopted local Supabase stack ${local.ref} as ${created.id}`);
223
+ announce();
224
+ return created;
225
+ });
@@ -14,6 +14,7 @@ import type {
14
14
  DbSslMode
15
15
  } from '$shared/types/db-client';
16
16
  import { debug } from '$shared/utils/logger';
17
+ import { dbLinks } from '../../db-client/integrations';
17
18
  import { getDbClientPrincipal, requireDbClientConnectionAccess } from './access';
18
19
 
19
20
  const driverSchema = t.Union([
@@ -101,6 +102,20 @@ function normalizeSshPatch(input: DbClientConnectionInput['ssh']): DbClientConne
101
102
  };
102
103
  }
103
104
 
105
+ /**
106
+ * The fields a user may still change on a derived connection.
107
+ *
108
+ * A projection owns where the connection points and what it logs in with. The
109
+ * colour is decoration, and the name is what the user calls it in their own
110
+ * list — neither is derived from anything, so neither is taken away.
111
+ */
112
+ function pickLocalFields(patch: Partial<DbClientConnectionInput>): Partial<DbClientConnectionInput> {
113
+ const local: Partial<DbClientConnectionInput> = {};
114
+ if (patch.name !== undefined) local.name = patch.name;
115
+ if (patch.color !== undefined) local.color = patch.color;
116
+ return local;
117
+ }
118
+
104
119
  function ensureInputDefaults(input: DbClientConnectionInput): DbClientConnectionInput {
105
120
  return {
106
121
  ...input,
@@ -117,7 +132,10 @@ export const connectionsHandler = createRouter()
117
132
  }, async ({ conn }) => {
118
133
  await initializeDatabase();
119
134
  const { userId, isAdmin } = getDbClientPrincipal(conn);
120
- return dbClientConnectionQueries.listForUser(userId, isAdmin);
135
+ // Ownership is attached HERE rather than stored on the connection: the
136
+ // answer lives in `integration_projections`, and duplicating it into a
137
+ // column would create a second place for it to be wrong.
138
+ return dbLinks.decorate(dbClientConnectionQueries.listForUser(userId, isAdmin));
121
139
  })
122
140
 
123
141
  .http('db-client:get', {
@@ -127,7 +145,7 @@ export const connectionsHandler = createRouter()
127
145
  const { userId, isAdmin } = getDbClientPrincipal(conn);
128
146
  const connection = dbClientConnectionQueries.getForUser(data.id, userId, isAdmin);
129
147
  if (!connection) throw new Error('db-client connection not found');
130
- return connection;
148
+ return { ...connection, managedBy: dbLinks.managedBy(data.id) };
131
149
  })
132
150
 
133
151
  .http('db-client:create', {
@@ -153,7 +171,13 @@ export const connectionsHandler = createRouter()
153
171
  }, async ({ data, conn }) => {
154
172
  const { userId, isAdmin } = getDbClientPrincipal(conn);
155
173
  requireDbClientConnectionAccess(conn, data.id);
156
- const patch = data.patch as Partial<DbClientConnectionInput>;
174
+ // A managed row is DERIVED. Letting the form edit its host or password
175
+ // would produce a connection the next re-projection silently reverts, so
176
+ // the two fields that are genuinely local are the only ones allowed
177
+ // through — everything else is changed by editing the link.
178
+ const patch = (dbLinks.isManaged(data.id)
179
+ ? pickLocalFields(data.patch as Partial<DbClientConnectionInput>)
180
+ : data.patch) as Partial<DbClientConnectionInput>;
157
181
  const normalized: Partial<DbClientConnectionInput> = {
158
182
  ...patch,
159
183
  ssh: patch.ssh ? normalizeSshPatch(patch.ssh) : undefined
@@ -169,6 +193,13 @@ export const connectionsHandler = createRouter()
169
193
  }, async ({ data, conn }) => {
170
194
  const { userId, isAdmin } = getDbClientPrincipal(conn);
171
195
  requireDbClientConnectionAccess(conn, data.id);
196
+ // Deleting a projected row here would leave the account owning a
197
+ // connection that no longer exists, and the next re-projection would
198
+ // recreate it — so the panel is told to unlink instead, which is the
199
+ // operation that actually means "I do not want this connection".
200
+ if (dbLinks.isManaged(data.id)) {
201
+ throw new Error('This connection comes from a connected account. Unlink it there to remove it.');
202
+ }
172
203
  await connectionManager.release(data.id);
173
204
  dbClientConnectionQueries.deleteForUser(data.id, userId, isAdmin);
174
205
  return { ok: true };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Which project a db-client route acts on.
3
+ *
4
+ * DB Client is a global surface: the connection list is not scoped to a
5
+ * project, and most routes need no project at all. But three things the
6
+ * Supabase tabs do are facts about a WORKING TREE rather than about a database
7
+ * — where the migration files are, where edge functions live, and where
8
+ * generated types get written — so those routes take an optional `projectId`
9
+ * and fall back to the connection's current one, exactly as the Deployments
10
+ * surface does.
11
+ *
12
+ * `projectId` arriving from the client is a request, not a permission:
13
+ * `requireProjectAccess` is what decides, and a route that resolves no project
14
+ * degrades to "no local files" rather than reaching for one it was not given.
15
+ */
16
+
17
+ import type { WSConnection } from '$shared/utils/ws-server';
18
+ import type { Project } from '$shared/types/database/schema';
19
+ import { ws } from '$backend/utils/ws';
20
+ import { requireProjectAccess } from '../access';
21
+
22
+ export interface DbClientProjectContext {
23
+ projectId: string;
24
+ project: Project;
25
+ root: string;
26
+ }
27
+
28
+ export function resolveDbClientProject(
29
+ conn: WSConnection,
30
+ projectId?: string
31
+ ): DbClientProjectContext | null {
32
+ const target = (projectId ?? '').trim() || ws.getProjectId(conn);
33
+ if (!target) return null;
34
+
35
+ const project = requireProjectAccess(conn, target);
36
+ return { projectId: target, project, root: project.path };
37
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * db-client — the connection as environment variables.
3
+ *
4
+ * THESE ROUTES HAND BACK A PASSWORD, which no other db-client route does:
5
+ * `db-client:list` redacts every secret before it crosses the wire. That is not
6
+ * an oversight being reversed, it is a different question — a connection string
7
+ * the user cannot copy solves nothing, and the whole feature is "put this into
8
+ * my project's `.env`". So the secret is gated at the ROUTE instead of stripped
9
+ * from the payload.
10
+ *
11
+ * Two gates, both already load-bearing elsewhere:
12
+ *
13
+ * - `requireDbClientConnectionAccess` is the owner-or-admin check the rest of
14
+ * the surface uses. A projected connection has NO owner, which in
15
+ * db-client's access model means only an admin can reach it — the same
16
+ * reason `db-client:link` is admin-only, arrived at without a second rule.
17
+ * - `requireProjectWorkspace` decides which tree a write lands in, and it is
18
+ * worktree-aware. A user looking at a worktree gets the worktree's `.env`,
19
+ * because that is the checkout their dev server is running from.
20
+ */
21
+
22
+ import { t } from 'elysia';
23
+ import { createRouter } from '$shared/utils/ws-server';
24
+ import type { WSConnection } from '$shared/utils/ws-server';
25
+ import { ws } from '$backend/utils/ws';
26
+ import { worktreeQueries } from '$backend/database/queries';
27
+ import { dbClientEnv, type EnvScope } from '../../db-client/env';
28
+ import type { DbEnvRequest } from '$shared/types/db-client';
29
+ import { requireProjectWorkspace } from '../access';
30
+ import { requireDbClientConnectionAccess } from './access';
31
+
32
+ const requestSchema = t.Object({
33
+ connectionId: t.String({ minLength: 1 }),
34
+ projectId: t.Optional(t.String()),
35
+ database: t.Optional(t.String()),
36
+ shape: t.Union([t.Literal('url'), t.Literal('split')]),
37
+ prefix: t.Optional(t.String()),
38
+ keyMap: t.Optional(t.Record(t.String(), t.String())),
39
+ fileName: t.Optional(t.String()),
40
+ includeAlternate: t.Optional(t.Boolean()),
41
+ allowTracked: t.Optional(t.Boolean())
42
+ });
43
+
44
+ /**
45
+ * The tree a write would land in, or null.
46
+ *
47
+ * Null rather than an error when no project is in scope: the panel still shows
48
+ * the variables and still lets them be copied, which is most of the value. A
49
+ * route that refused would turn "no project open" into "this feature is
50
+ * broken".
51
+ */
52
+ function resolveScope(conn: WSConnection, projectId?: string): EnvScope | null {
53
+ const target = (projectId ?? '').trim() || safeCurrentProject(conn);
54
+ if (!target) return null;
55
+
56
+ const { project, root, worktreeId } = requireProjectWorkspace(conn, target);
57
+ const worktree = worktreeId ? worktreeQueries.getById(worktreeId) : null;
58
+
59
+ return {
60
+ projectId: project.id,
61
+ // Named so the panel can say WHERE it is about to write. A worktree is a
62
+ // different checkout with its own dotenv file, and not saying so is how a
63
+ // user ends up looking for a variable in the main project.
64
+ projectName: worktree ? `${project.name} / ${worktree.name}` : project.name,
65
+ root
66
+ };
67
+ }
68
+
69
+ function safeCurrentProject(conn: WSConnection): string | null {
70
+ try {
71
+ return ws.getProjectId(conn);
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ function requireScope(conn: WSConnection, projectId?: string): EnvScope {
78
+ const scope = resolveScope(conn, projectId);
79
+ if (!scope) throw new Error('Open a project before writing to its environment file.');
80
+ return scope;
81
+ }
82
+
83
+ export const envHandler = createRouter()
84
+ .http('db-client:env-state', {
85
+ data: t.Object({
86
+ connectionId: t.String({ minLength: 1 }),
87
+ projectId: t.Optional(t.String()),
88
+ database: t.Optional(t.String())
89
+ }),
90
+ response: t.Any()
91
+ }, async ({ data, conn }) => {
92
+ const connection = requireDbClientConnectionAccess(conn, data.connectionId);
93
+ return dbClientEnv.state(connection, resolveScope(conn, data.projectId), data.database);
94
+ })
95
+
96
+ .http('db-client:env-preview', {
97
+ data: requestSchema,
98
+ response: t.Any()
99
+ }, async ({ data, conn }) => {
100
+ const connection = requireDbClientConnectionAccess(conn, data.connectionId);
101
+ return dbClientEnv.plan(connection, resolveScope(conn, data.projectId), toRequest(data));
102
+ })
103
+
104
+ .http('db-client:env-apply', {
105
+ data: requestSchema,
106
+ response: t.Any()
107
+ }, async ({ data, conn }) => {
108
+ const connection = requireDbClientConnectionAccess(conn, data.connectionId);
109
+ return dbClientEnv.apply(connection, requireScope(conn, data.projectId), toRequest(data));
110
+ })
111
+
112
+ .http('db-client:env-remove', {
113
+ data: requestSchema,
114
+ response: t.Any()
115
+ }, async ({ data, conn }) => {
116
+ const connection = requireDbClientConnectionAccess(conn, data.connectionId);
117
+ return dbClientEnv.remove(connection, requireScope(conn, data.projectId), toRequest(data));
118
+ });
119
+
120
+ function toRequest(data: {
121
+ connectionId: string;
122
+ projectId?: string;
123
+ database?: string;
124
+ shape: string;
125
+ prefix?: string;
126
+ keyMap?: Record<string, string>;
127
+ fileName?: string;
128
+ includeAlternate?: boolean;
129
+ allowTracked?: boolean;
130
+ }): DbEnvRequest {
131
+ return {
132
+ connectionId: data.connectionId,
133
+ projectId: data.projectId,
134
+ database: data.database,
135
+ shape: data.shape as DbEnvRequest['shape'],
136
+ prefix: data.prefix ?? '',
137
+ keyMap: data.keyMap as DbEnvRequest['keyMap'],
138
+ fileName: data.fileName,
139
+ includeAlternate: data.includeAlternate,
140
+ allowTracked: data.allowTracked
141
+ };
142
+ }
@@ -1,17 +1,38 @@
1
1
  /**
2
2
  * db-client WebSocket router.
3
+ *
4
+ * Importing `$backend/db-client/integrations` is what registers the `database`
5
+ * projector and the Supabase provider, so merging this router into the app is
6
+ * also what makes account-backed connections exist. Same arrangement as the
7
+ * Deployments router, and for the same reason: a surface with no routes has no
8
+ * providers to register either.
3
9
  */
4
10
 
11
+ import { t } from 'elysia';
5
12
  import { createRouter } from '$shared/utils/ws-server';
13
+ import '../../db-client/integrations';
6
14
  import { connectionsHandler } from './connections';
7
15
  import { schemaHandler } from './schema';
8
16
  import { queryHandler } from './query';
9
17
  import { structureHandler } from './structure';
10
18
  import { ioHandler } from './io';
19
+ import { accountsHandler } from './accounts';
20
+ import { supabaseHandler } from './supabase';
21
+ import { envHandler } from './env';
11
22
 
12
23
  export const dbClientRouter = createRouter()
13
24
  .merge(connectionsHandler)
14
25
  .merge(schemaHandler)
15
26
  .merge(queryHandler)
16
27
  .merge(structureHandler)
17
- .merge(ioHandler);
28
+ .merge(ioHandler)
29
+ .merge(accountsHandler)
30
+ .merge(supabaseHandler)
31
+ .merge(envHandler)
32
+ /**
33
+ * Broadcast when the connection list changes for a reason the requesting
34
+ * client did not cause — a link created, a link dropped, an account
35
+ * disconnected. A projected connection is visible to every admin, so a
36
+ * client that only refreshed after its own requests would show a stale list.
37
+ */
38
+ .emit('db-client:connections-changed', t.Object({}));