@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
@@ -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
+ }
@@ -1,17 +1,36 @@
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';
11
21
 
12
22
  export const dbClientRouter = createRouter()
13
23
  .merge(connectionsHandler)
14
24
  .merge(schemaHandler)
15
25
  .merge(queryHandler)
16
26
  .merge(structureHandler)
17
- .merge(ioHandler);
27
+ .merge(ioHandler)
28
+ .merge(accountsHandler)
29
+ .merge(supabaseHandler)
30
+ /**
31
+ * Broadcast when the connection list changes for a reason the requesting
32
+ * client did not cause — a link created, a link dropped, an account
33
+ * disconnected. A projected connection is visible to every admin, so a
34
+ * client that only refreshed after its own requests would show a stale list.
35
+ */
36
+ .emit('db-client:connections-changed', t.Object({}));
@@ -0,0 +1,188 @@
1
+ /**
2
+ * db-client — the Supabase surface.
3
+ *
4
+ * Every route starts by resolving a SCOPE: is this connection Supabase, and is
5
+ * there an account behind it or only a local stack. A connection that is
6
+ * neither answers `null` rather than an error, because the panel asks
7
+ * speculatively when a connection is selected and "this is not Supabase" is an
8
+ * ordinary answer.
9
+ *
10
+ * Access is checked the way the rest of this router checks it — the caller must
11
+ * be able to reach the CONNECTION — plus a project-access check inside
12
+ * `resolveDbClientProject` for the routes that touch the working tree. Reads
13
+ * are open to whoever can use the connection; applying a migration and writing
14
+ * types are not, and say so.
15
+ */
16
+
17
+ import { t } from 'elysia';
18
+ import { createRouter } from '$shared/utils/ws-server';
19
+ import { resolveSupabaseScope, supabaseSurface, type SupabaseScope } from '../../db-client/integrations';
20
+ import { getDbClientPrincipal, requireDbClientConnectionAccess } from './access';
21
+ import { resolveDbClientProject } from './context';
22
+ import type { WSConnection } from '$shared/utils/ws-server';
23
+ import { debug } from '$shared/utils/logger';
24
+
25
+ async function scopeFor(
26
+ conn: WSConnection,
27
+ connectionId: string,
28
+ projectId?: string
29
+ ): Promise<SupabaseScope | null> {
30
+ requireDbClientConnectionAccess(conn, connectionId);
31
+ const project = resolveDbClientProject(conn, projectId);
32
+ return resolveSupabaseScope(connectionId, project?.root ?? null);
33
+ }
34
+
35
+ /**
36
+ * A scope, or a readable failure.
37
+ *
38
+ * Used by every route that only makes sense for Supabase: reaching one of these
39
+ * on a plain Postgres connection means the panel offered a tab it should not
40
+ * have, and saying so beats returning an empty list that reads like "nothing
41
+ * here".
42
+ */
43
+ async function requireScope(
44
+ conn: WSConnection,
45
+ connectionId: string,
46
+ projectId?: string
47
+ ): Promise<SupabaseScope> {
48
+ const scope = await scopeFor(conn, connectionId, projectId);
49
+ if (!scope) throw new Error('This connection is not a Supabase project');
50
+ return scope;
51
+ }
52
+
53
+ /**
54
+ * Writes are admin-only.
55
+ *
56
+ * Applying a migration changes a schema everyone shares, and writing generated
57
+ * types writes a file into the repository. Both are outward-facing in the sense
58
+ * `Task 3` uses: the consequence outlives the request.
59
+ */
60
+ function requireAdmin(conn: WSConnection, action: string): void {
61
+ const { isAdmin } = getDbClientPrincipal(conn);
62
+ if (!isAdmin) throw new Error(`Only an admin can ${action}`);
63
+ }
64
+
65
+ const connectionTarget = {
66
+ connectionId: t.String({ minLength: 1 }),
67
+ projectId: t.Optional(t.String())
68
+ };
69
+
70
+ export const supabaseHandler = createRouter()
71
+ .http('db-client:supabase-context', {
72
+ data: t.Object(connectionTarget),
73
+ response: t.Nullable(t.Any())
74
+ }, async ({ data, conn }) => {
75
+ const scope = await scopeFor(conn, data.connectionId, data.projectId);
76
+ if (!scope) return null;
77
+ return {
78
+ ...supabaseSurface.context(scope),
79
+ hasLocalProject: scope.local !== null,
80
+ hasAccount: scope.remote !== null,
81
+ accountLabel: scope.accountLabel,
82
+ // Only meaningful for an account-backed connection; a local stack never
83
+ // touches the Management API, so it has no budget to report.
84
+ rateLimit: await supabaseSurface.rateLimit(scope)
85
+ };
86
+ })
87
+
88
+ .http('db-client:supabase-migrations', {
89
+ data: t.Object(connectionTarget),
90
+ response: t.Any()
91
+ }, async ({ data, conn }) => {
92
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
93
+ return supabaseSurface.migrations(scope);
94
+ })
95
+
96
+ .http('db-client:supabase-migration-sql', {
97
+ data: t.Object({ ...connectionTarget, version: t.String({ minLength: 1 }) }),
98
+ response: t.Object({ sql: t.String() })
99
+ }, async ({ data, conn }) => {
100
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
101
+ const report = await supabaseSurface.migrations(scope);
102
+ const migration = report.migrations.find((entry) => entry.version === data.version);
103
+ // The path is looked up rather than accepted, so this cannot be used to
104
+ // read a file outside the project's migrations directory.
105
+ if (!migration?.path) throw new Error(`Migration ${data.version} has no local file`);
106
+ return { sql: await supabaseSurface.migrationSql(migration.path) };
107
+ })
108
+
109
+ .http('db-client:supabase-apply-migration', {
110
+ data: t.Object({ ...connectionTarget, version: t.String({ minLength: 1 }) }),
111
+ response: t.Object({ version: t.String(), durationMs: t.Number() })
112
+ }, async ({ data, conn }) => {
113
+ requireAdmin(conn, 'apply a migration');
114
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
115
+ const result = await supabaseSurface.apply(scope, data.version);
116
+ debug.log('db-client', `Supabase migration ${result.version} applied to ${scope.context.ref}`);
117
+ return result;
118
+ })
119
+
120
+ .http('db-client:supabase-rls', {
121
+ data: t.Object(connectionTarget),
122
+ response: t.Any()
123
+ }, async ({ data, conn }) => {
124
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
125
+ return supabaseSurface.rls(scope);
126
+ })
127
+
128
+ .http('db-client:supabase-buckets', {
129
+ data: t.Object(connectionTarget),
130
+ response: t.Array(t.Any())
131
+ }, async ({ data, conn }) => {
132
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
133
+ return supabaseSurface.buckets(scope);
134
+ })
135
+
136
+ .http('db-client:supabase-auth-users', {
137
+ data: t.Object({
138
+ ...connectionTarget,
139
+ search: t.Optional(t.String()),
140
+ limit: t.Optional(t.Number()),
141
+ offset: t.Optional(t.Number())
142
+ }),
143
+ response: t.Any()
144
+ }, async ({ data, conn }) => {
145
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
146
+ return supabaseSurface.authUsers(scope, {
147
+ search: data.search,
148
+ limit: data.limit,
149
+ offset: data.offset
150
+ });
151
+ })
152
+
153
+ .http('db-client:supabase-functions', {
154
+ data: t.Object(connectionTarget),
155
+ response: t.Array(t.Any())
156
+ }, async ({ data, conn }) => {
157
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
158
+ return supabaseSurface.functions(scope);
159
+ })
160
+
161
+ .http('db-client:supabase-function-body', {
162
+ data: t.Object({ ...connectionTarget, slug: t.String({ minLength: 1 }) }),
163
+ response: t.Object({ body: t.String() })
164
+ }, async ({ data, conn }) => {
165
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
166
+ return { body: await supabaseSurface.functionBody(scope, data.slug) };
167
+ })
168
+
169
+ .http('db-client:supabase-types', {
170
+ data: t.Object({ ...connectionTarget, schemas: t.Optional(t.Array(t.String())) }),
171
+ response: t.Object({ types: t.String(), suggestedPath: t.String() })
172
+ }, async ({ data, conn }) => {
173
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
174
+ return supabaseSurface.types(scope, data.schemas ?? ['public']);
175
+ })
176
+
177
+ .http('db-client:supabase-write-types', {
178
+ data: t.Object({
179
+ ...connectionTarget,
180
+ path: t.String({ minLength: 1 }),
181
+ contents: t.String()
182
+ }),
183
+ response: t.Object({ path: t.String(), bytes: t.Number() })
184
+ }, async ({ data, conn }) => {
185
+ requireAdmin(conn, 'write generated types into the project');
186
+ const scope = await requireScope(conn, data.connectionId, data.projectId);
187
+ return supabaseSurface.writeTypes(scope, data.path, data.contents);
188
+ });