@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,523 @@
1
+ /**
2
+ * Supabase as a database provider.
3
+ *
4
+ * Three facts about Supabase shape everything below, and all three were checked
5
+ * against the published API document rather than assumed:
6
+ *
7
+ * 1. **The password cannot be read back.** There is no GET for a project's
8
+ * database password — only a PATCH that changes it. So a link asks for it
9
+ * once and stores it, and `resolveEndpoint` never pretends to know it.
10
+ * 2. **Direct connections are IPv6-only on projects created since 2024**,
11
+ * unless the account pays for an IPv4 add-on. A default of "direct" would
12
+ * therefore fail on most new projects with a DNS-shaped error that says
13
+ * nothing about the cause, so the pooler is the default and direct is an
14
+ * explicit choice that says why it might not work.
15
+ * 3. **Transaction mode does not support prepared statements.** Our Postgres
16
+ * driver is `Bun.sql`, which prepares, so transaction mode (port 6543) is
17
+ * offered but is not the default and says what it costs. Session mode on the
18
+ * pooler host is the one combination that is both reachable and compatible.
19
+ *
20
+ * The pooler host is NOT derivable from the project ref — it encodes the
21
+ * region — so it is fetched from `/config/database/pooler` at link time and
22
+ * stored on the link.
23
+ */
24
+
25
+ import type {
26
+ DbProviderAdapter,
27
+ DbProviderContext,
28
+ DbProviderEndpoint,
29
+ DbProviderEnvHints
30
+ } from '../types';
31
+ import type {
32
+ DbProviderCreateGroup,
33
+ DbProviderCreateOptions,
34
+ DbProviderInfo,
35
+ DbRemoteDatabase
36
+ } from '$shared/types/db-client';
37
+ import type { IntegrationStatus } from '$shared/types/integrations';
38
+ import type { SupabaseApiOrganization, SupabaseApiPoolerConfig, SupabaseApiProject } from './api-types';
39
+ import { SUPABASE_SLOW_TIMEOUT_MS, SupabaseError, supabaseRequest, type SupabaseCredentials } from './client';
40
+ import { debug } from '$shared/utils/logger';
41
+
42
+ export const SUPABASE_PROVIDER_ID = 'supabase';
43
+
44
+ /** Connection modes, in the order the dialog offers them. */
45
+ export const SUPABASE_MODES = {
46
+ poolerSession: 'pooler-session',
47
+ poolerTransaction: 'pooler-transaction',
48
+ direct: 'direct'
49
+ } as const;
50
+
51
+ /** Supavisor listens for session mode on 5432 and transaction mode on 6543. */
52
+ const POOLER_SESSION_PORT = 5432;
53
+ const POOLER_TRANSACTION_PORT = 6543;
54
+ const DIRECT_PORT = 5432;
55
+
56
+ export function supabaseCredentialsOf(context: DbProviderContext): SupabaseCredentials {
57
+ const accessToken = (context.credentials.accessToken ?? '').trim();
58
+ if (!accessToken) {
59
+ throw new SupabaseError(
60
+ 'This Supabase account has no access token. Reconnect it in Settings → Integrations.',
61
+ 401,
62
+ 'auth'
63
+ );
64
+ }
65
+ return { accessToken };
66
+ }
67
+
68
+ /**
69
+ * The one state a project can actually be connected to in.
70
+ *
71
+ * Everything else — `COMING_UP`, `PAUSED`, `RESTORING` — looks like an ordinary
72
+ * row in a list and refuses every connection, which is why readiness is
73
+ * reported rather than inferred from the row existing.
74
+ */
75
+ const READY_STATUS = 'ACTIVE_HEALTHY';
76
+
77
+ /**
78
+ * Regions, taken from the `region` enum in the published API document.
79
+ *
80
+ * Hard-coded deliberately. The live source is `GET /v1/projects/available-regions`,
81
+ * which is marked BETA, requires an organisation slug and answers with a nested
82
+ * recommendation structure — a lot of surface to depend on for a list of AWS
83
+ * regions that has changed a handful of times in five years. If a region is
84
+ * missing here the user can still create the project in Supabase's dashboard and
85
+ * link it, which is a far smaller failure than a beta endpoint changing shape.
86
+ */
87
+ const REGIONS: { value: string; label: string }[] = [
88
+ { value: 'us-east-1', label: 'US East (N. Virginia)' },
89
+ { value: 'us-east-2', label: 'US East (Ohio)' },
90
+ { value: 'us-west-1', label: 'US West (N. California)' },
91
+ { value: 'us-west-2', label: 'US West (Oregon)' },
92
+ { value: 'ca-central-1', label: 'Canada (Central)' },
93
+ { value: 'sa-east-1', label: 'South America (São Paulo)' },
94
+ { value: 'eu-west-1', label: 'Europe (Ireland)' },
95
+ { value: 'eu-west-2', label: 'Europe (London)' },
96
+ { value: 'eu-west-3', label: 'Europe (Paris)' },
97
+ { value: 'eu-central-1', label: 'Europe (Frankfurt)' },
98
+ { value: 'eu-central-2', label: 'Europe (Zurich)' },
99
+ { value: 'eu-north-1', label: 'Europe (Stockholm)' },
100
+ { value: 'ap-south-1', label: 'Asia Pacific (Mumbai)' },
101
+ { value: 'ap-southeast-1', label: 'Asia Pacific (Singapore)' },
102
+ { value: 'ap-southeast-2', label: 'Asia Pacific (Sydney)' },
103
+ { value: 'ap-northeast-1', label: 'Asia Pacific (Tokyo)' },
104
+ { value: 'ap-northeast-2', label: 'Asia Pacific (Seoul)' },
105
+ { value: 'ap-east-1', label: 'Asia Pacific (Hong Kong)' }
106
+ ];
107
+
108
+ /**
109
+ * A password for a project we are creating.
110
+ *
111
+ * Generated rather than asked for, and never shown: the user has no reason to
112
+ * type it, and Clopen stores it sealed the moment the project exists. Base64url
113
+ * of 24 random bytes clears Supabase's strength rules without needing to know
114
+ * what they are, and carries no characters that need escaping in a connection
115
+ * string.
116
+ */
117
+ function generatePassword(): string {
118
+ const bytes = new Uint8Array(24);
119
+ crypto.getRandomValues(bytes);
120
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
121
+ }
122
+
123
+ /** A project that is not running cannot be connected to, and says so. */
124
+ function statusDetail(project: SupabaseApiProject): string {
125
+ const parts = [project.region];
126
+ if (project.status && project.status !== 'ACTIVE_HEALTHY') {
127
+ parts.push(project.status.toLowerCase().replace(/_/g, ' '));
128
+ }
129
+ return parts.filter(Boolean).join(' · ');
130
+ }
131
+
132
+ export async function listSupabaseProjects(context: DbProviderContext): Promise<SupabaseApiProject[]> {
133
+ return supabaseRequest<SupabaseApiProject[]>(supabaseCredentialsOf(context), '/v1/projects');
134
+ }
135
+
136
+ /**
137
+ * The primary database's pooler configuration.
138
+ *
139
+ * The endpoint answers with an array — a project with read replicas has one
140
+ * entry each — and the primary is the one this surface connects to. Picking the
141
+ * first entry regardless would silently connect a read replica on some projects.
142
+ */
143
+ async function poolerConfig(
144
+ credentials: SupabaseCredentials,
145
+ ref: string
146
+ ): Promise<SupabaseApiPoolerConfig | null> {
147
+ const configs = await supabaseRequest<SupabaseApiPoolerConfig[]>(
148
+ credentials,
149
+ `/v1/projects/${encodeURIComponent(ref)}/config/database/pooler`
150
+ );
151
+ if (!Array.isArray(configs) || configs.length === 0) return null;
152
+ return configs.find((entry) => entry.database_type === 'PRIMARY') ?? configs[0];
153
+ }
154
+
155
+ export const supabaseDbAdapter: DbProviderAdapter = {
156
+ provider: SUPABASE_PROVIDER_ID,
157
+ driver: 'postgres',
158
+
159
+ info(): DbProviderInfo {
160
+ return {
161
+ id: SUPABASE_PROVIDER_ID,
162
+ name: 'Supabase',
163
+ driver: 'postgres',
164
+ description: 'Pick a project this token can reach.',
165
+ // Session mode is correct for this client in every case the other two
166
+ // are not, so it is the silent default and both escape hatches are
167
+ // marked advanced. Transaction mode is genuinely a trap here — our
168
+ // driver prepares statements — and a direct connection is IPv6-only on
169
+ // projects created since 2024; offering all three up front asked the
170
+ // user to choose between one right answer and two ways to fail.
171
+ modes: [
172
+ {
173
+ id: SUPABASE_MODES.poolerSession,
174
+ label: 'Pooler (session)',
175
+ help: 'Works over IPv4. The right choice unless the pooler is unavailable.',
176
+ isDefault: true
177
+ },
178
+ {
179
+ id: SUPABASE_MODES.poolerTransaction,
180
+ label: 'Pooler (transaction)',
181
+ help: 'Breaks prepared statements, which this client uses.',
182
+ isAdvanced: true
183
+ },
184
+ {
185
+ id: SUPABASE_MODES.direct,
186
+ label: 'Direct',
187
+ help: 'IPv6 only on projects created since 2024.',
188
+ isAdvanced: true
189
+ }
190
+ ],
191
+ secretFields: [
192
+ {
193
+ name: 'password',
194
+ label: 'Database password',
195
+ placeholder: 'Project database password',
196
+ help: 'Project Settings → Database. Supabase cannot read it back, so it is stored here, encrypted.',
197
+ isRequired: true
198
+ }
199
+ ]
200
+ };
201
+ },
202
+
203
+ /**
204
+ * Supabase documents the `POSTGRES_*` names Vercel's integration injects, so
205
+ * that is the preset. The direct endpoint is offered as the non-pooling half
206
+ * WITH its caveat attached rather than silently: on projects created since
207
+ * 2024 it answers only over IPv6, so a user on an IPv4-only network gets a
208
+ * URL that resolves and never connects — and being told that beats
209
+ * discovering it inside a migration.
210
+ */
211
+ envHints(): DbProviderEnvHints {
212
+ return {
213
+ urlPrefix: 'POSTGRES',
214
+ altKeySuffix: '_NON_POOLING',
215
+ directMode: SUPABASE_MODES.direct,
216
+ pooledModes: [SUPABASE_MODES.poolerSession, SUPABASE_MODES.poolerTransaction],
217
+ directNotice:
218
+ 'Supabase\u2019s direct endpoint is IPv6-only on projects created since 2024, so check it resolves before relying on it.'
219
+ };
220
+ },
221
+
222
+ async listDatabases(context: DbProviderContext): Promise<DbRemoteDatabase[]> {
223
+ const credentials = supabaseCredentialsOf(context);
224
+ // The organisation is fetched ALONGSIDE the projects, not for each of
225
+ // them: a project carries only its org's slug, and an account with a
226
+ // dozen projects in two organisations would otherwise ask twelve times
227
+ // for two answers. A token without Organizations Read still gets a list —
228
+ // it simply falls back to the slug the project already reported.
229
+ const [projects, organizations] = await Promise.all([
230
+ listSupabaseProjects(context),
231
+ supabaseRequest<SupabaseApiOrganization[]>(credentials, '/v1/organizations').catch((error) => {
232
+ debug.warn('db-client', 'Could not name Supabase organizations:', error);
233
+ return [] as SupabaseApiOrganization[];
234
+ })
235
+ ]);
236
+
237
+ const names = new Map<string, string>();
238
+ for (const organization of organizations ?? []) {
239
+ if (organization?.slug) names.set(organization.slug, organization.name || organization.slug);
240
+ }
241
+
242
+ return projects.map((project) => ({
243
+ ref: project.ref || project.id,
244
+ name: project.name,
245
+ detail: statusDetail(project),
246
+ group: project.organization_slug
247
+ ? names.get(project.organization_slug) ?? project.organization_slug
248
+ : null,
249
+ status: project.status ?? null,
250
+ isReady: project.status === READY_STATUS,
251
+ isLinked: false
252
+ }));
253
+ },
254
+
255
+ async resolveEndpoint(
256
+ context: DbProviderContext,
257
+ target: { remoteRef: string; mode: string }
258
+ ): Promise<DbProviderEndpoint> {
259
+ const credentials = supabaseCredentialsOf(context);
260
+ const ref = target.remoteRef;
261
+
262
+ if (target.mode === SUPABASE_MODES.direct) {
263
+ // The direct host is REPORTED per project rather than derived:
264
+ // `db.<ref>.supabase.co` is a convention, not a guarantee, and a project
265
+ // on a custom or older domain would be sent somewhere that does not
266
+ // resolve. The convention is only the fallback.
267
+ const project = await supabaseRequest<SupabaseApiProject>(
268
+ credentials,
269
+ `/v1/projects/${encodeURIComponent(ref)}`
270
+ );
271
+ const host = project?.database?.host ?? `db.${ref}.supabase.co`;
272
+ return {
273
+ host,
274
+ port: DIRECT_PORT,
275
+ username: 'postgres',
276
+ database: 'postgres',
277
+ // Supabase terminates TLS on every endpoint, but its certificate is
278
+ // issued by its own CA, so demanding verification without also
279
+ // shipping that CA would refuse every connection. `require` is the
280
+ // honest setting: encrypted, not pinned.
281
+ sslMode: 'require',
282
+ options: { supabase: { ref, mode: target.mode } }
283
+ };
284
+ }
285
+
286
+ const pooler = await poolerConfig(credentials, ref);
287
+ if (!pooler) {
288
+ throw new SupabaseError(
289
+ `Supabase did not report a pooler for ${ref}. Choose a direct connection instead, or check the project is running.`,
290
+ 404,
291
+ 'config'
292
+ );
293
+ }
294
+
295
+ const isTransaction = target.mode === SUPABASE_MODES.poolerTransaction;
296
+ return {
297
+ host: pooler.db_host,
298
+ // The reported port belongs to whichever mode the project is configured
299
+ // for, so it is only trusted when it matches the mode being asked for.
300
+ port: isTransaction ? POOLER_TRANSACTION_PORT : POOLER_SESSION_PORT,
301
+ // `postgres.<ref>` — the pooler routes on the username, so the plain
302
+ // `postgres` that works on a direct connection fails here.
303
+ username: pooler.db_user || `postgres.${ref}`,
304
+ database: pooler.db_name || 'postgres',
305
+ sslMode: 'require',
306
+ options: { supabase: { ref, mode: target.mode } }
307
+ };
308
+ },
309
+
310
+ async createOptions(context: DbProviderContext): Promise<DbProviderCreateOptions> {
311
+ const credentials = supabaseCredentialsOf(context);
312
+
313
+ // Listed organisations are trusted; derived ones are CHECKED but still
314
+ // offered when the check cannot confirm them.
315
+ //
316
+ // Three facts, all confirmed against a live scoped token, and each one
317
+ // killed a simpler design:
318
+ //
319
+ // 1. `/v1/organizations` answers `[]` with a 200 for a token that plainly
320
+ // reaches projects, so it is not the last word.
321
+ // 2. A project's `organization_slug` names where that project lives, not
322
+ // somewhere this token may act — `/v1/organizations/{slug}` 403s for
323
+ // an organisation the user is merely a member of. Offering those
324
+ // unmarked produced a 403 after the form was filled in.
325
+ // 3. But reading and writing are SEPARATE permissions: the same token
326
+ // that cannot read an organisation successfully created one. So
327
+ // dropping every unverifiable candidate removed a capability that
328
+ // works, which is its own kind of wrong.
329
+ //
330
+ // Hence: verify, and mark rather than hide. The caller decides how loudly
331
+ // to say "this might fail", and a 403 now names the missing permission.
332
+ const [listed, projects] = await Promise.all([
333
+ supabaseRequest<SupabaseApiOrganization[]>(credentials, '/v1/organizations').catch((error) => {
334
+ debug.warn('db-client', 'Could not list Supabase organizations:', error);
335
+ return [] as SupabaseApiOrganization[];
336
+ }),
337
+ supabaseRequest<SupabaseApiProject[]>(credentials, '/v1/projects').catch(() => [] as SupabaseApiProject[])
338
+ ]);
339
+
340
+ const groups = new Map<string, DbProviderCreateGroup>();
341
+ for (const organization of listed ?? []) {
342
+ if (!organization?.slug) continue;
343
+ groups.set(organization.slug, {
344
+ value: organization.slug,
345
+ label: organization.name || organization.slug
346
+ });
347
+ }
348
+
349
+ const candidates = new Set<string>();
350
+ for (const project of projects ?? []) {
351
+ const slug = project.organization_slug;
352
+ // Only a slug is usable: `organization_id` is deprecated and the create
353
+ // endpoint takes the slug.
354
+ if (slug && !groups.has(slug)) candidates.add(slug);
355
+ }
356
+
357
+ await Promise.all(
358
+ [...candidates].map(async (slug) => {
359
+ try {
360
+ const organization = await supabaseRequest<SupabaseApiOrganization>(
361
+ credentials,
362
+ `/v1/organizations/${encodeURIComponent(slug)}`
363
+ );
364
+ groups.set(slug, { value: slug, label: organization?.name || slug });
365
+ } catch {
366
+ groups.set(slug, {
367
+ value: slug,
368
+ label: slug,
369
+ detail: 'unverified',
370
+ isUnverified: true
371
+ });
372
+ }
373
+ })
374
+ );
375
+
376
+ debug.log(
377
+ 'db-client',
378
+ `Supabase create options: ${listed?.length ?? 0} listed, ${candidates.size} derived, ${groups.size} offered`
379
+ );
380
+
381
+ return {
382
+ groupLabel: 'Organisation',
383
+ groups: [...groups.values()],
384
+ regionLabel: 'Region',
385
+ regions: REGIONS,
386
+ // Names the consequence rather than asking "are you sure". Creating a
387
+ // project provisions real infrastructure against a real quota, and the
388
+ // plan lives on the organisation, so which one is picked decides
389
+ // whether this is free.
390
+ notice:
391
+ 'This provisions a real Postgres database on Supabase. It counts against the organisation\'s project quota and its plan decides what it costs.',
392
+ // Shown INSTEAD of the form when nothing is usable. The two real causes
393
+ // are named because the fix differs: one is a token problem, the other
394
+ // is a membership problem, and "Forbidden" distinguishes neither.
395
+ // Short, and one instruction. The long version listed three ways out at
396
+ // once and ended on "link it here", which named no action the reader
397
+ // could take from where they were standing.
398
+ emptyGroupsNotice:
399
+ 'This token reaches no organisation — create one, or regenerate the token with Organizations Read.',
400
+ canCreateGroup: true,
401
+ createGroupNotice: 'A new organisation is a billing entity and starts on the free plan.',
402
+ // `/v1/organizations/{slug}` is GET-only, so renaming and deleting are
403
+ // absent rather than broken and no permission would change that.
404
+ groupManagementNotice: "Rename or delete an organisation in Supabase's dashboard."
405
+ };
406
+ },
407
+
408
+ /**
409
+ * Create an organisation.
410
+ *
411
+ * `POST /v1/organizations` takes a name and nothing else — no plan, no
412
+ * region — and answers with the slug the create-project call needs. It is a
413
+ * billing entity, so the dialog names that before the button; new
414
+ * organisations start on the free plan.
415
+ */
416
+ async createGroup(
417
+ context: DbProviderContext,
418
+ input: { name: string }
419
+ ): Promise<{ value: string; label: string }> {
420
+ const created = await supabaseRequest<SupabaseApiOrganization>(
421
+ supabaseCredentialsOf(context),
422
+ '/v1/organizations',
423
+ { method: 'POST', body: { name: input.name.trim() } }
424
+ );
425
+ if (!created?.slug) {
426
+ throw new SupabaseError(
427
+ 'Supabase created the organisation but did not report its slug, so it cannot be used here yet. It will appear after a refresh.',
428
+ 502,
429
+ 'error'
430
+ );
431
+ }
432
+ return { value: created.slug, label: created.name || created.slug };
433
+ },
434
+
435
+ async createDatabase(
436
+ context: DbProviderContext,
437
+ input: { name: string; group: string; region: string }
438
+ ): Promise<{ ref: string; secrets: Record<string, string> }> {
439
+ const password = generatePassword();
440
+ const created = await supabaseRequest<SupabaseApiProject>(
441
+ supabaseCredentialsOf(context),
442
+ '/v1/projects',
443
+ {
444
+ method: 'POST',
445
+ body: {
446
+ name: input.name,
447
+ organization_slug: input.group,
448
+ db_pass: password,
449
+ // `region_selection` rather than the older `region` string, which
450
+ // the API document marks deprecated. The shape is the documented
451
+ // one: a discriminated object, not a bare code.
452
+ region_selection: { type: 'specific', code: input.region }
453
+ },
454
+ // Provisioning is real work upstream, and aborting at the read budget
455
+ // would report a timeout for a project that now exists.
456
+ timeoutMs: SUPABASE_SLOW_TIMEOUT_MS
457
+ }
458
+ );
459
+
460
+ const ref = created?.ref || created?.id;
461
+ if (!ref) {
462
+ throw new SupabaseError(
463
+ 'Supabase accepted the project but did not report its ref, so it cannot be linked automatically. It will be in the list once it finishes provisioning.',
464
+ 502,
465
+ 'error'
466
+ );
467
+ }
468
+ return { ref, secrets: { password } };
469
+ },
470
+
471
+ /**
472
+ * Delete a project.
473
+ *
474
+ * Irreversible, and the API offers no undo — there is no trash. The confirm
475
+ * that guards it names the database rather than asking "are you sure",
476
+ * because the name is the thing someone can check against what they meant.
477
+ */
478
+ async deleteDatabase(context: DbProviderContext, remoteRef: string): Promise<void> {
479
+ await supabaseRequest(
480
+ supabaseCredentialsOf(context),
481
+ `/v1/projects/${encodeURIComponent(remoteRef)}`,
482
+ { method: 'DELETE', timeoutMs: SUPABASE_SLOW_TIMEOUT_MS }
483
+ );
484
+ },
485
+
486
+ /**
487
+ * Rename a project.
488
+ *
489
+ * `PATCH /v1/projects/{ref}` takes a name and nothing else — it is the only
490
+ * field of a project the Management API lets us change. Organisations have
491
+ * no PATCH at all, which is why this adapter renames databases and not
492
+ * groups.
493
+ */
494
+ async renameDatabase(context: DbProviderContext, remoteRef: string, name: string): Promise<void> {
495
+ await supabaseRequest(
496
+ supabaseCredentialsOf(context),
497
+ `/v1/projects/${encodeURIComponent(remoteRef)}`,
498
+ { method: 'PATCH', body: { name } }
499
+ );
500
+ },
501
+
502
+ async probe(context: DbProviderContext): Promise<{ status: IntegrationStatus; detail: string | null }> {
503
+ try {
504
+ const projects = await listSupabaseProjects(context);
505
+ if (projects.length === 0) {
506
+ return {
507
+ status: 'needs_config',
508
+ detail: 'The token works but reaches no projects — check which Supabase user it belongs to.'
509
+ };
510
+ }
511
+ const plural = projects.length === 1 ? 'project' : 'projects';
512
+ return { status: 'ok', detail: `${projects.length} ${plural} reachable` };
513
+ } catch (error) {
514
+ if (error instanceof SupabaseError) {
515
+ const status: IntegrationStatus = error.kind === 'auth'
516
+ ? 'needs_auth'
517
+ : error.kind === 'config' ? 'needs_config' : 'error';
518
+ return { status, detail: error.message };
519
+ }
520
+ return { status: 'error', detail: error instanceof Error ? error.message : String(error) };
521
+ }
522
+ }
523
+ };
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The shapes the Supabase Management API actually returns.
3
+ *
4
+ * Transcribed from the published OpenAPI document, narrowed to the fields this
5
+ * surface reads. Everything optional is optional because the document says so —
6
+ * a field marked required there is still declared optional here when reading it
7
+ * wrong would produce a confident wrong answer rather than a missing one.
8
+ */
9
+
10
+ export interface SupabaseApiProject {
11
+ id: string;
12
+ ref: string;
13
+ name: string;
14
+ region: string;
15
+ status: string;
16
+ organization_id?: string;
17
+ organization_slug?: string;
18
+ created_at?: string;
19
+ database?: {
20
+ host: string;
21
+ version: string;
22
+ postgres_engine?: string;
23
+ release_channel?: string;
24
+ };
25
+ }
26
+
27
+ /**
28
+ * Supavisor, Supabase's connection pooler.
29
+ *
30
+ * The endpoint answers with an ARRAY — one entry per database, so a project
31
+ * with a read replica has more than one. `connection_string` is treated as a
32
+ * template and never mined for a password: the API cannot hand the password
33
+ * back, so anything password-shaped in there is a placeholder.
34
+ */
35
+ export interface SupabaseApiPoolerConfig {
36
+ identifier: string;
37
+ database_type: 'PRIMARY' | 'READ_REPLICA';
38
+ db_user: string;
39
+ db_host: string;
40
+ db_port: number;
41
+ db_name: string;
42
+ connection_string?: string;
43
+ pool_mode?: 'transaction' | 'session';
44
+ default_pool_size?: number | null;
45
+ max_client_conn?: number | null;
46
+ is_using_scram_auth?: boolean;
47
+ }
48
+
49
+ export interface SupabaseApiFunction {
50
+ id: string;
51
+ slug: string;
52
+ name: string;
53
+ status: string;
54
+ version?: number;
55
+ /** Epoch milliseconds, not an ISO string. */
56
+ created_at?: number;
57
+ updated_at?: number;
58
+ verify_jwt?: boolean;
59
+ entrypoint_path?: string;
60
+ }
61
+
62
+ export interface SupabaseApiAdvisorResponse {
63
+ lints?: SupabaseApiLint[];
64
+ }
65
+
66
+ export interface SupabaseApiLint {
67
+ name?: string;
68
+ title?: string;
69
+ level?: string;
70
+ facing?: string;
71
+ description?: string;
72
+ detail?: string;
73
+ remediation?: string;
74
+ categories?: string[];
75
+ metadata?: Record<string, unknown> | null;
76
+ cache_key?: string;
77
+ }
78
+
79
+ export interface SupabaseApiTypes {
80
+ types: string;
81
+ }
82
+
83
+ export interface SupabaseApiMigration {
84
+ version: string;
85
+ name?: string;
86
+ }
87
+
88
+ export interface SupabaseApiOrganization {
89
+ id: string;
90
+ slug: string;
91
+ name: string;
92
+ }