@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,502 @@
1
+ /**
2
+ * The Supabase surface inside DB Client.
3
+ *
4
+ * ONE RULE decides where each of these reads goes: anything that lives inside
5
+ * the database is read over SQL, through the connection DB Client already
6
+ * holds; only what lives outside it goes to the Management API. That is not a
7
+ * stylistic preference — it is what keeps five of the six tabs working for a
8
+ * `supabase start` stack that has no access token, and it keeps us off
9
+ * `POST /database/query`, which the API document marks as beta.
10
+ *
11
+ * So: policies, applied migrations, storage buckets and auth users are plain
12
+ * Postgres. Edge functions, generated types and the security advisor have no
13
+ * SQL equivalent, and each of those says plainly what it needs when there is no
14
+ * account behind the connection.
15
+ */
16
+
17
+ import { readdir, readFile, stat } from 'fs/promises';
18
+ import { join } from 'path';
19
+ import type {
20
+ SupabaseAdvisorLint,
21
+ SupabaseAuthUser,
22
+ SupabaseAuthUsersPage,
23
+ SupabaseBucket,
24
+ SupabaseEdgeFunction,
25
+ SupabaseMigration,
26
+ SupabaseMigrationsReport,
27
+ SupabasePolicy,
28
+ SupabaseRlsReport,
29
+ SupabaseTableRls,
30
+ SupabaseTypesResult
31
+ } from '$shared/types/db-client';
32
+ import type { DbClientDriverAdapter } from '../../drivers/types';
33
+ import type { SupabaseApiAdvisorResponse, SupabaseApiFunction, SupabaseApiTypes } from './api-types';
34
+ import { SUPABASE_SLOW_TIMEOUT_MS, SupabaseError, supabaseRequest, type SupabaseCredentials } from './client';
35
+ import { debug } from '$shared/utils/logger';
36
+
37
+ /** Rows out of a read, or an empty list — a missing schema is not an error here. */
38
+ async function rows(
39
+ adapter: DbClientDriverAdapter,
40
+ sql: string,
41
+ params: unknown[] = []
42
+ ): Promise<Record<string, unknown>[]> {
43
+ if (!adapter.executeRead) throw new Error('This connection cannot run queries');
44
+ // `limit` is passed explicitly because the executor's default auto-LIMIT is
45
+ // tuned for the query console. These are catalogue reads, and a truncated
46
+ // policy list would be a wrong answer rather than a short one.
47
+ const result = await adapter.executeRead(sql, params, { limit: 10_000 });
48
+ return result.rows;
49
+ }
50
+
51
+ function text(value: unknown): string | null {
52
+ if (value === null || value === undefined) return null;
53
+ return String(value);
54
+ }
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Migrations
58
+ // ---------------------------------------------------------------------------
59
+
60
+ /**
61
+ * The CLI's own bookkeeping table.
62
+ *
63
+ * `supabase_migrations.schema_migrations` is what `supabase db push` writes,
64
+ * and reading it directly is what lets this tab tell the truth for a local
65
+ * stack. A project that has never had a migration pushed has no such table, so
66
+ * its absence means "none applied" rather than a failure.
67
+ */
68
+ async function appliedVersions(adapter: DbClientDriverAdapter): Promise<Map<string, string | null>> {
69
+ const applied = new Map<string, string | null>();
70
+ try {
71
+ const result = await rows(
72
+ adapter,
73
+ `SELECT version, name FROM supabase_migrations.schema_migrations ORDER BY version ASC`
74
+ );
75
+ for (const row of result) {
76
+ const version = text(row.version);
77
+ if (version) applied.set(version, text(row.name));
78
+ }
79
+ } catch (error) {
80
+ debug.log('db-client', `No supabase_migrations table: ${error instanceof Error ? error.message : error}`);
81
+ }
82
+ return applied;
83
+ }
84
+
85
+ /** `20240101120000_create_widgets.sql` → version and name. */
86
+ function parseMigrationFile(fileName: string): { version: string; name: string | null } | null {
87
+ const match = /^(\d+)(?:_(.*))?\.sql$/i.exec(fileName);
88
+ if (!match) return null;
89
+ return { version: match[1], name: match[2] ? match[2].replace(/_/g, ' ') : null };
90
+ }
91
+
92
+ export async function readMigrations(
93
+ adapter: DbClientDriverAdapter,
94
+ migrationsDir: string | null
95
+ ): Promise<SupabaseMigrationsReport> {
96
+ const applied = await appliedVersions(adapter);
97
+ const byVersion = new Map<string, SupabaseMigration>();
98
+
99
+ for (const [version, name] of applied) {
100
+ byVersion.set(version, { version, name, isApplied: true, path: null, size: null });
101
+ }
102
+
103
+ if (migrationsDir) {
104
+ let entries: string[] = [];
105
+ try {
106
+ entries = await readdir(migrationsDir);
107
+ } catch {
108
+ // No migrations directory is an ordinary state for a project that has
109
+ // only ever been changed through the dashboard.
110
+ entries = [];
111
+ }
112
+
113
+ for (const entry of entries) {
114
+ const parsed = parseMigrationFile(entry);
115
+ if (!parsed) continue;
116
+ const path = join(migrationsDir, entry);
117
+ let size: number | null = null;
118
+ try {
119
+ size = (await stat(path)).size;
120
+ } catch {
121
+ size = null;
122
+ }
123
+ const existing = byVersion.get(parsed.version);
124
+ byVersion.set(parsed.version, {
125
+ version: parsed.version,
126
+ name: parsed.name ?? existing?.name ?? null,
127
+ isApplied: existing?.isApplied ?? false,
128
+ path,
129
+ size
130
+ });
131
+ }
132
+ }
133
+
134
+ const migrations = [...byVersion.values()].sort((a, b) => a.version.localeCompare(b.version));
135
+ return {
136
+ migrations,
137
+ localDir: migrationsDir,
138
+ // A version applied remotely with no local file means someone pushed from
139
+ // elsewhere. Worth saying out loud before anyone applies anything.
140
+ hasRemoteOnly: migrations.some((migration) => migration.isApplied && migration.path === null)
141
+ };
142
+ }
143
+
144
+ /** The SQL of one pending migration, read from the working tree. */
145
+ export async function readMigrationSql(path: string): Promise<string> {
146
+ return readFile(path, 'utf-8');
147
+ }
148
+
149
+ // ---------------------------------------------------------------------------
150
+ // RLS
151
+ // ---------------------------------------------------------------------------
152
+
153
+ /**
154
+ * Which tables have row-level security on, and every policy on them.
155
+ *
156
+ * `pg_policies` is a view over `pg_policy` that renders the expressions back as
157
+ * SQL text, which is what makes a policy readable without a parser. The table
158
+ * list comes from `pg_class` because a table with RLS enabled and NO policies
159
+ * is the dangerous case, and it does not appear in `pg_policies` at all.
160
+ *
161
+ * Supabase's internal schemas are excluded: `auth`, `storage` and friends carry
162
+ * dozens of policies the user did not write and cannot change, and they bury the
163
+ * handful that belong to the application.
164
+ */
165
+ const USER_SCHEMA_FILTER = `
166
+ n.nspname NOT IN (
167
+ 'pg_catalog','information_schema','auth','storage','graphql','graphql_public',
168
+ 'realtime','supabase_functions','supabase_migrations','vault','extensions','pgbouncer','net','cron'
169
+ )
170
+ AND n.nspname NOT LIKE 'pg_%'
171
+ `;
172
+
173
+ async function readTableRls(adapter: DbClientDriverAdapter): Promise<SupabaseTableRls[]> {
174
+ const result = await rows(adapter, `
175
+ SELECT
176
+ n.nspname AS schema_name,
177
+ c.relname AS table_name,
178
+ c.relrowsecurity AS rls_enabled,
179
+ (SELECT COUNT(*) FROM pg_policy p WHERE p.polrelid = c.oid) AS policy_count
180
+ FROM pg_class c
181
+ JOIN pg_namespace n ON n.oid = c.relnamespace
182
+ WHERE c.relkind IN ('r','p') AND ${USER_SCHEMA_FILTER}
183
+ ORDER BY n.nspname, c.relname
184
+ `);
185
+
186
+ return result.map((row) => ({
187
+ schema: String(row.schema_name),
188
+ table: String(row.table_name),
189
+ rlsEnabled: row.rls_enabled === true || row.rls_enabled === 't' || row.rls_enabled === 1,
190
+ policyCount: Number(row.policy_count ?? 0)
191
+ }));
192
+ }
193
+
194
+ async function readPolicies(adapter: DbClientDriverAdapter): Promise<SupabasePolicy[]> {
195
+ const result = await rows(adapter, `
196
+ SELECT
197
+ n.nspname AS schema_name,
198
+ c.relname AS table_name,
199
+ pol.polname AS policy_name,
200
+ CASE WHEN pol.polpermissive THEN 'PERMISSIVE' ELSE 'RESTRICTIVE' END AS permissive,
201
+ CASE pol.polcmd
202
+ WHEN 'r' THEN 'SELECT'
203
+ WHEN 'a' THEN 'INSERT'
204
+ WHEN 'w' THEN 'UPDATE'
205
+ WHEN 'd' THEN 'DELETE'
206
+ ELSE 'ALL'
207
+ END AS command,
208
+ COALESCE(
209
+ (SELECT array_agg(rolname ORDER BY rolname) FROM pg_roles WHERE oid = ANY(pol.polroles)),
210
+ ARRAY['public']::name[]
211
+ ) AS roles,
212
+ pg_get_expr(pol.polqual, pol.polrelid) AS using_expr,
213
+ pg_get_expr(pol.polwithcheck, pol.polrelid) AS check_expr
214
+ FROM pg_policy pol
215
+ JOIN pg_class c ON c.oid = pol.polrelid
216
+ JOIN pg_namespace n ON n.oid = c.relnamespace
217
+ WHERE ${USER_SCHEMA_FILTER}
218
+ ORDER BY n.nspname, c.relname, pol.polname
219
+ `);
220
+
221
+ return result.map((row) => ({
222
+ schema: String(row.schema_name),
223
+ table: String(row.table_name),
224
+ name: String(row.policy_name),
225
+ permissive: String(row.permissive),
226
+ command: String(row.command),
227
+ roles: Array.isArray(row.roles) ? row.roles.map(String) : [],
228
+ using: text(row.using_expr),
229
+ withCheck: text(row.check_expr)
230
+ }));
231
+ }
232
+
233
+ /**
234
+ * The security advisor.
235
+ *
236
+ * Account-only: there is no SQL behind it, it is Supabase's own lint set. The
237
+ * findings that matter most here — a public table with RLS off, RLS on with no
238
+ * policy, a policy on a table where RLS is disabled — are exactly the mistakes
239
+ * a policy list alone cannot show, which is why the tab is worth the extra call.
240
+ */
241
+ async function readAdvisorLints(
242
+ credentials: SupabaseCredentials,
243
+ ref: string
244
+ ): Promise<SupabaseAdvisorLint[]> {
245
+ const response = await supabaseRequest<SupabaseApiAdvisorResponse>(
246
+ credentials,
247
+ `/v1/projects/${encodeURIComponent(ref)}/advisors/security`
248
+ );
249
+
250
+ return (response?.lints ?? []).map((lint) => {
251
+ const metadata = lint.metadata ?? {};
252
+ const entity = typeof metadata.entity === 'string' ? metadata.entity : null;
253
+ const name = typeof metadata.name === 'string' ? metadata.name : null;
254
+ return {
255
+ name: lint.name ?? 'lint',
256
+ title: lint.title ?? lint.name ?? 'Finding',
257
+ level: lint.level ?? 'info',
258
+ facing: lint.facing ?? 'unknown',
259
+ description: lint.description ?? '',
260
+ detail: lint.detail ?? null,
261
+ remediation: lint.remediation ?? null,
262
+ target: entity ?? name
263
+ };
264
+ });
265
+ }
266
+
267
+ export async function readRls(
268
+ adapter: DbClientDriverAdapter,
269
+ remote: { credentials: SupabaseCredentials; ref: string } | null
270
+ ): Promise<SupabaseRlsReport> {
271
+ const [tables, policies] = await Promise.all([readTableRls(adapter), readPolicies(adapter)]);
272
+
273
+ if (!remote) {
274
+ return {
275
+ tables,
276
+ policies,
277
+ lints: [],
278
+ advisorError: 'Connect a Supabase account to run the security advisor — it has no SQL equivalent.'
279
+ };
280
+ }
281
+
282
+ try {
283
+ return { tables, policies, lints: await readAdvisorLints(remote.credentials, remote.ref), advisorError: null };
284
+ } catch (error) {
285
+ // The advisor failing must not take the policy list with it: the SQL half
286
+ // is the substance of this tab, and the lints are the bonus.
287
+ const message = error instanceof SupabaseError ? error.message : error instanceof Error ? error.message : String(error);
288
+ return { tables, policies, lints: [], advisorError: message };
289
+ }
290
+ }
291
+
292
+ // ---------------------------------------------------------------------------
293
+ // Storage buckets — `storage.buckets` is an ordinary table
294
+ // ---------------------------------------------------------------------------
295
+
296
+ export async function readBuckets(adapter: DbClientDriverAdapter): Promise<SupabaseBucket[]> {
297
+ const result = await rows(adapter, `
298
+ SELECT
299
+ b.id, b.name, b.public, b.file_size_limit, b.allowed_mime_types,
300
+ b.created_at, b.updated_at,
301
+ (SELECT COUNT(*) FROM storage.objects o WHERE o.bucket_id = b.id) AS object_count
302
+ FROM storage.buckets b
303
+ ORDER BY b.name
304
+ `);
305
+
306
+ return result.map((row) => ({
307
+ id: String(row.id),
308
+ name: String(row.name),
309
+ isPublic: row.public === true || row.public === 't' || row.public === 1,
310
+ fileSizeLimit: row.file_size_limit === null || row.file_size_limit === undefined
311
+ ? null
312
+ : Number(row.file_size_limit),
313
+ allowedMimeTypes: Array.isArray(row.allowed_mime_types) ? row.allowed_mime_types.map(String) : null,
314
+ objectCount: row.object_count === null || row.object_count === undefined ? null : Number(row.object_count),
315
+ createdAt: text(row.created_at),
316
+ updatedAt: text(row.updated_at)
317
+ }));
318
+ }
319
+
320
+ // ---------------------------------------------------------------------------
321
+ // Auth users — `auth.users` is an ordinary table too
322
+ // ---------------------------------------------------------------------------
323
+
324
+ /**
325
+ * Read users over SQL rather than through the GoTrue admin API.
326
+ *
327
+ * The admin API would need the project's SERVICE ROLE key, which is a key that
328
+ * bypasses every policy in the database. Storing one to render a read-only list
329
+ * would be a poor trade, and `auth.users` answers the same question with the
330
+ * credential this connection already has.
331
+ *
332
+ * `encrypted_password` and the token columns are never selected.
333
+ */
334
+ export async function readAuthUsers(
335
+ adapter: DbClientDriverAdapter,
336
+ options: { search?: string; limit?: number; offset?: number } = {}
337
+ ): Promise<SupabaseAuthUsersPage> {
338
+ const limit = Math.min(Math.max(options.limit ?? 50, 1), 200);
339
+ const offset = Math.max(options.offset ?? 0, 0);
340
+ const search = (options.search ?? '').trim();
341
+
342
+ // Interpolated into a LIKE pattern rather than passed as a parameter because
343
+ // the driver's parameter style differs per database and this file must stay
344
+ // driver-agnostic; the value is escaped for quotes and wildcards first.
345
+ const escaped = search.replace(/'/g, "''").replace(/[%_]/g, (char) => `\\${char}`);
346
+ const filter = search
347
+ ? `WHERE (u.email ILIKE '%${escaped}%' ESCAPE '\\' OR u.phone ILIKE '%${escaped}%' ESCAPE '\\')`
348
+ : '';
349
+
350
+ const countRows = await rows(adapter, `SELECT COUNT(*) AS total FROM auth.users u ${filter}`);
351
+ const total = Number(countRows[0]?.total ?? 0);
352
+
353
+ const result = await rows(adapter, `
354
+ SELECT
355
+ u.id, u.email, u.phone, u.created_at, u.last_sign_in_at,
356
+ u.confirmed_at, u.banned_until,
357
+ u.raw_app_meta_data ->> 'provider' AS provider,
358
+ u.raw_app_meta_data -> 'providers' AS providers
359
+ FROM auth.users u
360
+ ${filter}
361
+ ORDER BY u.created_at DESC
362
+ LIMIT ${limit} OFFSET ${offset}
363
+ `);
364
+
365
+ const users: SupabaseAuthUser[] = result.map((row) => {
366
+ const list = row.providers;
367
+ const providers = Array.isArray(list)
368
+ ? list.map(String)
369
+ : text(row.provider)
370
+ ? [String(row.provider)]
371
+ : [];
372
+ const bannedUntil = text(row.banned_until);
373
+ return {
374
+ id: String(row.id),
375
+ email: text(row.email),
376
+ phone: text(row.phone) || null,
377
+ providers,
378
+ createdAt: text(row.created_at),
379
+ lastSignInAt: text(row.last_sign_in_at),
380
+ confirmedAt: text(row.confirmed_at),
381
+ // `banned_until` is a timestamp, not a flag: a ban that has expired is
382
+ // not a ban, and rendering it as one would accuse the wrong accounts.
383
+ isBanned: bannedUntil !== null && new Date(bannedUntil).getTime() > Date.now()
384
+ };
385
+ });
386
+
387
+ return { users, total };
388
+ }
389
+
390
+ // ---------------------------------------------------------------------------
391
+ // Edge functions — remote through the API, local from the working tree
392
+ // ---------------------------------------------------------------------------
393
+
394
+ export async function readEdgeFunctions(
395
+ remote: { credentials: SupabaseCredentials; ref: string } | null,
396
+ functionsDir: string | null
397
+ ): Promise<SupabaseEdgeFunction[]> {
398
+ if (remote) {
399
+ const functions = await supabaseRequest<SupabaseApiFunction[]>(
400
+ remote.credentials,
401
+ `/v1/projects/${encodeURIComponent(remote.ref)}/functions`
402
+ );
403
+ return (functions ?? []).map((fn) => ({
404
+ id: fn.id,
405
+ slug: fn.slug,
406
+ name: fn.name,
407
+ status: fn.status,
408
+ version: fn.version ?? null,
409
+ // Epoch MILLISECONDS, not an ISO string and not seconds — the API
410
+ // document is explicit about it, and reading it as seconds dates every
411
+ // function to 1970.
412
+ createdAt: fn.created_at ? new Date(fn.created_at).toISOString() : null,
413
+ updatedAt: fn.updated_at ? new Date(fn.updated_at).toISOString() : null,
414
+ verifyJwt: fn.verify_jwt ?? null,
415
+ entrypointPath: fn.entrypoint_path ?? null,
416
+ isLocal: false
417
+ }));
418
+ }
419
+
420
+ if (!functionsDir) return [];
421
+
422
+ // No account: list what the working tree has, so a local stack still shows
423
+ // something true rather than an empty tab with no explanation.
424
+ let entries: { name: string; isDirectory(): boolean }[] = [];
425
+ try {
426
+ entries = await readdir(functionsDir, { withFileTypes: true });
427
+ } catch {
428
+ return [];
429
+ }
430
+
431
+ return entries
432
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('_'))
433
+ .map((entry) => ({
434
+ id: entry.name,
435
+ slug: entry.name,
436
+ name: entry.name,
437
+ status: 'LOCAL',
438
+ version: null,
439
+ createdAt: null,
440
+ updatedAt: null,
441
+ verifyJwt: null,
442
+ entrypointPath: join(functionsDir, entry.name, 'index.ts'),
443
+ isLocal: true
444
+ }));
445
+ }
446
+
447
+ /** The source of one function — the deployed body, or the local entrypoint. */
448
+ export async function readEdgeFunctionBody(
449
+ remote: { credentials: SupabaseCredentials; ref: string } | null,
450
+ slug: string,
451
+ functionsDir: string | null
452
+ ): Promise<string> {
453
+ if (remote) {
454
+ // The body endpoint answers with the bundled source as text rather than
455
+ // JSON, so it cannot go through `supabaseRequest`.
456
+ const response = await fetch(
457
+ `https://api.supabase.com/v1/projects/${encodeURIComponent(remote.ref)}/functions/${encodeURIComponent(slug)}/body`,
458
+ {
459
+ headers: { Authorization: `Bearer ${remote.credentials.accessToken}`, 'User-Agent': 'clopen' },
460
+ signal: AbortSignal.timeout(SUPABASE_SLOW_TIMEOUT_MS)
461
+ }
462
+ );
463
+ if (!response.ok) {
464
+ throw new SupabaseError(
465
+ `Could not read ${slug}: ${response.statusText || `HTTP ${response.status}`}`,
466
+ response.status,
467
+ response.status === 401 ? 'auth' : 'error'
468
+ );
469
+ }
470
+ return response.text();
471
+ }
472
+
473
+ if (!functionsDir) throw new Error('No Supabase account and no local functions directory');
474
+ return readFile(join(functionsDir, slug, 'index.ts'), 'utf-8');
475
+ }
476
+
477
+ // ---------------------------------------------------------------------------
478
+ // Generated types — API only, and there is no local equivalent
479
+ // ---------------------------------------------------------------------------
480
+
481
+ export async function generateTypes(
482
+ credentials: SupabaseCredentials,
483
+ ref: string,
484
+ schemas: string[]
485
+ ): Promise<SupabaseTypesResult> {
486
+ const response = await supabaseRequest<SupabaseApiTypes>(
487
+ credentials,
488
+ `/v1/projects/${encodeURIComponent(ref)}/types/typescript`,
489
+ {
490
+ query: { included_schemas: schemas.join(',') || 'public' },
491
+ // Generating types for a large schema is real work upstream, and
492
+ // aborting it at the read budget reports a timeout for something that
493
+ // completed.
494
+ timeoutMs: SUPABASE_SLOW_TIMEOUT_MS
495
+ }
496
+ );
497
+
498
+ return {
499
+ types: response?.types ?? '',
500
+ suggestedPath: 'src/lib/database.types.ts'
501
+ };
502
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The `supabase/config.toml` reader.
3
+ *
4
+ * Worth testing because the mistake it exists to avoid is silent: `port` is set
5
+ * under half a dozen sections in a real config, and a flat scan reports the API
6
+ * port as the database's. The connection then fails with "server does not
7
+ * support SSL" or a protocol error, neither of which points at the config.
8
+ */
9
+
10
+ import { describe, it, expect } from 'bun:test';
11
+ import { parseSupabaseConfig } from './local';
12
+
13
+ /** Trimmed from a real `supabase init` config, keeping the order it writes. */
14
+ const REAL_CONFIG = `
15
+ # A string used to distinguish different Supabase projects on the same host.
16
+ project_id = "acme-web"
17
+
18
+ [api]
19
+ enabled = true
20
+ port = 54321
21
+ schemas = ["public", "graphql_public"]
22
+
23
+ [db]
24
+ # Port to use for the local database URL.
25
+ port = 54322
26
+ shadow_port = 54320
27
+ major_version = 15
28
+
29
+ [db.pooler]
30
+ enabled = false
31
+ port = 54329
32
+
33
+ [studio]
34
+ enabled = true
35
+ port = 54323
36
+ `;
37
+
38
+ describe('parseSupabaseConfig', () => {
39
+ it('reads the project id and the database port', () => {
40
+ const parsed = parseSupabaseConfig(REAL_CONFIG);
41
+ expect(parsed.projectId).toBe('acme-web');
42
+ expect(parsed.dbPort).toBe(54322);
43
+ });
44
+
45
+ it('does not mistake the api port for the database port', () => {
46
+ // `[api]` comes FIRST in the file the CLI writes, so a reader that takes
47
+ // the first `port` it sees is wrong on every real project.
48
+ expect(parseSupabaseConfig(REAL_CONFIG).dbPort).not.toBe(54321);
49
+ });
50
+
51
+ it('does not read a nested section as its parent', () => {
52
+ // `[db.pooler]` is not `[db]`. Treating it as one would pick up 54329.
53
+ expect(parseSupabaseConfig(REAL_CONFIG).dbPort).not.toBe(54329);
54
+ });
55
+
56
+ it('ignores comments and trailing comments', () => {
57
+ const parsed = parseSupabaseConfig(`
58
+ # project_id = "commented-out"
59
+ project_id = "real-one" # the actual value
60
+ `);
61
+ expect(parsed.projectId).toBe('real-one');
62
+ });
63
+
64
+ it('accepts single quotes and bare values', () => {
65
+ expect(parseSupabaseConfig(`project_id = 'quoted'`).projectId).toBe('quoted');
66
+ expect(parseSupabaseConfig(`project_id = bare`).projectId).toBe('bare');
67
+ });
68
+
69
+ it('reports nothing for a config with no project id', () => {
70
+ const parsed = parseSupabaseConfig(`[db]\nport = 54322\n`);
71
+ expect(parsed.projectId).toBe(null);
72
+ expect(parsed.dbPort).toBe(54322);
73
+ });
74
+
75
+ it('rejects a port that is not a number rather than storing NaN', () => {
76
+ expect(parseSupabaseConfig(`[db]\nport = "auto"\n`).dbPort).toBe(null);
77
+ });
78
+ });