Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(database): version the schema as Supabase CLI migrations

spacesdrive5f56b72833fa
diff --git a/backend/tests/database/migrations.test.ts b/backend/tests/database/migrations.test.ts
new file mode 100644
index 0000000..e56d3e3
--- /dev/null
+++ b/backend/tests/database/migrations.test.ts
@@ -0,0 +1,52 @@
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import { readdirSync, readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const supabase = fileURLToPath(new URL('../../../supabase/', import.meta.url));
+const migrations = readdirSync(`${supabase}migrations`).sort();
+const rollbacks = readdirSync(`${supabase}rollbacks`).sort();
+const read = (folder: string, name: string) => readFileSync(`${supabase}${folder}/${name}`, 'utf8');
+const isBaseline = (name: string) => /^\d{14}_baseline_/.test(name);
+
+describe('database migrations', () => {
+ test('every migration is named <14 digit version>_<lowercase name>.sql with a unique version', () => {
+ for (const name of [...migrations, ...rollbacks]) assert.match(name, /^\d{14}_[a-z0-9_]+\.sql$/, name);
+ const versions = migrations.map(name => name.slice(0, 14));
+ assert.equal(new Set(versions).size, versions.length);
+ });
+
+ test('the baseline files come before every change, so a new instance starts from the same tables', () => {
+ const lastBaseline = migrations.findLastIndex(isBaseline);
+ const firstChange = migrations.findIndex(name => !isBaseline(name));
+ assert.ok(lastBaseline >= 0);
+ assert.ok(lastBaseline < firstChange);
+ });
+
+ test('every change has a rollback with the same name, and every rollback has its migration', () => {
+ assert.deepEqual(rollbacks, migrations.filter(name => !isBaseline(name)));
+ });
+
+ test('the baseline files can run again on a database that has them', () => {
+ for (const name of migrations.filter(isBaseline)) {
+ const sql = read('migrations', name);
+ assert.doesNotMatch(sql, /create table (?!if not exists)/i, name);
+ assert.doesNotMatch(sql, /create index (?!if not exists)/i, name);
+ assert.doesNotMatch(sql, /add column (?!if not exists)/i, name);
+ }
+ });
+
+ test('every function a migration creates is closed to the browser roles', () => {
+ for (const name of migrations) {
+ const sql = read('migrations', name);
+ for (const [, fn] of sql.matchAll(/create or replace function (public\.\w+)/gi)) {
+ assert.match(sql, new RegExp(`revoke execute on function ${fn.replace('.', '\\.')}\\(.*\\) from public, anon, authenticated`), `${name}: ${fn}`);
+ }
+ }
+ });
+
+ test('no file uses an em or en dash', () => {
+ for (const name of migrations) assert.doesNotMatch(read('migrations', name), /[–—]/, name);
+ for (const name of rollbacks) assert.doesNotMatch(read('rollbacks', name), /[–—]/, name);
+ });
+});
diff --git a/package-lock.json b/package-lock.json
index 3e50820..bdb8bf6 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -21,6 +21,7 @@
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"prettier": "^3.9.9",
+ "supabase": "^2.121.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.71.2"
},
@@ -926,6 +927,21 @@
"integrity": "sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg==",
"license": "BSD-3-Clause"
},
+ "node_modules/@ecies/ciphers": {
+ "version": "0.2.6",
+ "resolved": "https://registry.npmjs.org/@ecies/ciphers/-/ciphers-0.2.6.tgz",
+ "integrity": "sha512-patgsRPKGkhhoBjETV4XxD0En4ui5fbX0hzayqI3M8tvNMGUoUvmyYAIWwlxBc1KX5cturfqByYdj5bYGRpN9g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "bun": ">=1",
+ "deno": ">=2.7.10",
+ "node": ">=16"
+ },
+ "peerDependencies": {
+ "@noble/ciphers": "^1.0.0"
+ }
+ },
"node_modules/@emnapi/runtime": {
"version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
@@ -2312,6 +2328,49 @@
"node": "^22.20 || ^24.12 || >=25"
}
},
+ "node_modules/@noble/ciphers": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
+ "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": "^14.21.3 || >=16"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@noble/curves": {
+ "version": "1.9.7",
+ "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz",
+ "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@noble/hashes": "1.8.0"
+ },
+ "engines": {
+ "node": "^14.21.3 || >=16"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@noble/hashes": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
+ "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^14.21.3 || >=16"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -3255,6 +3314,118 @@
"node": ">=22.0.0"
}
},
+ "node_modules/@supabase/cli-darwin-arm64": {
+ "version": "2.121.0",
+ "resolved": "https://registry.npmjs.org/@supabase/cli-darwin-arm64/-/cli-darwin-arm64-2.121.0.tgz",
+ "integrity": "sha512-ZvXKj3wW4Kq5/MrG2xdgZeOWETxmUC9jl16X/i/np7u5A/WLuC/L0+KKY5i0eCrTnNwWFpZdlWKzu/J9QgkPgg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@supabase/cli-darwin-x64": {
+ "version": "2.121.0",
+ "resolved": "https://registry.npmjs.org/@supabase/cli-darwin-x64/-/cli-darwin-x64-2.121.0.tgz",
+ "integrity": "sha512-s+bnLljdI5MYlt92rJnsIuVcTYtmJyydUB/FUsKm5KCyD+HpwnY1hL6m/+bKZQCwIHsql1dlmJRZ0HNZOZzuTQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@supabase/cli-linux-arm64": {
+ "version": "2.121.0",
+ "resolved": "https://registry.npmjs.org/@supabase/cli-linux-arm64/-/cli-linux-arm64-2.121.0.tgz",
+ "integrity": "sha512-JKvffWRuzS1+cVzgv1gWi2nWaCGvS22mMMwEBnSkRFD0BSdN1QHZ7yteI7uRg1HV9R0s+HCwg1rtjrHnAEE55Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@supabase/cli-linux-arm64-musl": {
+ "version": "2.121.0",
+ "resolved": "https://registry.npmjs.org/@supabase/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.121.0.tgz",
+ "integrity": "sha512-8fGnWhnnbf3zdV7mQvEHb4qa1LMTq/JpSdO109O/Lxy246Dwar8o5XrDgy7bBK8QLzvp0XH+p1ky+wxRGVFzpw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@supabase/cli-linux-x64": {
+ "version": "2.121.0",
+ "resolved": "https://registry.npmjs.org/@supabase/cli-linux-x64/-/cli-linux-x64-2.121.0.tgz",
+ "integrity": "sha512-87EhtLctkNtC51CPhyeLoSdoGGzCZ3iNbSdczdcSklbvg0RsJbU+mTDaF3v53EWuPhyM0VRYqZJZNnjI5ABLcg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@supabase/cli-linux-x64-musl": {
+ "version": "2.121.0",
+ "resolved": "https://registry.npmjs.org/@supabase/cli-linux-x64-musl/-/cli-linux-x64-musl-2.121.0.tgz",
+ "integrity": "sha512-diDbFsC/KRmnOGUYYBxmUqn6ccqB+jliesMfp821grDIVkq9ucqg/aUjCOsCyRbcs5uhgbbWgh9YWTuxfVpZog==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@supabase/cli-windows-arm64": {
+ "version": "2.121.0",
+ "resolved": "https://registry.npmjs.org/@supabase/cli-windows-arm64/-/cli-windows-arm64-2.121.0.tgz",
+ "integrity": "sha512-cHpGQTLXUm4Uk9NzIdv8oUvmsNq7mlAN/CmVqNYzMUJyqmFofOPETwYPShDV9apA+5k84oKU93tn3N4wv7B3yg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@supabase/cli-windows-x64": {
+ "version": "2.121.0",
+ "resolved": "https://registry.npmjs.org/@supabase/cli-windows-x64/-/cli-windows-x64-2.121.0.tgz",
+ "integrity": "sha512-uvWiQ3cGKrZhtkctXHJJY0r0L6D2s/Dbc8/CxOVDxlXIH5mG3f8ZbqwMs9eRbPDqifyYFlwl+BX+tY3aJosIxQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
"node_modules/@supabase/functions-js": {
"version": "2.110.0",
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.110.0.tgz",
@@ -5449,6 +5620,24 @@
"node": ">= 0.4"
}
},
+ "node_modules/eciesjs": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/eciesjs/-/eciesjs-0.5.0.tgz",
+ "integrity": "sha512-s0J9SEVYAEPg7J63GFMApLYzPH9VNIQIyC6s15JpnqVc0TqcKWdbgFlnAweEBRyMmko2dcs2sfC83Hj4J43tuA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@ecies/ciphers": "^0.2.6",
+ "@noble/ciphers": "^1.3.0",
+ "@noble/curves": "^1.9.7",
+ "@noble/hashes": "^1.8.0"
+ },
+ "engines": {
+ "bun": ">=1",
+ "deno": ">=2.7.10",
+ "node": ">=16"
+ }
+ },
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
@@ -11185,6 +11374,30 @@
"inline-style-parser": "0.2.7"
}
},
+ "node_modules/supabase": {
+ "version": "2.121.0",
+ "resolved": "https://registry.npmjs.org/supabase/-/supabase-2.121.0.tgz",
+ "integrity": "sha512-xffhOgD9rXsXLK+DQ+3Gq8b2KmavMjPHGuJr7lfVlD8vKK1HHFggYlmzdRECqPmOL8g3Yd5PN3URcUR8xWZcWw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "eciesjs": "^0.5.0",
+ "jose": "^6.2.10"
+ },
+ "bin": {
+ "supabase": "dist/supabase.js"
+ },
+ "optionalDependencies": {
+ "@supabase/cli-darwin-arm64": "2.121.0",
+ "@supabase/cli-darwin-x64": "2.121.0",
+ "@supabase/cli-linux-arm64": "2.121.0",
+ "@supabase/cli-linux-arm64-musl": "2.121.0",
+ "@supabase/cli-linux-x64": "2.121.0",
+ "@supabase/cli-linux-x64-musl": "2.121.0",
+ "@supabase/cli-windows-arm64": "2.121.0",
+ "@supabase/cli-windows-x64": "2.121.0"
+ }
+ },
"node_modules/supports-color": {
"version": "10.2.2",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",
diff --git a/package.json b/package.json
index ae81d5d..f23365f 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,11 @@
"lint": "eslint .",
"format": "prettier --write .",
"typecheck": "npm run typecheck --workspace backend && npm run typecheck --workspace frontend && npm run typecheck --workspace site && tsc -p scripts/tsconfig.json",
- "dev:site": "npm run dev --workspace site"
+ "dev:site": "npm run dev --workspace site",
+ "db:new": "supabase migration new",
+ "db:status": "supabase migration list",
+ "db:check": "supabase db push --dry-run",
+ "db:push": "supabase db push"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
@@ -28,6 +32,7 @@
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"prettier": "^3.9.9",
+ "supabase": "^2.121.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.71.2"
},
diff --git a/supabase/.gitignore b/supabase/.gitignore
new file mode 100644
index 0000000..ad9264f
--- /dev/null
+++ b/supabase/.gitignore
@@ -0,0 +1,8 @@
+# Supabase
+.branches
+.temp
+
+# dotenvx
+.env.keys
+.env.local
+.env.*.local
diff --git a/supabase/config.toml b/supabase/config.toml
new file mode 100644
index 0000000..b046e9b
--- /dev/null
+++ b/supabase/config.toml
@@ -0,0 +1,415 @@
+# For detailed configuration reference documentation, visit:
+# https://supabase.com/docs/guides/local-development/cli/config
+# A string used to distinguish different Supabase projects on the same host. Defaults to the
+# working directory name when running `supabase init`.
+project_id = "twiligent"
+
+[api]
+enabled = true
+# Port to use for the API URL.
+port = 54321
+# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API
+# endpoints. `public` and `graphql_public` schemas are included by default.
+schemas = ["public", "graphql_public"]
+# Extra schemas to add to the search_path of every request.
+extra_search_path = ["public", "extensions"]
+# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size
+# for accidental or malicious requests.
+max_rows = 1000
+# Controls whether new tables, views, sequences and functions created in the `public` schema by
+# `postgres` are reachable through the Data API roles (`anon`, `authenticated`, `service_role`)
+# without explicit GRANTs, matching the cloud default. Set to `false` to require explicit GRANTs
+# instead. Left unset, a fresh project falls back to `true`.
+# auto_expose_new_tables = true
+
+[api.tls]
+# Enable HTTPS endpoints locally using a self-signed certificate.
+enabled = false
+# Paths to self-signed certificate pair.
+# cert_path = "../certs/my-cert.pem"
+# key_path = "../certs/my-key.pem"
+
+[db]
+# Port to use for the local database URL.
+port = 54322
+# Port used by db diff command to initialize the shadow database.
+shadow_port = 54320
+# Maximum amount of time to wait for health check when starting the local database.
+health_timeout = "2m"
+# The database major version to use. This has to be the same as your remote database's. Run `SHOW
+# server_version;` on the remote database to check.
+major_version = 17
+# OrioleDB version to use as the Postgres storage engine. Leave empty to use the default engine.
+orioledb_version = ""
+
+[db.pooler]
+enabled = false
+# Port to use for the local connection pooler.
+port = 54329
+# Specifies when a server connection can be reused by other clients.
+# Configure one of the supported pooler modes: `transaction`, `session`.
+pool_mode = "transaction"
+# How many server connections to allow per user/database pair.
+default_pool_size = 20
+# Maximum number of client connections allowed.
+max_client_conn = 100
+
+# [db.vault]
+# secret_key = "env(SECRET_VALUE)"
+
+[db.migrations]
+# If disabled, migrations will be skipped during a db push or reset.
+enabled = true
+# Specifies an ordered list of schema files, directories, or glob patterns that describe your database.
+# Supports paths relative to supabase directory: "./schemas/*.sql", "./database".
+schema_paths = []
+
+[db.seed]
+# If enabled, seeds the database after migrations during a db reset.
+enabled = true
+# Specifies an ordered list of seed files to load during db reset.
+# Supports glob patterns relative to supabase directory: "./seeds/*.sql"
+sql_paths = ["./seed.sql"]
+
+[db.network_restrictions]
+# Enable management of network restrictions.
+enabled = false
+# List of IPv4 CIDR blocks allowed to connect to the database.
+# Defaults to allow all IPv4 connections. Set empty array to block all IPs.
+allowed_cidrs = ["0.0.0.0/0"]
+# List of IPv6 CIDR blocks allowed to connect to the database.
+# Defaults to allow all IPv6 connections. Set empty array to block all IPs.
+allowed_cidrs_v6 = ["::/0"]
+
+# Uncomment to reject non-secure connections to the database.
+# [db.ssl_enforcement]
+# enabled = true
+
+[realtime]
+enabled = true
+# Bind realtime via either IPv4 or IPv6. (default: IPv4)
+# ip_version = "IPv6"
+# The maximum length in bytes of HTTP request headers. (default: 4096)
+# max_header_length = 4096
+
+[studio]
+enabled = true
+# Port to use for Supabase Studio.
+port = 54323
+# External URL of the API server that frontend connects to.
+api_url = "http://127.0.0.1"
+# OpenAI API Key to use for Supabase AI in the Supabase Studio.
+openai_api_key = "env(OPENAI_API_KEY)"
+
+# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they
+# are monitored, and you can view the emails that would have been sent from the web interface.
+[local_smtp]
+enabled = true
+# Port to use for the email testing server web interface.
+port = 54324
+# Uncomment to expose additional ports for testing user applications that send emails.
+# smtp_port = 54325
+# pop3_port = 54326
+# admin_email = "[email protected]"
+# sender_name = "Admin"
+
+[storage]
+enabled = true
+# The maximum file size allowed (e.g. "5MB", "500KB").
+file_size_limit = "50MiB"
+
+# Uncomment to configure local storage buckets
+# [storage.buckets.images]
+# public = false
+# file_size_limit = "50MiB"
+# allowed_mime_types = ["image/png", "image/jpeg"]
+# objects_path = "./images"
+
+# Allow connections via S3 compatible clients
+[storage.s3_protocol]
+enabled = true
+
+# Image transformation API is available to Supabase Pro plan.
+# [storage.image_transformation]
+# enabled = true
+
+# Store analytical data in S3 for running ETL jobs over Iceberg Catalog
+# This feature is only available on the hosted platform.
+[storage.analytics]
+enabled = false
+max_namespaces = 5
+max_tables = 10
+max_catalogs = 2
+
+# Analytics Buckets is available to Supabase Pro plan.
+# [storage.analytics.buckets.my-warehouse]
+
+# Store vector embeddings in S3 for large and durable datasets
+[storage.vector]
+enabled = true
+max_buckets = 10
+max_indexes = 5
+
+# Vector Buckets is available to Supabase Pro plan.
+# [storage.vector.buckets.documents-openai]
+
+[auth]
+enabled = true
+# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used
+# in emails.
+site_url = "http://127.0.0.1:3000"
+# The public URL that Auth serves on. Defaults to the API external URL with `/auth/v1` appended.
+# external_url = ""
+# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
+additional_redirect_urls = ["https://127.0.0.1:3000"]
+# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
+jwt_expiry = 3600
+# JWT issuer URL. If not set, defaults to auth.external_url.
+# jwt_issuer = ""
+# Path to JWT signing key. DO NOT commit your signing keys file to git.
+# signing_keys_path = "./signing_keys.json"
+# If disabled, the refresh token will never expire.
+enable_refresh_token_rotation = true
+# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds.
+# Requires enable_refresh_token_rotation = true.
+refresh_token_reuse_interval = 10
+# Allow/disallow new user signups to your project.
+enable_signup = true
+# Allow/disallow anonymous sign-ins to your project.
+enable_anonymous_sign_ins = false
+# Allow/disallow testing manual linking of accounts
+enable_manual_linking = false
+# Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.
+minimum_password_length = 6
+# Passwords that do not meet the following requirements will be rejected as weak. Supported values
+# are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols`
+password_requirements = ""
+
+# Configure passkey sign-ins.
+# [auth.passkey]
+# enabled = false
+
+# Configure WebAuthn relying party settings (required when passkey is enabled).
+# [auth.webauthn]
+# rp_display_name = "Supabase"
+# rp_id = "localhost"
+# rp_origins = ["http://127.0.0.1:3000"]
+
+[auth.rate_limit]
+# Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled.
+email_sent = 2
+# Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled.
+sms_sent = 30
+# Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true.
+anonymous_users = 30
+# Number of sessions that can be refreshed in a 5 minute interval per IP address.
+token_refresh = 150
+# Number of sign up and sign-in requests that can be made in a 5 minute interval per IP address (excludes anonymous users).
+sign_in_sign_ups = 30
+# Number of OTP / Magic link verifications that can be made in a 5 minute interval per IP address.
+token_verifications = 30
+# Number of Web3 logins that can be made in a 5 minute interval per IP address.
+web3 = 30
+
+# Configure one of the supported captcha providers: `hcaptcha`, `turnstile`.
+# [auth.captcha]
+# enabled = true
+# provider = "hcaptcha"
+# secret = ""
+
+[auth.email]
+# Allow/disallow new user signups via email to your project.
+enable_signup = true
+# If enabled, a user will be required to confirm any email change on both the old, and new email
+# addresses. If disabled, only the new email is required to confirm.
+double_confirm_changes = true
+# If enabled, users need to confirm their email address before signing in.
+enable_confirmations = false
+# If enabled, users will need to reauthenticate or have logged in recently to change their password.
+secure_password_change = false
+# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.
+max_frequency = "1s"
+# Number of characters used in the email OTP.
+otp_length = 6
+# Number of seconds before the email OTP expires (defaults to 1 hour).
+otp_expiry = 3600
+
+# Use a production-ready SMTP server
+# [auth.email.smtp]
+# enabled = true
+# host = "smtp.sendgrid.net"
+# port = 587
+# user = "apikey"
+# pass = "env(SENDGRID_API_KEY)"
+# admin_email = "[email protected]"
+# sender_name = "Admin"
+
+# Uncomment to customize email template
+# [auth.email.template.invite]
+# subject = "You have been invited"
+# content_path = "./supabase/templates/invite.html"
+
+# Uncomment to customize notification email template
+# [auth.email.notification.password_changed]
+# enabled = true
+# subject = "Your password has been changed"
+# content_path = "./supabase/templates/password_changed_notification.html"
+
+[auth.sms]
+# Allow/disallow new user signups via SMS to your project.
+enable_signup = false
+# If enabled, users need to confirm their phone number before signing in.
+enable_confirmations = false
+# Template for sending OTP to users
+template = "Your code is {{ .Code }}"
+# Controls the minimum amount of time that must pass before sending another sms otp.
+max_frequency = "5s"
+
+# Use pre-defined map of phone number to OTP for testing.
+# [auth.sms.test_otp]
+# 4152127777 = "123456"
+
+# Configure logged in session timeouts.
+# [auth.sessions]
+# Force log out after the specified duration.
+# timebox = "24h"
+# Force log out if the user has been inactive longer than the specified duration.
+# inactivity_timeout = "8h"
+
+# This hook runs before a new user is created and allows developers to reject the request based on the incoming user object.
+# [auth.hook.before_user_created]
+# enabled = true
+# uri = "pg-functions://postgres/auth/before-user-created-hook"
+
+# This hook runs before a token is issued and allows you to add additional claims based on the authentication method used.
+# [auth.hook.custom_access_token]
+# enabled = true
+# uri = "pg-functions://<database>/<schema>/<hook_name>"
+
+# Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`.
+[auth.sms.twilio]
+enabled = false
+account_sid = ""
+message_service_sid = ""
+# DO NOT commit your Twilio auth token to git. Use environment variable substitution instead:
+auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)"
+
+# Multi-factor-authentication is available to Supabase Pro plan.
+[auth.mfa]
+# Control how many MFA factors can be enrolled at once per user.
+max_enrolled_factors = 10
+
+# Control MFA via App Authenticator (TOTP)
+[auth.mfa.totp]
+enroll_enabled = false
+verify_enabled = false
+
+# Configure MFA via Phone Messaging
+[auth.mfa.phone]
+enroll_enabled = false
+verify_enabled = false
+otp_length = 6
+template = "Your code is {{ .Code }}"
+max_frequency = "5s"
+
+# Configure MFA via WebAuthn
+# [auth.mfa.web_authn]
+# enroll_enabled = true
+# verify_enabled = true
+
+# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`,
+# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`,
+# `twitter`, `x`, `slack`, `spotify`, `workos`, `zoom`.
+[auth.external.apple]
+enabled = false
+client_id = ""
+# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead:
+secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)"
+# Overrides the default auth callback URL derived from auth.external_url.
+redirect_uri = ""
+# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure,
+# or any other third-party OIDC providers.
+url = ""
+# If enabled, the nonce check will be skipped. Required for local sign in with Google auth.
+skip_nonce_check = false
+# If enabled, it will allow the user to successfully authenticate when the provider does not return an email address.
+email_optional = false
+
+# Allow Solana wallet holders to sign in to your project via the Sign in with Solana (SIWS, EIP-4361) standard.
+# You can configure "web3" rate limit in the [auth.rate_limit] section and set up [auth.captcha] if self-hosting.
+[auth.web3.solana]
+enabled = false
+
+# Use Firebase Auth as a third-party provider alongside Supabase Auth.
+[auth.third_party.firebase]
+enabled = false
+# project_id = "my-firebase-project"
+
+# Use Auth0 as a third-party provider alongside Supabase Auth.
+[auth.third_party.auth0]
+enabled = false
+# tenant = "my-auth0-tenant"
+# tenant_region = "us"
+
+# Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth.
+[auth.third_party.aws_cognito]
+enabled = false
+# user_pool_id = "my-user-pool-id"
+# user_pool_region = "us-east-1"
+
+# Use Clerk as a third-party provider alongside Supabase Auth.
+[auth.third_party.clerk]
+enabled = false
+# Obtain from https://clerk.com/setup/supabase
+# domain = "example.clerk.accounts.dev"
+
+# OAuth server configuration
+[auth.oauth_server]
+# Enable OAuth server functionality
+enabled = false
+# Path for OAuth consent flow UI
+authorization_url_path = "/oauth/consent"
+# Allow dynamic client registration
+allow_dynamic_registration = false
+
+[edge_runtime]
+enabled = true
+# Supported request policies: `oneshot`, `per_worker`.
+# `per_worker` (default) enables hot reload during local development.
+# `oneshot` is the fallback mode if hot reload causes issues (e.g. in large repos or with symlinks).
+policy = "per_worker"
+# Port to attach the Chrome inspector for debugging edge functions.
+inspector_port = 8083
+# The Deno major version to use.
+deno_version = 2
+
+# [edge_runtime.secrets]
+# secret_key = "env(SECRET_VALUE)"
+
+[analytics]
+enabled = true
+port = 54327
+# Configure one of the supported backends: `postgres`, `bigquery`.
+backend = "postgres"
+
+# Experimental features may be deprecated any time
+[experimental]
+# Configures S3 bucket URL, eg. <bucket_name>.s3-<region>.amazonaws.com
+s3_host = "env(S3_HOST)"
+# Configures S3 bucket region, eg. us-east-1
+s3_region = "env(S3_REGION)"
+# Configures AWS_ACCESS_KEY_ID for S3 bucket
+s3_access_key = "env(S3_ACCESS_KEY)"
+# Configures AWS_SECRET_ACCESS_KEY for S3 bucket
+s3_secret_key = "env(S3_SECRET_KEY)"
+
+# pg-delta is the schema diff engine for db diff / db pull / db remote commit.
+# Set enabled = false to fall back to the legacy migra engine.
+[experimental.pgdelta]
+enabled = true
+# Directory under `supabase/` where declarative files are written.
+# declarative_schema_path = "./schemas"
+# JSON string passed through to pg-delta SQL formatting. When omitted, SQL is
+# formatted with uppercase keywords, indent 2, max width 180, trailing commas,
+# and column/key alignment. Set to "null" to emit raw, unformatted SQL.
+# format_options = "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":180,\"commaStyle\":\"trailing\"}"
diff --git a/supabase/migrations/20261016000000_baseline_accounts.sql b/supabase/migrations/20261016000000_baseline_accounts.sql
new file mode 100644
index 0000000..6d4fb46
--- /dev/null
+++ b/supabase/migrations/20261016000000_baseline_accounts.sql
@@ -0,0 +1,15 @@
+-- the accounts table before versioned migrations; safe to repeat on a database that already has it
+create table if not exists public.accounts (
+ id text primary key,
+ user_id uuid not null references auth.users (id) on delete cascade,
+ platform text not null,
+ data jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+-- older setup SQL had no created_at and allowed null data
+alter table public.accounts add column if not exists created_at timestamptz not null default now();
+update public.accounts set data = '{}'::jsonb where data is null;
+alter table public.accounts alter column data set default '{}'::jsonb, alter column data set not null;
+
+alter table public.accounts enable row level security;
diff --git a/supabase/migrations/20261016000100_baseline_settings.sql b/supabase/migrations/20261016000100_baseline_settings.sql
new file mode 100644
index 0000000..c4fbb58
--- /dev/null
+++ b/supabase/migrations/20261016000100_baseline_settings.sql
@@ -0,0 +1,15 @@
+-- the settings table before versioned migrations; safe to repeat on a database that already has it
+create table if not exists public.settings (
+ user_id uuid not null references auth.users (id) on delete cascade,
+ key text not null,
+ value jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now(),
+ primary key (user_id, key)
+);
+
+-- older setup SQL had no created_at and allowed a null value
+alter table public.settings add column if not exists created_at timestamptz not null default now();
+update public.settings set value = '{}'::jsonb where value is null;
+alter table public.settings alter column value set default '{}'::jsonb, alter column value set not null;
+
+alter table public.settings enable row level security;
diff --git a/supabase/migrations/20261016000200_baseline_scheduled_posts.sql b/supabase/migrations/20261016000200_baseline_scheduled_posts.sql
new file mode 100644
index 0000000..6b4d776
--- /dev/null
+++ b/supabase/migrations/20261016000200_baseline_scheduled_posts.sql
@@ -0,0 +1,31 @@
+-- the scheduled_posts table before versioned migrations; safe to repeat on a database that already has it
+create table if not exists public.scheduled_posts (
+ id text primary key,
+ user_id uuid not null references auth.users (id) on delete cascade,
+ account_id text not null,
+ status text not null default 'pending',
+ scheduled_at timestamptz not null,
+ data jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now(),
+ claimed_at timestamptz,
+ attempts integer not null default 0
+);
+
+-- older setup SQL had no created_at, no claim columns and allowed null data
+alter table public.scheduled_posts
+ add column if not exists created_at timestamptz not null default now(),
+ add column if not exists claimed_at timestamptz,
+ add column if not exists attempts integer not null default 0;
+update public.scheduled_posts set data = '{}'::jsonb where data is null;
+alter table public.scheduled_posts alter column data set default '{}'::jsonb, alter column data set not null;
+
+-- posts stuck in publishing before the claim lease have no saved container, so nothing can tell whether they went out
+update public.scheduled_posts
+set status = 'failed',
+ data = data || jsonb_build_object('error', 'Publishing was interrupted before Twiligent tracked it. Check Instagram before scheduling this post again.')
+where status = 'publishing' and claimed_at is null;
+
+create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);
+create index if not exists scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);
+
+alter table public.scheduled_posts enable row level security;
diff --git a/supabase/migrations/20261016000300_baseline_tracked_posts.sql b/supabase/migrations/20261016000300_baseline_tracked_posts.sql
new file mode 100644
index 0000000..688fd22
--- /dev/null
+++ b/supabase/migrations/20261016000300_baseline_tracked_posts.sql
@@ -0,0 +1,20 @@
+-- the tracked_posts table before versioned migrations; safe to repeat on a database that already has it
+create table if not exists public.tracked_posts (
+ id text primary key,
+ user_id uuid not null references auth.users (id) on delete cascade,
+ account_id text references public.accounts (id) on delete set null,
+ url text not null,
+ label text not null default '',
+ category text not null default '',
+ content_type text not null default 'reddit',
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ data jsonb
+);
+
+-- the first version of the table had no content_type
+alter table public.tracked_posts add column if not exists content_type text not null default 'reddit';
+
+create index if not exists tracked_posts_user_id_idx on public.tracked_posts (user_id);
+
+alter table public.tracked_posts enable row level security;
diff --git a/supabase/migrations/20261016000400_revoke_browser_access_accounts.sql b/supabase/migrations/20261016000400_revoke_browser_access_accounts.sql
new file mode 100644
index 0000000..e7a7bc9
--- /dev/null
+++ b/supabase/migrations/20261016000400_revoke_browser_access_accounts.sql
@@ -0,0 +1,3 @@
+-- only the Worker's service role reads accounts; the anon key ships in every browser, so browser roles get nothing
+drop policy if exists users_own_accounts on public.accounts;
+revoke all on table public.accounts from anon, authenticated;
diff --git a/supabase/migrations/20261016000500_revoke_browser_access_settings.sql b/supabase/migrations/20261016000500_revoke_browser_access_settings.sql
new file mode 100644
index 0000000..eb445cc
--- /dev/null
+++ b/supabase/migrations/20261016000500_revoke_browser_access_settings.sql
@@ -0,0 +1,3 @@
+-- only the Worker's service role reads settings; the anon key ships in every browser, so browser roles get nothing
+drop policy if exists users_own_settings on public.settings;
+revoke all on table public.settings from anon, authenticated;
diff --git a/supabase/migrations/20261016000600_revoke_browser_access_scheduled_posts.sql b/supabase/migrations/20261016000600_revoke_browser_access_scheduled_posts.sql
new file mode 100644
index 0000000..bae2fb2
--- /dev/null
+++ b/supabase/migrations/20261016000600_revoke_browser_access_scheduled_posts.sql
@@ -0,0 +1,3 @@
+-- only the Worker's service role reads scheduled_posts; the anon key ships in every browser, so browser roles get nothing
+drop policy if exists users_own_posts on public.scheduled_posts;
+revoke all on table public.scheduled_posts from anon, authenticated;
diff --git a/supabase/migrations/20261016000700_revoke_browser_access_tracked_posts.sql b/supabase/migrations/20261016000700_revoke_browser_access_tracked_posts.sql
new file mode 100644
index 0000000..091cd58
--- /dev/null
+++ b/supabase/migrations/20261016000700_revoke_browser_access_tracked_posts.sql
@@ -0,0 +1,2 @@
+-- only the Worker's service role reads tracked_posts; the anon key ships in every browser, so browser roles get nothing
+revoke all on table public.tracked_posts from anon, authenticated;
diff --git a/supabase/migrations/20261016000800_revoke_browser_default_privileges.sql b/supabase/migrations/20261016000800_revoke_browser_default_privileges.sql
new file mode 100644
index 0000000..a827fb7
--- /dev/null
+++ b/supabase/migrations/20261016000800_revoke_browser_default_privileges.sql
@@ -0,0 +1,3 @@
+-- Supabase grants new tables and functions in public to the browser roles; later migrations start without that
+alter default privileges for role postgres in schema public revoke all on tables from anon, authenticated;
+alter default privileges for role postgres in schema public revoke all on functions from anon, authenticated;
diff --git a/supabase/migrations/20261016000900_check_accounts_values.sql b/supabase/migrations/20261016000900_check_accounts_values.sql
new file mode 100644
index 0000000..fcdf4a7
--- /dev/null
+++ b/supabase/migrations/20261016000900_check_accounts_values.sql
@@ -0,0 +1,4 @@
+-- an unknown platform or a data value that is not an object fails at the write instead of breaking a later read
+alter table public.accounts
+ add constraint accounts_platform_check check (platform in ('youtube', 'instagram', 'reddit')),
+ add constraint accounts_data_check check (jsonb_typeof(data) = 'object');
diff --git a/supabase/migrations/20261016001000_check_settings_values.sql b/supabase/migrations/20261016001000_check_settings_values.sql
new file mode 100644
index 0000000..ae1d525
--- /dev/null
+++ b/supabase/migrations/20261016001000_check_settings_values.sql
@@ -0,0 +1,3 @@
+-- every setting is stored as an object of named values
+alter table public.settings
+ add constraint settings_value_check check (jsonb_typeof(value) = 'object');
diff --git a/supabase/migrations/20261016001100_check_scheduled_posts_values.sql b/supabase/migrations/20261016001100_check_scheduled_posts_values.sql
new file mode 100644
index 0000000..74b3ad3
--- /dev/null
+++ b/supabase/migrations/20261016001100_check_scheduled_posts_values.sql
@@ -0,0 +1,7 @@
+-- the four statuses of the publishing lifecycle; anything else is a bug and fails at the write
+alter table public.scheduled_posts
+ add constraint scheduled_posts_status_check check (status in ('pending', 'publishing', 'published', 'failed')),
+ add constraint scheduled_posts_attempts_check check (attempts >= 0),
+ -- the lease is measured from the claim, so a post being published must carry one
+ add constraint scheduled_posts_claim_check check (status <> 'publishing' or claimed_at is not null),
+ add constraint scheduled_posts_data_check check (jsonb_typeof(data) = 'object');
diff --git a/supabase/migrations/20261016001200_check_tracked_posts_values.sql b/supabase/migrations/20261016001200_check_tracked_posts_values.sql
new file mode 100644
index 0000000..2689c2a
--- /dev/null
+++ b/supabase/migrations/20261016001200_check_tracked_posts_values.sql
@@ -0,0 +1,6 @@
+-- tracked items are Reddit posts or YouTube videos
+alter table public.tracked_posts
+ add constraint tracked_posts_content_type_check check (content_type in ('reddit', 'youtube')),
+ -- only Reddit items read through an account, for its cookie
+ add constraint tracked_posts_account_check check (content_type = 'reddit' or account_id is null),
+ add constraint tracked_posts_data_check check (data is null or jsonb_typeof(data) = 'object');
diff --git a/supabase/migrations/20261016001300_add_accounts_id_user_id_key.sql b/supabase/migrations/20261016001300_add_accounts_id_user_id_key.sql
new file mode 100644
index 0000000..a631192
--- /dev/null
+++ b/supabase/migrations/20261016001300_add_accounts_id_user_id_key.sql
@@ -0,0 +1,2 @@
+-- id alone is unique, so (id, user_id) is too; naming the pair lets a post reference an account with its owner
+alter table public.accounts add constraint accounts_id_user_id_key unique (id, user_id);
diff --git a/supabase/migrations/20261016001400_add_scheduled_posts_account_fkey.sql b/supabase/migrations/20261016001400_add_scheduled_posts_account_fkey.sql
new file mode 100644
index 0000000..409aaa1
--- /dev/null
+++ b/supabase/migrations/20261016001400_add_scheduled_posts_account_fkey.sql
@@ -0,0 +1,5 @@
+-- a scheduled post can only name an account of the same user, and goes with that account when it is removed
+alter table public.scheduled_posts drop constraint if exists scheduled_posts_account_id_fkey;
+alter table public.scheduled_posts
+ add constraint scheduled_posts_account_fkey foreign key (account_id, user_id)
+ references public.accounts (id, user_id) on delete cascade;
diff --git a/supabase/migrations/20261016001500_add_tracked_posts_account_fkey.sql b/supabase/migrations/20261016001500_add_tracked_posts_account_fkey.sql
new file mode 100644
index 0000000..1e428ec
--- /dev/null
+++ b/supabase/migrations/20261016001500_add_tracked_posts_account_fkey.sql
@@ -0,0 +1,5 @@
+-- a tracked item can only read through the same user's account; removing the account keeps the item without one
+alter table public.tracked_posts drop constraint if exists tracked_posts_account_id_fkey;
+alter table public.tracked_posts
+ add constraint tracked_posts_account_fkey foreign key (account_id, user_id)
+ references public.accounts (id, user_id) on delete set null (account_id);
diff --git a/supabase/migrations/20261016001600_create_set_updated_at_function.sql b/supabase/migrations/20261016001600_create_set_updated_at_function.sql
new file mode 100644
index 0000000..0ac5000
--- /dev/null
+++ b/supabase/migrations/20261016001600_create_set_updated_at_function.sql
@@ -0,0 +1,13 @@
+-- one trigger function keeps updated_at on every table, so no query has to remember to set it
+create or replace function public.set_updated_at()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ new.updated_at := now();
+ return new;
+end;
+$$;
+
+revoke execute on function public.set_updated_at() from public, anon, authenticated;
diff --git a/supabase/migrations/20261016001700_add_accounts_updated_at.sql b/supabase/migrations/20261016001700_add_accounts_updated_at.sql
new file mode 100644
index 0000000..725c7fa
--- /dev/null
+++ b/supabase/migrations/20261016001700_add_accounts_updated_at.sql
@@ -0,0 +1,7 @@
+alter table public.accounts add column if not exists updated_at timestamptz not null default now();
+
+-- existing rows were last changed at an unknown time; their creation time is the closest honest value
+update public.accounts set updated_at = created_at;
+
+create trigger accounts_set_updated_at before update on public.accounts
+ for each row execute function public.set_updated_at();
diff --git a/supabase/migrations/20261016001800_add_settings_updated_at.sql b/supabase/migrations/20261016001800_add_settings_updated_at.sql
new file mode 100644
index 0000000..121afa1
--- /dev/null
+++ b/supabase/migrations/20261016001800_add_settings_updated_at.sql
@@ -0,0 +1,7 @@
+alter table public.settings add column if not exists updated_at timestamptz not null default now();
+
+-- existing rows were last changed at an unknown time; their creation time is the closest honest value
+update public.settings set updated_at = created_at;
+
+create trigger settings_set_updated_at before update on public.settings
+ for each row execute function public.set_updated_at();
diff --git a/supabase/migrations/20261016001900_add_scheduled_posts_updated_at.sql b/supabase/migrations/20261016001900_add_scheduled_posts_updated_at.sql
new file mode 100644
index 0000000..7d1ec85
--- /dev/null
+++ b/supabase/migrations/20261016001900_add_scheduled_posts_updated_at.sql
@@ -0,0 +1,7 @@
+alter table public.scheduled_posts add column if not exists updated_at timestamptz not null default now();
+
+-- existing rows were last changed at an unknown time; their creation time is the closest honest value
+update public.scheduled_posts set updated_at = created_at;
+
+create trigger scheduled_posts_set_updated_at before update on public.scheduled_posts
+ for each row execute function public.set_updated_at();
diff --git a/supabase/migrations/20261016002000_add_tracked_posts_updated_at_trigger.sql b/supabase/migrations/20261016002000_add_tracked_posts_updated_at_trigger.sql
new file mode 100644
index 0000000..17b691e
--- /dev/null
+++ b/supabase/migrations/20261016002000_add_tracked_posts_updated_at_trigger.sql
@@ -0,0 +1,3 @@
+-- tracked_posts already had updated_at, set by the repository; the trigger takes that job over
+create trigger tracked_posts_set_updated_at before update on public.tracked_posts
+ for each row execute function public.set_updated_at();
diff --git a/supabase/migrations/20261016002100_create_merge_account_data_function.sql b/supabase/migrations/20261016002100_create_merge_account_data_function.sql
new file mode 100644
index 0000000..8cf9a0f
--- /dev/null
+++ b/supabase/migrations/20261016002100_create_merge_account_data_function.sql
@@ -0,0 +1,15 @@
+-- merges a patch into data in one UPDATE, so two writers never undo each other; a null p_user_id is the cron form
+create or replace function public.merge_account_data(p_id text, p_user_id uuid, p_patch jsonb)
+returns boolean
+language sql
+set search_path = ''
+as $$
+ update public.accounts
+ set data = data || p_patch
+ where id = p_id and (p_user_id is null or user_id = p_user_id)
+ returning true;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.merge_account_data(text, uuid, jsonb) from public, anon, authenticated;
+grant execute on function public.merge_account_data(text, uuid, jsonb) to service_role;
diff --git a/supabase/migrations/20261016002200_create_merge_scheduled_post_function.sql b/supabase/migrations/20261016002200_create_merge_scheduled_post_function.sql
new file mode 100644
index 0000000..ca64d06
--- /dev/null
+++ b/supabase/migrations/20261016002200_create_merge_scheduled_post_function.sql
@@ -0,0 +1,26 @@
+-- one UPDATE for status, time and a data patch; p_only_status keeps an edit off a post a scheduler has just claimed
+create or replace function public.merge_scheduled_post(
+ p_id text,
+ p_user_id uuid,
+ p_patch jsonb,
+ p_status text default null,
+ p_scheduled_at timestamptz default null,
+ p_only_status text default null
+)
+returns boolean
+language sql
+set search_path = ''
+as $$
+ update public.scheduled_posts
+ set data = data || p_patch,
+ status = coalesce(p_status, status),
+ scheduled_at = coalesce(p_scheduled_at, scheduled_at)
+ where id = p_id
+ and (p_user_id is null or user_id = p_user_id)
+ and (p_only_status is null or status = p_only_status)
+ returning true;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.merge_scheduled_post(text, uuid, jsonb, text, timestamptz, text) from public, anon, authenticated;
+grant execute on function public.merge_scheduled_post(text, uuid, jsonb, text, timestamptz, text) to service_role;
diff --git a/supabase/migrations/20261016002300_create_merge_tracked_post_data_function.sql b/supabase/migrations/20261016002300_create_merge_tracked_post_data_function.sql
new file mode 100644
index 0000000..1750dfb
--- /dev/null
+++ b/supabase/migrations/20261016002300_create_merge_tracked_post_data_function.sql
@@ -0,0 +1,15 @@
+-- merges a patch into data in one UPDATE, so a manual view count and a refresh at the same moment both survive
+create or replace function public.merge_tracked_post_data(p_id text, p_user_id uuid, p_patch jsonb)
+returns boolean
+language sql
+set search_path = ''
+as $$
+ update public.tracked_posts
+ set data = coalesce(data, '{}'::jsonb) || p_patch
+ where id = p_id and user_id = p_user_id
+ returning true;
+$$;
+
+-- functions in public are exposed through the Data API, so only the service role may call it
+revoke execute on function public.merge_tracked_post_data(text, uuid, jsonb) from public, anon, authenticated;
+grant execute on function public.merge_tracked_post_data(text, uuid, jsonb) to service_role;
diff --git a/supabase/migrations/20261016002400_index_accounts_list.sql b/supabase/migrations/20261016002400_index_accounts_list.sql
new file mode 100644
index 0000000..e1d7447
--- /dev/null
+++ b/supabase/migrations/20261016002400_index_accounts_list.sql
@@ -0,0 +1,2 @@
+-- accounts.listForUser: where user_id = $1 order by created_at, id
+create index if not exists accounts_user_id_created_at_idx on public.accounts (user_id, created_at, id);
diff --git a/supabase/migrations/20261016002500_index_scheduled_posts_list.sql b/supabase/migrations/20261016002500_index_scheduled_posts_list.sql
new file mode 100644
index 0000000..439b5ed
--- /dev/null
+++ b/supabase/migrations/20261016002500_index_scheduled_posts_list.sql
@@ -0,0 +1,3 @@
+-- scheduledPosts.listForUser: where user_id = $1 order by scheduled_at; the counts behind delete all use it too
+create index if not exists scheduled_posts_user_id_scheduled_at_idx on public.scheduled_posts (user_id, scheduled_at);
+drop index if exists public.scheduled_posts_user_id_idx;
diff --git a/supabase/migrations/20261016002600_index_scheduled_posts_schedulers.sql b/supabase/migrations/20261016002600_index_scheduled_posts_schedulers.sql
new file mode 100644
index 0000000..72dffd2
--- /dev/null
+++ b/supabase/migrations/20261016002600_index_scheduled_posts_schedulers.sql
@@ -0,0 +1,4 @@
+-- the schedulers only read pending and publishing posts, so partial indexes leave out the growing published history
+drop index if exists public.scheduled_posts_due_idx;
+create index scheduled_posts_due_idx on public.scheduled_posts (scheduled_at) where status = 'pending';
+create index if not exists scheduled_posts_claimed_idx on public.scheduled_posts (claimed_at) where status = 'publishing';
diff --git a/supabase/migrations/20261016002700_index_tracked_posts_list.sql b/supabase/migrations/20261016002700_index_tracked_posts_list.sql
new file mode 100644
index 0000000..feae405
--- /dev/null
+++ b/supabase/migrations/20261016002700_index_tracked_posts_list.sql
@@ -0,0 +1,3 @@
+-- trackedPosts.listForUser: where user_id = $1 order by created_at desc
+create index if not exists tracked_posts_user_id_created_at_idx on public.tracked_posts (user_id, created_at desc);
+drop index if exists public.tracked_posts_user_id_idx;
diff --git a/supabase/rollbacks/20261016000400_revoke_browser_access_accounts.sql b/supabase/rollbacks/20261016000400_revoke_browser_access_accounts.sql
new file mode 100644
index 0000000..cf2ac73
--- /dev/null
+++ b/supabase/rollbacks/20261016000400_revoke_browser_access_accounts.sql
@@ -0,0 +1,3 @@
+-- restores the browser access accounts had before; only for returning to that state
+grant all on table public.accounts to anon, authenticated;
+create policy users_own_accounts on public.accounts for all using (auth.uid() = user_id) with check (auth.uid() = user_id);
diff --git a/supabase/rollbacks/20261016000500_revoke_browser_access_settings.sql b/supabase/rollbacks/20261016000500_revoke_browser_access_settings.sql
new file mode 100644
index 0000000..3cd37af
--- /dev/null
+++ b/supabase/rollbacks/20261016000500_revoke_browser_access_settings.sql
@@ -0,0 +1,3 @@
+-- restores the browser access settings had before; only for returning to that state
+grant all on table public.settings to anon, authenticated;
+create policy users_own_settings on public.settings for all using (auth.uid() = user_id) with check (auth.uid() = user_id);
diff --git a/supabase/rollbacks/20261016000600_revoke_browser_access_scheduled_posts.sql b/supabase/rollbacks/20261016000600_revoke_browser_access_scheduled_posts.sql
new file mode 100644
index 0000000..364292d
--- /dev/null
+++ b/supabase/rollbacks/20261016000600_revoke_browser_access_scheduled_posts.sql
@@ -0,0 +1,3 @@
+-- restores the browser access scheduled_posts had before; only for returning to that state
+grant all on table public.scheduled_posts to anon, authenticated;
+create policy users_own_posts on public.scheduled_posts for all using (auth.uid() = user_id) with check (auth.uid() = user_id);
diff --git a/supabase/rollbacks/20261016000700_revoke_browser_access_tracked_posts.sql b/supabase/rollbacks/20261016000700_revoke_browser_access_tracked_posts.sql
new file mode 100644
index 0000000..c3ef763
--- /dev/null
+++ b/supabase/rollbacks/20261016000700_revoke_browser_access_tracked_posts.sql
@@ -0,0 +1,2 @@
+-- restores the browser access tracked_posts had before; only for returning to that state
+grant all on table public.tracked_posts to anon, authenticated;
diff --git a/supabase/rollbacks/20261016000800_revoke_browser_default_privileges.sql b/supabase/rollbacks/20261016000800_revoke_browser_default_privileges.sql
new file mode 100644
index 0000000..d2f3297
--- /dev/null
+++ b/supabase/rollbacks/20261016000800_revoke_browser_default_privileges.sql
@@ -0,0 +1,2 @@
+alter default privileges for role postgres in schema public grant all on functions to anon, authenticated;
+alter default privileges for role postgres in schema public grant all on tables to anon, authenticated;
diff --git a/supabase/rollbacks/20261016000900_check_accounts_values.sql b/supabase/rollbacks/20261016000900_check_accounts_values.sql
new file mode 100644
index 0000000..becca94
--- /dev/null
+++ b/supabase/rollbacks/20261016000900_check_accounts_values.sql
@@ -0,0 +1,3 @@
+alter table public.accounts
+ drop constraint if exists accounts_data_check,
+ drop constraint if exists accounts_platform_check;
diff --git a/supabase/rollbacks/20261016001000_check_settings_values.sql b/supabase/rollbacks/20261016001000_check_settings_values.sql
new file mode 100644
index 0000000..433ad65
--- /dev/null
+++ b/supabase/rollbacks/20261016001000_check_settings_values.sql
@@ -0,0 +1 @@
+alter table public.settings drop constraint if exists settings_value_check;
diff --git a/supabase/rollbacks/20261016001100_check_scheduled_posts_values.sql b/supabase/rollbacks/20261016001100_check_scheduled_posts_values.sql
new file mode 100644
index 0000000..615ec2c
--- /dev/null
+++ b/supabase/rollbacks/20261016001100_check_scheduled_posts_values.sql
@@ -0,0 +1,5 @@
+alter table public.scheduled_posts
+ drop constraint if exists scheduled_posts_data_check,
+ drop constraint if exists scheduled_posts_claim_check,
+ drop constraint if exists scheduled_posts_attempts_check,
+ drop constraint if exists scheduled_posts_status_check;
diff --git a/supabase/rollbacks/20261016001200_check_tracked_posts_values.sql b/supabase/rollbacks/20261016001200_check_tracked_posts_values.sql
new file mode 100644
index 0000000..6193967
--- /dev/null
+++ b/supabase/rollbacks/20261016001200_check_tracked_posts_values.sql
@@ -0,0 +1,4 @@
+alter table public.tracked_posts
+ drop constraint if exists tracked_posts_data_check,
+ drop constraint if exists tracked_posts_account_check,
+ drop constraint if exists tracked_posts_content_type_check;
diff --git a/supabase/rollbacks/20261016001300_add_accounts_id_user_id_key.sql b/supabase/rollbacks/20261016001300_add_accounts_id_user_id_key.sql
new file mode 100644
index 0000000..d12a87a
--- /dev/null
+++ b/supabase/rollbacks/20261016001300_add_accounts_id_user_id_key.sql
@@ -0,0 +1 @@
+alter table public.accounts drop constraint if exists accounts_id_user_id_key;
diff --git a/supabase/rollbacks/20261016001400_add_scheduled_posts_account_fkey.sql b/supabase/rollbacks/20261016001400_add_scheduled_posts_account_fkey.sql
new file mode 100644
index 0000000..66711dd
--- /dev/null
+++ b/supabase/rollbacks/20261016001400_add_scheduled_posts_account_fkey.sql
@@ -0,0 +1,2 @@
+-- production had no foreign key here before the migration
+alter table public.scheduled_posts drop constraint if exists scheduled_posts_account_fkey;
diff --git a/supabase/rollbacks/20261016001500_add_tracked_posts_account_fkey.sql b/supabase/rollbacks/20261016001500_add_tracked_posts_account_fkey.sql
new file mode 100644
index 0000000..44ffbce
--- /dev/null
+++ b/supabase/rollbacks/20261016001500_add_tracked_posts_account_fkey.sql
@@ -0,0 +1,4 @@
+alter table public.tracked_posts drop constraint if exists tracked_posts_account_fkey;
+alter table public.tracked_posts
+ add constraint tracked_posts_account_id_fkey foreign key (account_id)
+ references public.accounts (id) on delete set null;
diff --git a/supabase/rollbacks/20261016001600_create_set_updated_at_function.sql b/supabase/rollbacks/20261016001600_create_set_updated_at_function.sql
new file mode 100644
index 0000000..9271627
--- /dev/null
+++ b/supabase/rollbacks/20261016001600_create_set_updated_at_function.sql
@@ -0,0 +1 @@
+drop function if exists public.set_updated_at();
diff --git a/supabase/rollbacks/20261016001700_add_accounts_updated_at.sql b/supabase/rollbacks/20261016001700_add_accounts_updated_at.sql
new file mode 100644
index 0000000..e9756e1
--- /dev/null
+++ b/supabase/rollbacks/20261016001700_add_accounts_updated_at.sql
@@ -0,0 +1,2 @@
+drop trigger if exists accounts_set_updated_at on public.accounts;
+alter table public.accounts drop column if exists updated_at;
diff --git a/supabase/rollbacks/20261016001800_add_settings_updated_at.sql b/supabase/rollbacks/20261016001800_add_settings_updated_at.sql
new file mode 100644
index 0000000..7263805
--- /dev/null
+++ b/supabase/rollbacks/20261016001800_add_settings_updated_at.sql
@@ -0,0 +1,2 @@
+drop trigger if exists settings_set_updated_at on public.settings;
+alter table public.settings drop column if exists updated_at;
diff --git a/supabase/rollbacks/20261016001900_add_scheduled_posts_updated_at.sql b/supabase/rollbacks/20261016001900_add_scheduled_posts_updated_at.sql
new file mode 100644
index 0000000..d1cda3a
--- /dev/null
+++ b/supabase/rollbacks/20261016001900_add_scheduled_posts_updated_at.sql
@@ -0,0 +1,2 @@
+drop trigger if exists scheduled_posts_set_updated_at on public.scheduled_posts;
+alter table public.scheduled_posts drop column if exists updated_at;
diff --git a/supabase/rollbacks/20261016002000_add_tracked_posts_updated_at_trigger.sql b/supabase/rollbacks/20261016002000_add_tracked_posts_updated_at_trigger.sql
new file mode 100644
index 0000000..264f646
--- /dev/null
+++ b/supabase/rollbacks/20261016002000_add_tracked_posts_updated_at_trigger.sql
@@ -0,0 +1 @@
+drop trigger if exists tracked_posts_set_updated_at on public.tracked_posts;
diff --git a/supabase/rollbacks/20261016002100_create_merge_account_data_function.sql b/supabase/rollbacks/20261016002100_create_merge_account_data_function.sql
new file mode 100644
index 0000000..2bcf45c
--- /dev/null
+++ b/supabase/rollbacks/20261016002100_create_merge_account_data_function.sql
@@ -0,0 +1,2 @@
+-- deploy the code that reads data before writing it again first, or its writes will fail
+drop function if exists public.merge_account_data(text, uuid, jsonb);
diff --git a/supabase/rollbacks/20261016002200_create_merge_scheduled_post_function.sql b/supabase/rollbacks/20261016002200_create_merge_scheduled_post_function.sql
new file mode 100644
index 0000000..7674465
--- /dev/null
+++ b/supabase/rollbacks/20261016002200_create_merge_scheduled_post_function.sql
@@ -0,0 +1,2 @@
+-- deploy the code that reads data before writing it again first, or its writes will fail
+drop function if exists public.merge_scheduled_post(text, uuid, jsonb, text, timestamptz, text);
diff --git a/supabase/rollbacks/20261016002300_create_merge_tracked_post_data_function.sql b/supabase/rollbacks/20261016002300_create_merge_tracked_post_data_function.sql
new file mode 100644
index 0000000..e05a844
--- /dev/null
+++ b/supabase/rollbacks/20261016002300_create_merge_tracked_post_data_function.sql
@@ -0,0 +1,2 @@
+-- deploy the code that reads data before writing it again first, or its writes will fail
+drop function if exists public.merge_tracked_post_data(text, uuid, jsonb);
diff --git a/supabase/rollbacks/20261016002400_index_accounts_list.sql b/supabase/rollbacks/20261016002400_index_accounts_list.sql
new file mode 100644
index 0000000..c67221f
--- /dev/null
+++ b/supabase/rollbacks/20261016002400_index_accounts_list.sql
@@ -0,0 +1 @@
+drop index if exists public.accounts_user_id_created_at_idx;
diff --git a/supabase/rollbacks/20261016002500_index_scheduled_posts_list.sql b/supabase/rollbacks/20261016002500_index_scheduled_posts_list.sql
new file mode 100644
index 0000000..6d60c6d
--- /dev/null
+++ b/supabase/rollbacks/20261016002500_index_scheduled_posts_list.sql
@@ -0,0 +1,2 @@
+create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);
+drop index if exists public.scheduled_posts_user_id_scheduled_at_idx;
diff --git a/supabase/rollbacks/20261016002600_index_scheduled_posts_schedulers.sql b/supabase/rollbacks/20261016002600_index_scheduled_posts_schedulers.sql
new file mode 100644
index 0000000..b3c4568
--- /dev/null
+++ b/supabase/rollbacks/20261016002600_index_scheduled_posts_schedulers.sql
@@ -0,0 +1,3 @@
+drop index if exists public.scheduled_posts_claimed_idx;
+drop index if exists public.scheduled_posts_due_idx;
+create index scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);
diff --git a/supabase/rollbacks/20261016002700_index_tracked_posts_list.sql b/supabase/rollbacks/20261016002700_index_tracked_posts_list.sql
new file mode 100644
index 0000000..f351eb0
--- /dev/null
+++ b/supabase/rollbacks/20261016002700_index_tracked_posts_list.sql
@@ -0,0 +1,2 @@
+create index if not exists tracked_posts_user_id_idx on public.tracked_posts (user_id);
+drop index if exists public.tracked_posts_user_id_created_at_idx;