diff --git a/package.json b/package.json index d102e98d..46c2f0c3 100644 --- a/package.json +++ b/package.json @@ -19,10 +19,17 @@ "lint": "pnpm -r lint", "format": "prettier --write .", "check": "pnpm typecheck && pnpm test:run && pnpm lint && pnpm build", - "scaffold:species": "pnpm --filter @faunosteo/app scaffold:species" + "scaffold:species": "pnpm --filter @faunosteo/app scaffold:species", + "db:start": "supabase start", + "db:stop": "supabase stop", + "db:reset": "supabase db reset", + "db:test": "supabase test db", + "db:types": "supabase gen types typescript --local --schema public > packages/supabase/src/database.types.ts", + "db:types:check": "supabase gen types typescript --local --schema public | diff - packages/supabase/src/database.types.ts" }, "devDependencies": { "pnpm": "10.13.1", - "prettier": "^3.4.2" + "prettier": "^3.4.2", + "supabase": "^2.100.0" } } diff --git a/packages/supabase/eslint.config.js b/packages/supabase/eslint.config.js new file mode 100644 index 00000000..023d72da --- /dev/null +++ b/packages/supabase/eslint.config.js @@ -0,0 +1,17 @@ +import globals from 'globals' +import tseslint from 'typescript-eslint' + +export default tseslint.config( + { ignores: ['node_modules/**'] }, + { + files: ['**/*.ts'], + extends: [...tseslint.configs.recommended], + languageOptions: { + globals: { ...globals.node, ...globals.es2022 }, + }, + rules: { + '@typescript-eslint/no-explicit-any': 'warn', + '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }], + }, + }, +) diff --git a/packages/supabase/package.json b/packages/supabase/package.json new file mode 100644 index 00000000..be08c258 --- /dev/null +++ b/packages/supabase/package.json @@ -0,0 +1,33 @@ +{ + "name": "@faunosteo/supabase", + "version": "0.1.0", + "private": true, + "description": "Faunosteo Supabase access layer: typed browser client, generated database types, SQL test harness", + "license": "MIT", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./types": "./src/database.types.ts" + }, + "scripts": { + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest", + "test:run": "vitest run", + "lint": "eslint . --max-warnings 0", + "build": "tsc -p tsconfig.json --noEmit" + }, + "dependencies": { + "@supabase/supabase-js": "^2.100.0" + }, + "devDependencies": { + "@electric-sql/pglite": "^0.3.0", + "@types/node": "^20.19.41", + "eslint": "^9.17.0", + "globals": "^15.14.0", + "typescript": "^5.7.2", + "typescript-eslint": "^8.19.0", + "vitest": "^3.2.7" + } +} diff --git a/packages/supabase/src/client.ts b/packages/supabase/src/client.ts new file mode 100644 index 00000000..e626126c --- /dev/null +++ b/packages/supabase/src/client.ts @@ -0,0 +1,29 @@ +import { createClient, type SupabaseClient } from '@supabase/supabase-js' +import type { Database } from './database.types' + +/** Typed Supabase client for the Faunosteo database. */ +export type FaunosteoClient = SupabaseClient + +/** + * Public connection settings. The anon (publishable) key is safe to ship to + * the browser: every table is behind RLS. The service-role key never is. + */ +export interface SupabaseConnection { + url: string + anonKey: string +} + +/** + * Browser client: session persisted in localStorage, tokens refreshed in the + * background, PKCE for OAuth and magic-link redirects. + */ +export function createBrowserClient(connection: SupabaseConnection): FaunosteoClient { + return createClient(connection.url, connection.anonKey, { + auth: { + persistSession: true, + autoRefreshToken: true, + detectSessionInUrl: true, + flowType: 'pkce', + }, + }) +} diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts new file mode 100644 index 00000000..b5c300ca --- /dev/null +++ b/packages/supabase/src/database.types.ts @@ -0,0 +1,271 @@ +// Database types in the `supabase gen types typescript` format. +// Regenerate after every migration: `pnpm db:types` (needs the local stack); +// CI runs `pnpm db:types:check`. packages/supabase/tests/db/schema-types.test.ts +// checks tables, columns, enums and RPC names against the migrated schema. +export type Json = + | string + | number + | boolean + | null + | { [key: string]: Json | undefined } + | Json[] + +export type Database = { + // Allows to automatically instantiate createClient with right options + // instead of createClient(URL, KEY) + __InternalSupabase: { + PostgrestVersion: "13" + } + public: { + Tables: { + profile_roles: { + Row: { + granted_at: string + granted_by: string | null + id: string + revoke_reason: string | null + revoked_at: string | null + revoked_by: string | null + role: Database["public"]["Enums"]["platform_role"] + user_id: string + } + Insert: { + granted_at?: string + granted_by?: string | null + id?: string + revoke_reason?: string | null + revoked_at?: string | null + revoked_by?: string | null + role: Database["public"]["Enums"]["platform_role"] + user_id: string + } + Update: { + granted_at?: string + granted_by?: string | null + id?: string + revoke_reason?: string | null + revoked_at?: string | null + revoked_by?: string | null + role?: Database["public"]["Enums"]["platform_role"] + user_id?: string + } + Relationships: [ + { + foreignKeyName: "profile_roles_granted_by_fkey" + columns: ["granted_by"] + isOneToOne: false + referencedRelation: "profiles" + referencedColumns: ["id"] + }, + { + foreignKeyName: "profile_roles_revoked_by_fkey" + columns: ["revoked_by"] + isOneToOne: false + referencedRelation: "profiles" + referencedColumns: ["id"] + }, + { + foreignKeyName: "profile_roles_user_id_fkey" + columns: ["user_id"] + isOneToOne: false + referencedRelation: "profiles" + referencedColumns: ["id"] + }, + ] + } + profiles: { + Row: { + active: boolean + created_at: string + display_name: string + first_name: string | null + id: string + last_name: string | null + locale: string + phone: string | null + phone_verified_at: string | null + timezone: string + updated_at: string + } + Insert: { + active?: boolean + created_at?: string + display_name: string + first_name?: string | null + id: string + last_name?: string | null + locale?: string + phone?: string | null + phone_verified_at?: string | null + timezone?: string + updated_at?: string + } + Update: { + active?: boolean + created_at?: string + display_name?: string + first_name?: string | null + id?: string + last_name?: string | null + locale?: string + phone?: string | null + phone_verified_at?: string | null + timezone?: string + updated_at?: string + } + Relationships: [] + } + } + Views: { + [_ in never]: never + } + Functions: { + grant_platform_role: { + Args: { + role: Database["public"]["Enums"]["platform_role"] + target_user_id: string + } + Returns: string + } + revoke_platform_role: { + Args: { + reason?: string + role: Database["public"]["Enums"]["platform_role"] + target_user_id: string + } + Returns: string + } + } + Enums: { + platform_role: "owner" | "admin" | "moderator" | "support" + } + CompositeTypes: { + [_ in never]: never + } + } +} + +type DatabaseWithoutInternals = Omit + +type DefaultSchema = DatabaseWithoutInternals[Extract] + +export type Tables< + DefaultSchemaTableNameOrOptions extends + | keyof (DefaultSchema["Tables"] & DefaultSchema["Views"]) + | { schema: keyof DatabaseWithoutInternals }, + TableName extends DefaultSchemaTableNameOrOptions extends { + schema: keyof DatabaseWithoutInternals + } + ? keyof (DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"] & + DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Views"]) + : never = never, +> = DefaultSchemaTableNameOrOptions extends { + schema: keyof DatabaseWithoutInternals +} + ? (DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"] & + DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Views"])[TableName] extends { + Row: infer R + } + ? R + : never + : DefaultSchemaTableNameOrOptions extends keyof (DefaultSchema["Tables"] & + DefaultSchema["Views"]) + ? (DefaultSchema["Tables"] & + DefaultSchema["Views"])[DefaultSchemaTableNameOrOptions] extends { + Row: infer R + } + ? R + : never + : never + +export type TablesInsert< + DefaultSchemaTableNameOrOptions extends + | keyof DefaultSchema["Tables"] + | { schema: keyof DatabaseWithoutInternals }, + TableName extends DefaultSchemaTableNameOrOptions extends { + schema: keyof DatabaseWithoutInternals + } + ? keyof DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"] + : never = never, +> = DefaultSchemaTableNameOrOptions extends { + schema: keyof DatabaseWithoutInternals +} + ? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"][TableName] extends { + Insert: infer I + } + ? I + : never + : DefaultSchemaTableNameOrOptions extends keyof DefaultSchema["Tables"] + ? DefaultSchema["Tables"][DefaultSchemaTableNameOrOptions] extends { + Insert: infer I + } + ? I + : never + : never + +export type TablesUpdate< + DefaultSchemaTableNameOrOptions extends + | keyof DefaultSchema["Tables"] + | { schema: keyof DatabaseWithoutInternals }, + TableName extends DefaultSchemaTableNameOrOptions extends { + schema: keyof DatabaseWithoutInternals + } + ? keyof DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"] + : never = never, +> = DefaultSchemaTableNameOrOptions extends { + schema: keyof DatabaseWithoutInternals +} + ? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"][TableName] extends { + Update: infer U + } + ? U + : never + : DefaultSchemaTableNameOrOptions extends keyof DefaultSchema["Tables"] + ? DefaultSchema["Tables"][DefaultSchemaTableNameOrOptions] extends { + Update: infer U + } + ? U + : never + : never + +export type Enums< + DefaultSchemaEnumNameOrOptions extends + | keyof DefaultSchema["Enums"] + | { schema: keyof DatabaseWithoutInternals }, + EnumName extends DefaultSchemaEnumNameOrOptions extends { + schema: keyof DatabaseWithoutInternals + } + ? keyof DatabaseWithoutInternals[DefaultSchemaEnumNameOrOptions["schema"]]["Enums"] + : never = never, +> = DefaultSchemaEnumNameOrOptions extends { + schema: keyof DatabaseWithoutInternals +} + ? DatabaseWithoutInternals[DefaultSchemaEnumNameOrOptions["schema"]]["Enums"][EnumName] + : DefaultSchemaEnumNameOrOptions extends keyof DefaultSchema["Enums"] + ? DefaultSchema["Enums"][DefaultSchemaEnumNameOrOptions] + : never + +export type CompositeTypes< + PublicCompositeTypeNameOrOptions extends + | keyof DefaultSchema["CompositeTypes"] + | { schema: keyof DatabaseWithoutInternals }, + CompositeTypeName extends PublicCompositeTypeNameOrOptions extends { + schema: keyof DatabaseWithoutInternals + } + ? keyof DatabaseWithoutInternals[PublicCompositeTypeNameOrOptions["schema"]]["CompositeTypes"] + : never = never, +> = PublicCompositeTypeNameOrOptions extends { + schema: keyof DatabaseWithoutInternals +} + ? DatabaseWithoutInternals[PublicCompositeTypeNameOrOptions["schema"]]["CompositeTypes"][CompositeTypeName] + : PublicCompositeTypeNameOrOptions extends keyof DefaultSchema["CompositeTypes"] + ? DefaultSchema["CompositeTypes"][PublicCompositeTypeNameOrOptions] + : never + +export const Constants = { + public: { + Enums: { + platform_role: ["owner", "admin", "moderator", "support"], + }, + }, +} as const diff --git a/packages/supabase/src/index.ts b/packages/supabase/src/index.ts new file mode 100644 index 00000000..b3ddf824 --- /dev/null +++ b/packages/supabase/src/index.ts @@ -0,0 +1,23 @@ +export { + createBrowserClient, + type FaunosteoClient, + type SupabaseConnection, +} from './client' +export type { + Database, + Enums, + Json, + Tables, + TablesInsert, + TablesUpdate, +} from './database.types' +export { Constants } from './database.types' + +import type { Enums, Tables } from './database.types' + +/** Row of public.profiles. */ +export type Profile = Tables<'profiles'> +/** Row of public.profile_roles. */ +export type ProfileRole = Tables<'profile_roles'> +/** owner | admin | moderator | support. Not a professional status. */ +export type PlatformRole = Enums<'platform_role'> diff --git a/packages/supabase/tests/client.test.ts b/packages/supabase/tests/client.test.ts new file mode 100644 index 00000000..15949b1d --- /dev/null +++ b/packages/supabase/tests/client.test.ts @@ -0,0 +1,21 @@ +import { createBrowserClient, Constants, type PlatformRole } from '../src' + +describe('createBrowserClient', () => { + it('builds a typed client bound to the given project URL', () => { + const client = createBrowserClient({ + url: 'http://127.0.0.1:54321', + anonKey: 'anon-key-placeholder', + }) + expect(typeof client.from).toBe('function') + expect(client.auth).toBeDefined() + // supabase-js keeps the resolved REST URL on the client instance. + expect(String((client as unknown as { supabaseUrl: string }).supabaseUrl)).toContain( + '127.0.0.1:54321', + ) + }) + + it('exposes the platform roles as runtime constants', () => { + const roles: readonly PlatformRole[] = Constants.public.Enums.platform_role + expect(roles).toEqual(['owner', 'admin', 'moderator', 'support']) + }) +}) diff --git a/packages/supabase/tests/db/harness.ts b/packages/supabase/tests/db/harness.ts new file mode 100644 index 00000000..6fdf8085 --- /dev/null +++ b/packages/supabase/tests/db/harness.ts @@ -0,0 +1,80 @@ +/** + * PGlite harness: a real PostgreSQL (WASM) that applies the Supabase shim, + * then every migration under supabase/migrations, in filename order. + * Lets the pgTAP suite and the schema checks run without Docker. The same + * SQL runs unchanged under `supabase test db` on the real stack. + */ +import { readdir, readFile } from 'node:fs/promises' +import { resolve, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { PGlite } from '@electric-sql/pglite' +import { pgtap } from '@electric-sql/pglite/pgtap' + +const here = fileURLToPath(new URL('.', import.meta.url)) +export const repoRoot = resolve(here, '../../../..') +export const supabaseDir = join(repoRoot, 'supabase') +export const migrationsDir = join(supabaseDir, 'migrations') +export const pgTapTestsDir = join(supabaseDir, 'tests') + +async function listSqlFiles(dir: string): Promise { + const entries = await readdir(dir) + return entries.filter((f) => f.endsWith('.sql')).sort() +} + +export async function listMigrations(): Promise { + return listSqlFiles(migrationsDir) +} + +export async function listPgTapTests(): Promise { + return listSqlFiles(pgTapTestsDir) +} + +/** Boots PGlite, installs the shim and applies all migrations. */ +export async function createMigratedDatabase(): Promise { + const db = await PGlite.create({ extensions: { pgtap } }) + await db.exec(await readFile(join(here, 'supabase-shim.sql'), 'utf8')) + // Same placement as `supabase test db`: pgTAP lives in extensions, out of public. + await db.exec('create extension if not exists pgtap with schema extensions;') + await db.exec('set search_path to public, extensions;') + for (const file of await listMigrations()) { + await db.exec(await readFile(join(migrationsDir, file), 'utf8')) + } + return db +} + +export interface TapReport { + lines: string[] + failures: string[] +} + +function collectTapLines(results: Array<{ rows: unknown[] }>): string[] { + const lines: string[] = [] + for (const result of results) { + for (const row of result.rows) { + const values = Object.values(row as Record) + for (const value of values) { + if (typeof value === 'string') lines.push(...value.split('\n')) + } + } + } + return lines +} + +/** + * Runs one pgTAP file (which must wrap itself in begin/rollback) and reports + * every `not ok` line plus plan mismatches announced by finish(). + */ +export async function runPgTapFile(db: PGlite, file: string): Promise { + const sql = await readFile(join(pgTapTestsDir, file), 'utf8') + let lines: string[] + try { + lines = collectTapLines(await db.exec(sql)) + } finally { + // A failing statement leaves the transaction aborted: always clean up. + await db.exec('rollback;').catch(() => undefined) + } + const failures = lines.filter( + (line) => /^not ok\b/.test(line) || /^# Looks like/.test(line), + ) + return { lines, failures } +} diff --git a/packages/supabase/tests/db/pgtap.test.ts b/packages/supabase/tests/db/pgtap.test.ts new file mode 100644 index 00000000..12cbf4b3 --- /dev/null +++ b/packages/supabase/tests/db/pgtap.test.ts @@ -0,0 +1,36 @@ +/** + * Runs every pgTAP file under supabase/tests against a migrated PGlite + * database. One vitest case per SQL file: the failing TAP lines are the + * assertion message, so a red test names the exact pgTAP check. + */ +import type { PGlite } from '@electric-sql/pglite' +import { + createMigratedDatabase, + listPgTapTests, + runPgTapFile, +} from './harness' + +const files = await listPgTapTests() + +describe('pgTAP suite (supabase/tests) on PGlite', () => { + let db: PGlite + + beforeAll(async () => { + db = await createMigratedDatabase() + }) + + afterAll(async () => { + await db?.close() + }) + + it('finds at least one pgTAP file', () => { + expect(files.length).toBeGreaterThan(0) + }) + + it.each(files)('%s passes', async (file) => { + const report = await runPgTapFile(db, file) + const okCount = report.lines.filter((l) => /^ok\b/.test(l)).length + expect(report.failures, report.lines.join('\n')).toEqual([]) + expect(okCount).toBeGreaterThan(0) + }) +}) diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts new file mode 100644 index 00000000..52d39074 --- /dev/null +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -0,0 +1,157 @@ +/** + * database.types.ts must describe the migrated schema: same tables, same + * columns, same enum labels, same RPC names and arguments. The column map + * below is checked twice: by the compiler (every listed name exists in the + * type, and the type has no column missing from the list) and at runtime + * against information_schema in PGlite. + * + * Also pins two invariants for every future table in public: RLS enabled, and + * no `using (true)` policy for authenticated. + */ +import type { PGlite } from '@electric-sql/pglite' +import { Constants, type Database } from '../../src/database.types' +import { createMigratedDatabase } from './harness' + +type Tables = Database['public']['Tables'] +type Functions = Database['public']['Functions'] + +type ColumnMap = { readonly [T in keyof Tables]: readonly (keyof Tables[T]['Row'] & string)[] } + +const expectedColumns = { + profile_roles: [ + 'granted_at', + 'granted_by', + 'id', + 'revoke_reason', + 'revoked_at', + 'revoked_by', + 'role', + 'user_id', + ], + profiles: [ + 'active', + 'created_at', + 'display_name', + 'first_name', + 'id', + 'last_name', + 'locale', + 'phone', + 'phone_verified_at', + 'timezone', + 'updated_at', + ], +} as const satisfies ColumnMap + +// Compile-time: a column present in the type but absent from the list is an error. +type MissingColumns = { + [T in keyof Tables]: Exclude +}[keyof Tables] +const noMissingColumn: MissingColumns extends never ? true : never = true + +type FunctionArgs = { readonly [F in keyof Functions]: readonly (keyof Functions[F]['Args'] & string)[] } +const expectedFunctionArgs = { + grant_platform_role: ['role', 'target_user_id'], + revoke_platform_role: ['reason', 'role', 'target_user_id'], +} as const satisfies FunctionArgs + +type MissingArgs = { + [F in keyof Functions]: Exclude +}[keyof Functions] +const noMissingArg: MissingArgs extends never ? true : never = true + +interface ColumnRow { + table_name: string + column_name: string +} +interface NameRow { + name: string +} +interface FunctionRow { + name: string + args: string[] +} +interface PolicyRow { + tablename: string + policyname: string +} + +describe('database.types.ts matches the migrated schema', () => { + let db: PGlite + + beforeAll(async () => { + db = await createMigratedDatabase() + }) + + afterAll(async () => { + await db?.close() + }) + + it('has the compile-time exhaustiveness witnesses', () => { + expect(noMissingColumn).toBe(true) + expect(noMissingArg).toBe(true) + }) + + it('lists exactly the public tables and their columns', async () => { + const { rows } = await db.query( + `select table_name, column_name + from information_schema.columns + where table_schema = 'public' + order by table_name, column_name`, + ) + const actual: Record = {} + for (const row of rows) (actual[row.table_name] ??= []).push(row.column_name) + const expected = Object.fromEntries( + Object.entries(expectedColumns).map(([table, cols]) => [table, [...cols].sort()]), + ) + expect(actual).toEqual(expected) + }) + + it('lists the enum labels in order', async () => { + const { rows } = await db.query( + `select e.enumlabel as name + from pg_enum e join pg_type t on t.oid = e.enumtypid + join pg_namespace n on n.oid = t.typnamespace + where n.nspname = 'public' and t.typname = 'platform_role' + order by e.enumsortorder`, + ) + expect(rows.map((r) => r.name)).toEqual([...Constants.public.Enums.platform_role]) + }) + + it('lists exactly the public functions and their argument names', async () => { + const { rows } = await db.query( + `select p.proname as name, coalesce(p.proargnames, '{}') as args + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'public' and p.prokind = 'f' + and not exists ( + select 1 from pg_depend d where d.objid = p.oid and d.deptype = 'e' + ) + order by p.proname`, + ) + const actual = Object.fromEntries(rows.map((r) => [r.name, [...r.args].sort()])) + const expected = Object.fromEntries( + Object.entries(expectedFunctionArgs).map(([fn, args]) => [fn, [...args].sort()]), + ) + expect(actual).toEqual(expected) + }) + + it('keeps RLS enabled on every public table', async () => { + const { rows } = await db.query( + `select c.relname as name + from pg_class c join pg_namespace n on n.oid = c.relnamespace + where n.nspname = 'public' and c.relkind = 'r' and not c.relrowsecurity`, + ) + expect(rows).toEqual([]) + }) + + it('has no unconditional policy for API roles', async () => { + const { rows } = await db.query( + `select tablename, policyname + from pg_policies + where schemaname = 'public' + and (qual = 'true' or with_check = 'true') + and roles && array['authenticated', 'anon']::name[]`, + ) + expect(rows).toEqual([]) + }) +}) diff --git a/packages/supabase/tests/db/supabase-shim.sql b/packages/supabase/tests/db/supabase-shim.sql new file mode 100644 index 00000000..066394cd --- /dev/null +++ b/packages/supabase/tests/db/supabase-shim.sql @@ -0,0 +1,75 @@ +-- Minimal stand-in for the Supabase base schema, applied to a bare PGlite +-- database before the project migrations. Mirrors what the hosted/local stack +-- provides: API roles, auth schema with users table + JWT claim helpers, and +-- the permissive default privileges on public (ALL to the API roles), so a +-- migration that forgets to revoke is caught by the tests. +-- Test-only file: never applied to a real Supabase database. + +create role anon nologin noinherit; +create role authenticated nologin noinherit; +create role service_role nologin noinherit bypassrls; + +create schema auth; +create schema extensions; + +create table auth.users ( + instance_id uuid, + id uuid primary key default gen_random_uuid(), + aud varchar(255), + role varchar(255), + email varchar(255), + encrypted_password varchar(255), + email_confirmed_at timestamptz, + raw_app_meta_data jsonb, + raw_user_meta_data jsonb, + created_at timestamptz default now(), + updated_at timestamptz default now() +); + +create or replace function auth.uid() +returns uuid +language sql +stable +as $$ + select nullif( + coalesce( + current_setting('request.jwt.claim.sub', true), + (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub') + ), + '' + )::uuid +$$; + +create or replace function auth.role() +returns text +language sql +stable +as $$ + select nullif( + coalesce( + current_setting('request.jwt.claim.role', true), + (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'role') + ), + '' + )::text +$$; + +create or replace function auth.jwt() +returns jsonb +language sql +stable +as $$ + select coalesce( + nullif(current_setting('request.jwt.claim', true), ''), + nullif(current_setting('request.jwt.claims', true), '') + )::jsonb +$$; + +grant usage on schema auth to anon, authenticated, service_role; +grant execute on function auth.uid(), auth.role(), auth.jwt() to anon, authenticated, service_role; + +grant usage on schema public to anon, authenticated, service_role; +grant usage on schema extensions to anon, authenticated, service_role; +alter default privileges in schema public grant all on tables to anon, authenticated, service_role; +alter default privileges in schema public grant all on functions to anon, authenticated, service_role; +alter default privileges in schema public grant all on sequences to anon, authenticated, service_role; diff --git a/packages/supabase/tsconfig.json b/packages/supabase/tsconfig.json new file mode 100644 index 00000000..985fbacd --- /dev/null +++ b/packages/supabase/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM"], + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "skipLibCheck": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "isolatedModules": true, + "types": ["node", "vitest/globals"], + "noEmit": true + }, + "include": ["src", "tests"], + "exclude": ["node_modules"] +} diff --git a/packages/supabase/vitest.config.ts b/packages/supabase/vitest.config.ts new file mode 100644 index 00000000..91ab39c3 --- /dev/null +++ b/packages/supabase/vitest.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + globals: true, + include: ['tests/**/*.test.ts'], + // PGlite boots a WASM Postgres per file: give it room on slow CI runners. + testTimeout: 60_000, + hookTimeout: 120_000, + }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f0318419..b99ca1cb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: prettier: specifier: ^3.4.2 version: 3.8.3 + supabase: + specifier: ^2.100.0 + version: 2.120.0 apps/app: dependencies: @@ -91,6 +94,34 @@ importers: specifier: ^3.2.7 version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0) + packages/supabase: + dependencies: + '@supabase/supabase-js': + specifier: ^2.100.0 + version: 2.117.3 + devDependencies: + '@electric-sql/pglite': + specifier: ^0.3.0 + version: 0.3.16 + '@types/node': + specifier: ^20.19.41 + version: 20.19.41 + eslint: + specifier: ^9.17.0 + version: 9.39.4(jiti@2.7.0) + globals: + specifier: ^15.14.0 + version: 15.15.0 + typescript: + specifier: ^5.7.2 + version: 5.9.3 + typescript-eslint: + specifier: ^8.19.0 + version: 8.59.3(eslint@9.39.4(jiti@2.7.0))(typescript@5.9.3) + vitest: + specifier: ^3.2.7 + version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0) + packages: '@adobe/css-tools@4.4.4': @@ -108,6 +139,15 @@ packages: resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==} engines: {node: '>=6.9.0'} + '@ecies/ciphers@0.2.6': + resolution: {integrity: sha512-patgsRPKGkhhoBjETV4XxD0En4ui5fbX0hzayqI3M8tvNMGUoUvmyYAIWwlxBc1KX5cturfqByYdj5bYGRpN9g==} + engines: {bun: '>=1', deno: '>=2.7.10', node: '>=16'} + peerDependencies: + '@noble/ciphers': ^1.0.0 + + '@electric-sql/pglite@0.3.16': + resolution: {integrity: sha512-mZkZfOd9OqTMHsK+1cje8OSzfAQcpD7JmILXTl5ahdempjUDdmg4euf1biDex5/LfQIDJ3gvCu6qDgdnDxfJmA==} + '@esbuild/aix-ppc64@0.28.1': resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} engines: {node: '>=18'} @@ -338,6 +378,18 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@noble/ciphers@1.3.0': + resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==} + engines: {node: ^14.21.3 || >=16} + + '@noble/curves@1.9.7': + resolution: {integrity: sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==} + engines: {node: ^14.21.3 || >=16} + + '@noble/hashes@1.8.0': + resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} + engines: {node: ^14.21.3 || >=16} + '@pdf-lib/standard-fonts@1.0.0': resolution: {integrity: sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==} @@ -472,6 +524,78 @@ packages: cpu: [x64] os: [win32] + '@supabase/auth-js@2.117.3': + resolution: {integrity: sha512-XOZV+jllcU2Hzij8SwgM78zl0lOEr6BTjzi2MYkBb39nOAQzb5AelGpMUvVj7lwGSB11JmpAs/FEQroAyFzWEA==} + engines: {node: '>=22.0.0'} + + '@supabase/cli-darwin-arm64@2.120.0': + resolution: {integrity: sha512-GXjW2+J4dGYjbZW0oeDs9y8+Eo/AloRYkbc7LpZmKagc1NYVPzQyviSHZ8LzidCXGlNF3Gds3k8UetjTQQmXbQ==} + cpu: [arm64] + os: [darwin] + + '@supabase/cli-darwin-x64@2.120.0': + resolution: {integrity: sha512-o6ISS9smQnNfpws2nqs3e9lxA0UTsWGI9LAvz2zMymRm11Iy8vZIeOXHV8BbGQWtqxLgfiHHCVvBLE9/41AKQA==} + cpu: [x64] + os: [darwin] + + '@supabase/cli-linux-arm64-musl@2.120.0': + resolution: {integrity: sha512-+4IwiBpGOQgLFeEG6RImxSUrMHo+LDsFNGJ4WLoLBOozFaippoz5J6CnNpVSTeJj9QaOX3G9iVsL/wYF6P1Cxw==} + cpu: [arm64] + os: [linux] + + '@supabase/cli-linux-arm64@2.120.0': + resolution: {integrity: sha512-pmR61xpBmzUc79gkh3sE42KtBkludBXex1TIQTVY6jkTjs2+JhJYNKxR7udeaFgxFpiV+zTeAyqJBYXLibxQJw==} + cpu: [arm64] + os: [linux] + + '@supabase/cli-linux-x64-musl@2.120.0': + resolution: {integrity: sha512-YIrqu1+hBiLwYIk1HKesrfIm2ycQIsOfN5VGV3r/okQx8JyWl9Jrw7emKVS/F+1afe+1MqKEBP70B0PbuvX+jQ==} + cpu: [x64] + os: [linux] + + '@supabase/cli-linux-x64@2.120.0': + resolution: {integrity: sha512-IWJ0yFefhX/69ofcgJfN8MyOC9TtCG4SLrlMCvXjH3vZXxnRkiVNggxQqUCIhshS9Afa+q17DRbQen7/IZTL4A==} + cpu: [x64] + os: [linux] + + '@supabase/cli-windows-arm64@2.120.0': + resolution: {integrity: sha512-U+IDegKWC4xXxk7aCRUUy2ZTJ4bwwrcVlnzG1VJqC7nB7SLgMiyUMyvuo1tB+Xt8hHf0hkuViNtohnXPdZHCIQ==} + cpu: [arm64] + os: [win32] + + '@supabase/cli-windows-x64@2.120.0': + resolution: {integrity: sha512-y96p4JdUuKygzUDCRo1T8yEiLbyWIiL/4Qdnmgu/X84WJOZmji/TlW5ThqDllsQuGWbkgovy+6LLqWKHk330XQ==} + cpu: [x64] + os: [win32] + + '@supabase/functions-js@2.117.3': + resolution: {integrity: sha512-6GuizbP4N5xWaxEVUsI+UQpJdmMmn0t3sYNpObo9gCAldvM22gFjnYzRVmkHxp5ylU21azEYmiWVwk9iDgCMkQ==} + engines: {node: '>=22.0.0'} + + '@supabase/phoenix@0.4.5': + resolution: {integrity: sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==} + + '@supabase/postgrest-js@2.117.3': + resolution: {integrity: sha512-NpyTgullu6tw11ojYKTdZg9HannZ4mu4FUlhc9V5zDXOVllUJzEmuyLM+WWoYF0BurfrRvarimpm3SR8P0Gzfw==} + engines: {node: '>=22.0.0'} + + '@supabase/realtime-js@2.117.3': + resolution: {integrity: sha512-4W4ISbreRygNXbhwqxeqyuRul8RPx+SF+Hp2IT8wctebQEHSVCULfKatiRiEhmasfoXvYm2AHV4XFsOxhoousA==} + engines: {node: '>=22.0.0'} + + '@supabase/storage-js@2.117.3': + resolution: {integrity: sha512-QhUxFC33Crlw6WDeA4hLADdi1PzjI3c4UJs7ivWHHEnU7ulmCWEZSDaRCuIfmsjUwbHYaIfRNFQNsm+IsGYS6w==} + engines: {node: '>=22.0.0'} + + '@supabase/supabase-js@2.117.3': + resolution: {integrity: sha512-K+f8PimXDunPWQ63CKRXaF5pbVPJxmfw5ryAnh0s9S9PkwcuqBjiSpIaqpF7KLDljeYwXIL85ST8QxaO0+XuvA==} + engines: {node: '>=22.0.0'} + peerDependencies: + '@opentelemetry/api': '>=1.0.0' + peerDependenciesMeta: + '@opentelemetry/api': + optional: true + '@swc/core-darwin-arm64@1.15.33': resolution: {integrity: sha512-N+L0uXhuO7FIfzqwgxmzv0zIpV0qEp8wPX3QQs2p4atjMoywup2JTeDlXPw+z9pWJGCae3JjM+tZ6myclI+2gA==} engines: {node: '>=10'} @@ -1013,6 +1137,10 @@ packages: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} + eciesjs@0.5.0: + resolution: {integrity: sha512-s0J9SEVYAEPg7J63GFMApLYzPH9VNIQIyC6s15JpnqVc0TqcKWdbgFlnAweEBRyMmko2dcs2sfC83Hj4J43tuA==} + engines: {bun: '>=1', deno: '>=2.7.10', node: '>=16'} + enhanced-resolve@5.21.3: resolution: {integrity: sha512-QyL119InA+XXEkNLNTPCXPugSvOfhwv0JOlGNzvxs0hZaiHLNvXSpudUWsOlsXGWJh8G6ckCScEkVHfX3kw/2Q==} engines: {node: '>=10.13.0'} @@ -1267,6 +1395,10 @@ packages: resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==} engines: {node: '>= 0.4'} + iceberg-js@0.8.1: + resolution: {integrity: sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==} + engines: {node: '>=20.0.0'} + ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -1401,6 +1533,9 @@ packages: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} hasBin: true + jose@6.2.12: + resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -1852,6 +1987,10 @@ packages: strip-literal@3.1.0: resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==} + supabase@2.120.0: + resolution: {integrity: sha512-NF8ueHsOZMbyiFJARKbiZy9AhNtj5E5R49P+cVqlv2u/T2JpMtsvp29YgPgrIWkVUjsfhJseTmKEdckatSeWZQ==} + hasBin: true + supports-color@7.2.0: resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} engines: {node: '>=8'} @@ -2101,6 +2240,12 @@ snapshots: '@babel/runtime@7.29.2': {} + '@ecies/ciphers@0.2.6(@noble/ciphers@1.3.0)': + dependencies: + '@noble/ciphers': 1.3.0 + + '@electric-sql/pglite@0.3.16': {} + '@esbuild/aix-ppc64@0.28.1': optional: true @@ -2260,6 +2405,14 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@noble/ciphers@1.3.0': {} + + '@noble/curves@1.9.7': + dependencies: + '@noble/hashes': 1.8.0 + + '@noble/hashes@1.8.0': {} + '@pdf-lib/standard-fonts@1.0.0': dependencies: pako: 1.0.11 @@ -2345,6 +2498,62 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.60.4': optional: true + '@supabase/auth-js@2.117.3': + dependencies: + tslib: 2.8.1 + + '@supabase/cli-darwin-arm64@2.120.0': + optional: true + + '@supabase/cli-darwin-x64@2.120.0': + optional: true + + '@supabase/cli-linux-arm64-musl@2.120.0': + optional: true + + '@supabase/cli-linux-arm64@2.120.0': + optional: true + + '@supabase/cli-linux-x64-musl@2.120.0': + optional: true + + '@supabase/cli-linux-x64@2.120.0': + optional: true + + '@supabase/cli-windows-arm64@2.120.0': + optional: true + + '@supabase/cli-windows-x64@2.120.0': + optional: true + + '@supabase/functions-js@2.117.3': + dependencies: + tslib: 2.8.1 + + '@supabase/phoenix@0.4.5': {} + + '@supabase/postgrest-js@2.117.3': + dependencies: + tslib: 2.8.1 + + '@supabase/realtime-js@2.117.3': + dependencies: + '@supabase/phoenix': 0.4.5 + tslib: 2.8.1 + + '@supabase/storage-js@2.117.3': + dependencies: + iceberg-js: 0.8.1 + tslib: 2.8.1 + + '@supabase/supabase-js@2.117.3': + dependencies: + '@supabase/auth-js': 2.117.3 + '@supabase/functions-js': 2.117.3 + '@supabase/postgrest-js': 2.117.3 + '@supabase/realtime-js': 2.117.3 + '@supabase/storage-js': 2.117.3 + '@swc/core-darwin-arm64@1.15.33': optional: true @@ -2904,6 +3113,13 @@ snapshots: es-errors: 1.3.0 gopd: 1.2.0 + eciesjs@0.5.0: + dependencies: + '@ecies/ciphers': 0.2.6(@noble/ciphers@1.3.0) + '@noble/ciphers': 1.3.0 + '@noble/curves': 1.9.7 + '@noble/hashes': 1.8.0 + enhanced-resolve@5.21.3: dependencies: graceful-fs: 4.2.11 @@ -3280,6 +3496,8 @@ snapshots: dependencies: function-bind: 1.1.2 + iceberg-js@0.8.1: {} + ignore@5.3.2: {} ignore@7.0.5: {} @@ -3420,6 +3638,8 @@ snapshots: jiti@2.7.0: {} + jose@6.2.12: {} + js-tokens@4.0.0: {} js-tokens@9.0.1: {} @@ -3912,6 +4132,20 @@ snapshots: dependencies: js-tokens: 9.0.1 + supabase@2.120.0: + dependencies: + eciesjs: 0.5.0 + jose: 6.2.12 + optionalDependencies: + '@supabase/cli-darwin-arm64': 2.120.0 + '@supabase/cli-darwin-x64': 2.120.0 + '@supabase/cli-linux-arm64': 2.120.0 + '@supabase/cli-linux-arm64-musl': 2.120.0 + '@supabase/cli-linux-x64': 2.120.0 + '@supabase/cli-linux-x64-musl': 2.120.0 + '@supabase/cli-windows-arm64': 2.120.0 + '@supabase/cli-windows-x64': 2.120.0 + supports-color@7.2.0: dependencies: has-flag: 4.0.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index d6bfc053..5a348c66 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -7,3 +7,5 @@ packages: onlyBuiltDependencies: - '@swc/core' - esbuild + # Supabase CLI npm wrapper downloads its binary in a postinstall script. + - supabase