Add local Supabase backend foundation: schema, RLS, and RLS tests
- supabase/config.toml: local dev stack config, pinned to the app's fixed dev server port, email confirmation required (hard verification gate per organized-ideas.md). - Initial schema migration: profiles/roles, the public/private catalog tables (manufacturers, device categories, port types, cable types, device templates + ports) with the shared is_public/owner_id RLS pattern, a generalized catalog_submissions review-queue table, and diagrams as JSONB documents (+ collaborators, snapshots) rather than fully normalized -- see the migration's header comment for why. - pgTAP RLS test suite (23 assertions) covering catalog visibility and promotion-in-place, diagram owner/collaborator/admin/super-admin visibility and edit permissions, submission visibility, and role escalation. Caught and fixed a real infinite-recursion bug between the diagrams and diagram_collaborators policies before this ever touched real data. - vite.config.ts: pinned dev server port so Supabase Auth's redirect allow-list doesn't silently break if Vite floats to another port. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017DUU6CnxECCDeqDNYJgr5x
This commit is contained in:
@@ -0,0 +1,8 @@
|
|||||||
|
# Supabase
|
||||||
|
.branches
|
||||||
|
.temp
|
||||||
|
|
||||||
|
# dotenvx
|
||||||
|
.env.keys
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
@@ -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 = "av-planner"
|
||||||
|
|
||||||
|
[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
|
||||||
|
|
||||||
|
[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 = "admin@email.com"
|
||||||
|
# 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:5173"
|
||||||
|
# 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 = ["http://127.0.0.1:5173"]
|
||||||
|
# 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.
|
||||||
|
# Enabled per organized-ideas.md §2: email verification is a hard gate before
|
||||||
|
# first use for manual signups (Google-SSO users are implicitly verified).
|
||||||
|
enable_confirmations = true
|
||||||
|
# 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 = "admin@email.com"
|
||||||
|
# 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` — 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 Postgres storage engine to use OrioleDB (S3)
|
||||||
|
orioledb_version = ""
|
||||||
|
# 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.
|
||||||
|
# format_options = "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":80,\"commaStyle\":\"trailing\"}"
|
||||||
@@ -0,0 +1,519 @@
|
|||||||
|
-- Initial schema for AV Planner's backend, per organized-ideas.md.
|
||||||
|
--
|
||||||
|
-- Two different shapes on purpose:
|
||||||
|
-- * Catalog entities (manufacturers, categories, port types, cable types,
|
||||||
|
-- device templates) are fully relational rows, because they must be
|
||||||
|
-- independently browsable, searchable, and moderated one row at a time
|
||||||
|
-- (the public/private + submission-for-review workflow).
|
||||||
|
-- * Diagrams are a JSONB document per row. A diagram's devices/ports/
|
||||||
|
-- connections already carry copied-in data rather than live references
|
||||||
|
-- (the "snapshot at time of use" decision), so they're inherently
|
||||||
|
-- document-shaped, not relational — and RLS only ever needs to gate
|
||||||
|
-- access at the whole-diagram level (owner + collaborators), never at
|
||||||
|
-- the level of one device or cable inside it, so normalizing would add
|
||||||
|
-- complexity without adding any real security granularity.
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- profiles — one row per auth.users row. Username is separate from email
|
||||||
|
-- (organized-ideas.md §2) and unique. Account suspension uses Supabase
|
||||||
|
-- Auth's own built-in ban mechanism (auth.users.banned_until, set via the
|
||||||
|
-- Admin API with the service role key) rather than a column here — no need
|
||||||
|
-- to reinvent it.
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
create table public.profiles (
|
||||||
|
id uuid primary key references auth.users (id) on delete cascade,
|
||||||
|
username text not null unique,
|
||||||
|
role text not null default 'regular' check (role in ('regular', 'admin', 'super_admin')),
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Helper functions used throughout the RLS policies below. Defined here,
|
||||||
|
-- right after `profiles` exists, since a `language sql` function's body is
|
||||||
|
-- validated against the schema at CREATE FUNCTION time.
|
||||||
|
create or replace function public.current_user_role()
|
||||||
|
returns text
|
||||||
|
language sql
|
||||||
|
stable
|
||||||
|
security definer
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
select role from public.profiles where id = auth.uid();
|
||||||
|
$$;
|
||||||
|
|
||||||
|
create or replace function public.is_admin()
|
||||||
|
returns boolean
|
||||||
|
language sql
|
||||||
|
stable
|
||||||
|
as $$
|
||||||
|
select coalesce(public.current_user_role() in ('admin', 'super_admin'), false);
|
||||||
|
$$;
|
||||||
|
|
||||||
|
create or replace function public.is_super_admin()
|
||||||
|
returns boolean
|
||||||
|
language sql
|
||||||
|
stable
|
||||||
|
as $$
|
||||||
|
select coalesce(public.current_user_role() = 'super_admin', false);
|
||||||
|
$$;
|
||||||
|
|
||||||
|
alter table public.profiles enable row level security;
|
||||||
|
|
||||||
|
-- Anyone can read their own profile; Super Admins can read everyone's
|
||||||
|
-- (Admins get no special profile visibility — their power is scoped to
|
||||||
|
-- catalog submissions, not user accounts, per the role table in §2/§6).
|
||||||
|
create policy "profiles_select_self_or_super_admin"
|
||||||
|
on public.profiles for select
|
||||||
|
using (id = auth.uid() or public.is_super_admin());
|
||||||
|
|
||||||
|
-- Users can update their own profile (e.g. username); Super Admins can
|
||||||
|
-- update anyone's (e.g. role changes). Role escalation by a non-super-admin
|
||||||
|
-- is blocked by the WITH CHECK clause, not just the USING clause.
|
||||||
|
create policy "profiles_update_self_or_super_admin"
|
||||||
|
on public.profiles for update
|
||||||
|
using (id = auth.uid() or public.is_super_admin())
|
||||||
|
with check (
|
||||||
|
public.is_super_admin()
|
||||||
|
or (id = auth.uid() and role = (select role from public.profiles where id = auth.uid()))
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Row creation happens via the trigger below, not direct client inserts.
|
||||||
|
-- Deletion happens by deleting the auth.users row (via the Admin API),
|
||||||
|
-- which cascades here — no direct delete policy needed.
|
||||||
|
|
||||||
|
-- Auto-create a profile when a new auth user is created. Username comes
|
||||||
|
-- from signup metadata (`options.data.username`) for manual signup; for
|
||||||
|
-- Google SSO, the frontend collects a username up front and passes it the
|
||||||
|
-- same way (per §2: "username collected up front, email pulled from Google").
|
||||||
|
create or replace function public.handle_new_user()
|
||||||
|
returns trigger
|
||||||
|
language plpgsql
|
||||||
|
security definer
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
begin
|
||||||
|
insert into public.profiles (id, username)
|
||||||
|
values (new.id, new.raw_user_meta_data ->> 'username');
|
||||||
|
return new;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
create trigger on_auth_user_created
|
||||||
|
after insert on auth.users
|
||||||
|
for each row execute function public.handle_new_user();
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- Catalog entities: manufacturers, device_categories, port_types,
|
||||||
|
-- cable_types, device_templates (+ device_template_ports).
|
||||||
|
--
|
||||||
|
-- Shared shape and RLS pattern across all of them:
|
||||||
|
-- * is_public + owner_id (null owner = seeded/system row)
|
||||||
|
-- * SELECT: visible if public, or you own it, or you're an Admin+
|
||||||
|
-- * INSERT: you can always create your own private (is_public = false)
|
||||||
|
-- row; only Admins+ can insert directly as public
|
||||||
|
-- * UPDATE: you can edit your own row while it's still private; once
|
||||||
|
-- public, only Admins+ can edit it (that's what "promote in place"
|
||||||
|
-- during submission review does — see catalog_submissions below)
|
||||||
|
-- * DELETE: same shape as UPDATE
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
create table public.manufacturers (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
name text not null,
|
||||||
|
is_public boolean not null default false,
|
||||||
|
owner_id uuid references public.profiles (id) on delete set null,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
create unique index manufacturers_public_name_key on public.manufacturers (lower(name)) where is_public;
|
||||||
|
|
||||||
|
alter table public.manufacturers enable row level security;
|
||||||
|
|
||||||
|
create policy "manufacturers_select" on public.manufacturers for select
|
||||||
|
using (is_public or owner_id = auth.uid() or public.is_admin());
|
||||||
|
|
||||||
|
create policy "manufacturers_insert" on public.manufacturers for insert
|
||||||
|
with check (
|
||||||
|
(owner_id = auth.uid() and not is_public)
|
||||||
|
or (public.is_admin() and is_public)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "manufacturers_update" on public.manufacturers for update
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin())
|
||||||
|
with check ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
create policy "manufacturers_delete" on public.manufacturers for delete
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
create table public.device_categories (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
name text not null,
|
||||||
|
is_public boolean not null default false,
|
||||||
|
owner_id uuid references public.profiles (id) on delete set null,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
create unique index device_categories_public_name_key on public.device_categories (lower(name)) where is_public;
|
||||||
|
|
||||||
|
alter table public.device_categories enable row level security;
|
||||||
|
|
||||||
|
create policy "device_categories_select" on public.device_categories for select
|
||||||
|
using (is_public or owner_id = auth.uid() or public.is_admin());
|
||||||
|
|
||||||
|
create policy "device_categories_insert" on public.device_categories for insert
|
||||||
|
with check (
|
||||||
|
(owner_id = auth.uid() and not is_public)
|
||||||
|
or (public.is_admin() and is_public)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "device_categories_update" on public.device_categories for update
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin())
|
||||||
|
with check ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
create policy "device_categories_delete" on public.device_categories for delete
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
create table public.port_types (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
name text not null,
|
||||||
|
category text not null check (category in ('video', 'audio', 'network', 'usb', 'power', 'control', 'other')),
|
||||||
|
family text not null,
|
||||||
|
compatible_family_ids text[] not null default '{}',
|
||||||
|
max_connections integer,
|
||||||
|
is_public boolean not null default false,
|
||||||
|
owner_id uuid references public.profiles (id) on delete set null,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.port_types enable row level security;
|
||||||
|
|
||||||
|
create policy "port_types_select" on public.port_types for select
|
||||||
|
using (is_public or owner_id = auth.uid() or public.is_admin());
|
||||||
|
|
||||||
|
create policy "port_types_insert" on public.port_types for insert
|
||||||
|
with check (
|
||||||
|
(owner_id = auth.uid() and not is_public)
|
||||||
|
or (public.is_admin() and is_public)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "port_types_update" on public.port_types for update
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin())
|
||||||
|
with check ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
create policy "port_types_delete" on public.port_types for delete
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
create table public.cable_types (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
name text not null,
|
||||||
|
family text not null,
|
||||||
|
family2 text,
|
||||||
|
unit text not null check (unit in ('ft', 'm')),
|
||||||
|
cost_per_unit numeric(10, 2),
|
||||||
|
is_public boolean not null default false,
|
||||||
|
owner_id uuid references public.profiles (id) on delete set null,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.cable_types enable row level security;
|
||||||
|
|
||||||
|
create policy "cable_types_select" on public.cable_types for select
|
||||||
|
using (is_public or owner_id = auth.uid() or public.is_admin());
|
||||||
|
|
||||||
|
create policy "cable_types_insert" on public.cable_types for insert
|
||||||
|
with check (
|
||||||
|
(owner_id = auth.uid() and not is_public)
|
||||||
|
or (public.is_admin() and is_public)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "cable_types_update" on public.cable_types for update
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin())
|
||||||
|
with check ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
create policy "cable_types_delete" on public.cable_types for delete
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
create table public.device_templates (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
name text not null,
|
||||||
|
category_id uuid not null references public.device_categories (id),
|
||||||
|
manufacturer_id uuid references public.manufacturers (id),
|
||||||
|
model text,
|
||||||
|
cost numeric(10, 2),
|
||||||
|
is_public boolean not null default false,
|
||||||
|
owner_id uuid references public.profiles (id) on delete set null,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.device_templates enable row level security;
|
||||||
|
|
||||||
|
create policy "device_templates_select" on public.device_templates for select
|
||||||
|
using (is_public or owner_id = auth.uid() or public.is_admin());
|
||||||
|
|
||||||
|
create policy "device_templates_insert" on public.device_templates for insert
|
||||||
|
with check (
|
||||||
|
(owner_id = auth.uid() and not is_public)
|
||||||
|
or (public.is_admin() and is_public)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "device_templates_update" on public.device_templates for update
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin())
|
||||||
|
with check ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
create policy "device_templates_delete" on public.device_templates for delete
|
||||||
|
using ((owner_id = auth.uid() and not is_public) or public.is_admin());
|
||||||
|
|
||||||
|
-- A device template's ports inherit their parent template's visibility —
|
||||||
|
-- there's no independent is_public/owner_id here, just a join back up.
|
||||||
|
create table public.device_template_ports (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
device_template_id uuid not null references public.device_templates (id) on delete cascade,
|
||||||
|
name text not null,
|
||||||
|
direction text not null check (direction in ('input', 'output', 'bidirectional')),
|
||||||
|
port_type_id uuid not null references public.port_types (id),
|
||||||
|
sort_order integer not null default 0
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.device_template_ports enable row level security;
|
||||||
|
|
||||||
|
create policy "device_template_ports_select" on public.device_template_ports for select
|
||||||
|
using (
|
||||||
|
exists (
|
||||||
|
select 1 from public.device_templates dt
|
||||||
|
where dt.id = device_template_id
|
||||||
|
and (dt.is_public or dt.owner_id = auth.uid() or public.is_admin())
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "device_template_ports_insert" on public.device_template_ports for insert
|
||||||
|
with check (
|
||||||
|
exists (
|
||||||
|
select 1 from public.device_templates dt
|
||||||
|
where dt.id = device_template_id
|
||||||
|
and ((dt.owner_id = auth.uid() and not dt.is_public) or public.is_admin())
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "device_template_ports_update" on public.device_template_ports for update
|
||||||
|
using (
|
||||||
|
exists (
|
||||||
|
select 1 from public.device_templates dt
|
||||||
|
where dt.id = device_template_id
|
||||||
|
and ((dt.owner_id = auth.uid() and not dt.is_public) or public.is_admin())
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "device_template_ports_delete" on public.device_template_ports for delete
|
||||||
|
using (
|
||||||
|
exists (
|
||||||
|
select 1 from public.device_templates dt
|
||||||
|
where dt.id = device_template_id
|
||||||
|
and ((dt.owner_id = auth.uid() and not dt.is_public) or public.is_admin())
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- catalog_submissions — one generalized review-queue table covering all
|
||||||
|
-- five catalog entity types (rather than five near-identical submission
|
||||||
|
-- tables), per §3: diff-against-current review UX, notify either way,
|
||||||
|
-- promote-in-place on approval, rejected stays editable for resubmission.
|
||||||
|
-- `entity_id` is null for a brand-new proposed entry, set for a proposed
|
||||||
|
-- edit to an existing public entry. `proposed_data` holds the submitted
|
||||||
|
-- fields as JSON; the diff view is computed at the app layer by comparing
|
||||||
|
-- it against the current live row (if entity_id is set).
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
create table public.catalog_submissions (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
entity_type text not null check (
|
||||||
|
entity_type in ('device_template', 'port_type', 'cable_type', 'device_category', 'manufacturer')
|
||||||
|
),
|
||||||
|
entity_id uuid,
|
||||||
|
proposed_data jsonb not null,
|
||||||
|
submitter_id uuid not null references public.profiles (id) on delete cascade,
|
||||||
|
status text not null default 'pending' check (status in ('pending', 'approved', 'rejected')),
|
||||||
|
reviewer_id uuid references public.profiles (id),
|
||||||
|
review_reason text,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.catalog_submissions enable row level security;
|
||||||
|
|
||||||
|
create policy "catalog_submissions_select" on public.catalog_submissions for select
|
||||||
|
using (submitter_id = auth.uid() or public.is_admin());
|
||||||
|
|
||||||
|
create policy "catalog_submissions_insert" on public.catalog_submissions for insert
|
||||||
|
with check (submitter_id = auth.uid() and status = 'pending');
|
||||||
|
|
||||||
|
-- Submitter can revise their own pending/rejected submission (e.g. edit
|
||||||
|
-- proposed_data and flip status back to 'pending' after a rejection).
|
||||||
|
-- Admins can update any submission (approve/reject, set reviewer_id/
|
||||||
|
-- review_reason) — actually applying an approval to the live catalog row
|
||||||
|
-- is separate application logic, not something RLS does on its own.
|
||||||
|
create policy "catalog_submissions_update" on public.catalog_submissions for update
|
||||||
|
using (
|
||||||
|
(submitter_id = auth.uid() and status in ('pending', 'rejected'))
|
||||||
|
or public.is_admin()
|
||||||
|
)
|
||||||
|
with check (
|
||||||
|
(submitter_id = auth.uid() and status in ('pending', 'rejected'))
|
||||||
|
or public.is_admin()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Submitter can withdraw their own still-pending submission.
|
||||||
|
create policy "catalog_submissions_delete" on public.catalog_submissions for delete
|
||||||
|
using (submitter_id = auth.uid() and status = 'pending');
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- diagrams — JSONB document per diagram (see file header for why).
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
create table public.diagrams (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
name text not null,
|
||||||
|
owner_id uuid not null references public.profiles (id) on delete cascade,
|
||||||
|
data jsonb not null,
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
updated_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Created here (before diagrams' own RLS policies) because those policies
|
||||||
|
-- need to reference it — table existence is checked at CREATE POLICY time,
|
||||||
|
-- same as it was for the helper functions above. Its own RLS/policies are
|
||||||
|
-- defined further down, once `diagrams` policies no longer need editing.
|
||||||
|
create table public.diagram_collaborators (
|
||||||
|
diagram_id uuid not null references public.diagrams (id) on delete cascade,
|
||||||
|
user_id uuid not null references public.profiles (id) on delete cascade,
|
||||||
|
permission text not null check (permission in ('view', 'edit')),
|
||||||
|
created_at timestamptz not null default now(),
|
||||||
|
primary key (diagram_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- `diagrams` and `diagram_collaborators` policies each need to check the
|
||||||
|
-- other table (is this user a collaborator? / does this user own the
|
||||||
|
-- diagram?). A direct correlated subquery from one RLS-protected table into
|
||||||
|
-- another RLS-protected table that itself queries back is a well-known
|
||||||
|
-- Postgres RLS trap: each table's policy re-triggers the other's, forever
|
||||||
|
-- ("infinite recursion detected in policy for relation..."). The fix is to
|
||||||
|
-- route the cross-table check through a SECURITY DEFINER function — it runs
|
||||||
|
-- as the function's owner (postgres, which bypasses RLS as the table
|
||||||
|
-- owner), so the lookup inside it never re-enters either policy.
|
||||||
|
create or replace function public.diagram_owner_id(p_diagram_id uuid)
|
||||||
|
returns uuid
|
||||||
|
language sql
|
||||||
|
stable
|
||||||
|
security definer
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
select owner_id from public.diagrams where id = p_diagram_id;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
create or replace function public.diagram_collaborator_permission(p_diagram_id uuid, p_user_id uuid)
|
||||||
|
returns text
|
||||||
|
language sql
|
||||||
|
stable
|
||||||
|
security definer
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
select permission from public.diagram_collaborators
|
||||||
|
where diagram_id = p_diagram_id and user_id = p_user_id;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
alter table public.diagrams enable row level security;
|
||||||
|
|
||||||
|
create policy "diagrams_select" on public.diagrams for select
|
||||||
|
using (
|
||||||
|
owner_id = auth.uid()
|
||||||
|
or public.is_super_admin()
|
||||||
|
or public.diagram_collaborator_permission(id, auth.uid()) is not null
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "diagrams_insert" on public.diagrams for insert
|
||||||
|
with check (owner_id = auth.uid());
|
||||||
|
|
||||||
|
create policy "diagrams_update" on public.diagrams for update
|
||||||
|
using (
|
||||||
|
owner_id = auth.uid()
|
||||||
|
or public.is_super_admin()
|
||||||
|
or public.diagram_collaborator_permission(id, auth.uid()) = 'edit'
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "diagrams_delete" on public.diagrams for delete
|
||||||
|
using (owner_id = auth.uid() or public.is_super_admin());
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- diagram_collaborators — per-collaborator view/edit permission (§8).
|
||||||
|
-- Only the diagram's owner (or a Super Admin) manages the collaborator
|
||||||
|
-- list; a collaborator can see their own membership row but can't add
|
||||||
|
-- others, matching "the owner picks who has access" from the plan.
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
alter table public.diagram_collaborators enable row level security;
|
||||||
|
|
||||||
|
create policy "diagram_collaborators_select" on public.diagram_collaborators for select
|
||||||
|
using (
|
||||||
|
user_id = auth.uid()
|
||||||
|
or public.is_super_admin()
|
||||||
|
or public.diagram_owner_id(diagram_id) = auth.uid()
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "diagram_collaborators_insert" on public.diagram_collaborators for insert
|
||||||
|
with check (
|
||||||
|
public.is_super_admin()
|
||||||
|
or public.diagram_owner_id(diagram_id) = auth.uid()
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "diagram_collaborators_update" on public.diagram_collaborators for update
|
||||||
|
using (
|
||||||
|
public.is_super_admin()
|
||||||
|
or public.diagram_owner_id(diagram_id) = auth.uid()
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "diagram_collaborators_delete" on public.diagram_collaborators for delete
|
||||||
|
using (
|
||||||
|
public.is_super_admin()
|
||||||
|
or public.diagram_owner_id(diagram_id) = auth.uid()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ============================================================================
|
||||||
|
-- diagram_snapshots — rolling undo/recovery history (§8). Immutable once
|
||||||
|
-- written (no update policy); retention/pruning to "recent" snapshots is a
|
||||||
|
-- scheduled job running as service_role (bypasses RLS entirely), not
|
||||||
|
-- modeled here — this table just needs to accept writes and be readable by
|
||||||
|
-- whoever can already see/edit the diagram.
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
create table public.diagram_snapshots (
|
||||||
|
id uuid primary key default gen_random_uuid(),
|
||||||
|
diagram_id uuid not null references public.diagrams (id) on delete cascade,
|
||||||
|
data jsonb not null,
|
||||||
|
saved_by uuid references public.profiles (id),
|
||||||
|
created_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.diagram_snapshots enable row level security;
|
||||||
|
|
||||||
|
-- Same recursion trap as diagrams/diagram_collaborators applies here too
|
||||||
|
-- (this table's policy would otherwise correlated-subquery into both of
|
||||||
|
-- those RLS-protected tables) — routed through the same SECURITY DEFINER
|
||||||
|
-- helper functions for the same reason.
|
||||||
|
create policy "diagram_snapshots_select" on public.diagram_snapshots for select
|
||||||
|
using (
|
||||||
|
public.is_super_admin()
|
||||||
|
or public.diagram_owner_id(diagram_id) = auth.uid()
|
||||||
|
or public.diagram_collaborator_permission(diagram_id, auth.uid()) is not null
|
||||||
|
);
|
||||||
|
|
||||||
|
create policy "diagram_snapshots_insert" on public.diagram_snapshots for insert
|
||||||
|
with check (
|
||||||
|
public.is_super_admin()
|
||||||
|
or public.diagram_owner_id(diagram_id) = auth.uid()
|
||||||
|
or public.diagram_collaborator_permission(diagram_id, auth.uid()) = 'edit'
|
||||||
|
);
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
-- RLS policy tests (pgTAP), per organized-ideas.md §1: "automated tests
|
||||||
|
-- specifically for the RLS policies... the actual security boundary once
|
||||||
|
-- roles matter." Run with: supabase test db
|
||||||
|
--
|
||||||
|
-- device_categories is used as the representative test for the shared
|
||||||
|
-- catalog pattern (manufacturers/port_types/cable_types/device_templates
|
||||||
|
-- all use the identical is_public/owner_id policy shape) rather than
|
||||||
|
-- repeating the same assertions five times.
|
||||||
|
--
|
||||||
|
-- Approach: fixture users/rows are set up as the postgres superuser (which
|
||||||
|
-- bypasses RLS entirely), then we switch to the `authenticated` role and
|
||||||
|
-- impersonate each fixture user in turn by setting the JWT `sub` claim that
|
||||||
|
-- auth.uid() reads — the same mechanism Supabase's own runtime uses.
|
||||||
|
--
|
||||||
|
-- Note on UPDATE/DELETE vs. INSERT RLS failures: an INSERT whose new row
|
||||||
|
-- fails WITH CHECK always raises 42501. An UPDATE/DELETE whose target row
|
||||||
|
-- doesn't satisfy USING is simply excluded from the statement — 0 rows
|
||||||
|
-- affected, no error. Only an UPDATE where USING passes (the row is yours
|
||||||
|
-- to touch) but the *new* values fail WITH CHECK actually throws. Tests
|
||||||
|
-- below use throws_ok only for genuine WITH CHECK failures, and a plain
|
||||||
|
-- update-then-assert-unchanged for the "you can't even touch this row"
|
||||||
|
-- case.
|
||||||
|
|
||||||
|
begin;
|
||||||
|
|
||||||
|
create extension if not exists pgtap with schema extensions;
|
||||||
|
|
||||||
|
select plan(23);
|
||||||
|
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
-- Fixtures (as postgres — RLS does not apply)
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
insert into auth.users (id, email, raw_user_meta_data) values
|
||||||
|
('11111111-1111-1111-1111-111111111111', 'alice@example.com', '{"username":"alice"}'),
|
||||||
|
('22222222-2222-2222-2222-222222222222', 'bob@example.com', '{"username":"bob"}'),
|
||||||
|
('33333333-3333-3333-3333-333333333333', 'carol@example.com', '{"username":"carol_admin"}'),
|
||||||
|
('44444444-4444-4444-4444-444444444444', 'dave@example.com', '{"username":"dave_superadmin"}');
|
||||||
|
|
||||||
|
update public.profiles set role = 'admin' where id = '33333333-3333-3333-3333-333333333333';
|
||||||
|
update public.profiles set role = 'super_admin' where id = '44444444-4444-4444-4444-444444444444';
|
||||||
|
|
||||||
|
-- Everything from here on runs as the `authenticated` role, with auth.uid()
|
||||||
|
-- controlled by the JWT sub claim we set before each block.
|
||||||
|
set local role authenticated;
|
||||||
|
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
-- Catalog pattern (device_categories as the representative case)
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '11111111-1111-1111-1111-111111111111', true);
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ insert into public.device_categories (id, name, owner_id, is_public)
|
||||||
|
values ('a0000000-0000-0000-0000-000000000001', 'Alice Test Category', '11111111-1111-1111-1111-111111111111', false) $$,
|
||||||
|
'alice can insert her own private category'
|
||||||
|
);
|
||||||
|
|
||||||
|
select throws_ok(
|
||||||
|
$$ insert into public.device_categories (name, owner_id, is_public)
|
||||||
|
values ('Sneaky Public Category', '11111111-1111-1111-1111-111111111111', true) $$,
|
||||||
|
'42501'::char(5), null,
|
||||||
|
'alice cannot insert a public category directly'
|
||||||
|
);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select count(*)::int from public.device_categories where id = 'a0000000-0000-0000-0000-000000000001'),
|
||||||
|
1,
|
||||||
|
'alice can see her own private category'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '22222222-2222-2222-2222-222222222222', true);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select count(*)::int from public.device_categories where id = 'a0000000-0000-0000-0000-000000000001'),
|
||||||
|
0,
|
||||||
|
'bob cannot see alice''s private category'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '11111111-1111-1111-1111-111111111111', true);
|
||||||
|
|
||||||
|
select throws_ok(
|
||||||
|
$$ update public.device_categories set is_public = true where id = 'a0000000-0000-0000-0000-000000000001' $$,
|
||||||
|
'42501'::char(5), null,
|
||||||
|
'alice cannot self-promote her category to public'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '33333333-3333-3333-3333-333333333333', true);
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ update public.device_categories set is_public = true where id = 'a0000000-0000-0000-0000-000000000001' $$,
|
||||||
|
'carol (admin) can promote alice''s category to public in place'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '22222222-2222-2222-2222-222222222222', true);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select count(*)::int from public.device_categories where id = 'a0000000-0000-0000-0000-000000000001'),
|
||||||
|
1,
|
||||||
|
'bob can see the category now that it is public'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Now-public row: alice's USING clause ("mine AND still private") no
|
||||||
|
-- longer matches at all, so this update is a silent no-op, not an error.
|
||||||
|
select set_config('request.jwt.claim.sub', '11111111-1111-1111-1111-111111111111', true);
|
||||||
|
update public.device_categories set name = 'Renamed' where id = 'a0000000-0000-0000-0000-000000000001';
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select name from public.device_categories where id = 'a0000000-0000-0000-0000-000000000001'),
|
||||||
|
'Alice Test Category',
|
||||||
|
'alice (original owner) can no longer edit it now that it is public (update is a no-op)'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
-- Diagrams + collaborators
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ insert into public.diagrams (id, name, owner_id, data)
|
||||||
|
values ('b0000000-0000-0000-0000-000000000001', 'Alice''s Rig', '11111111-1111-1111-1111-111111111111', '{}'::jsonb) $$,
|
||||||
|
'alice can insert her own diagram'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '22222222-2222-2222-2222-222222222222', true);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select count(*)::int from public.diagrams where id = 'b0000000-0000-0000-0000-000000000001'),
|
||||||
|
0,
|
||||||
|
'bob cannot see alice''s diagram before being added as a collaborator'
|
||||||
|
);
|
||||||
|
|
||||||
|
select throws_ok(
|
||||||
|
$$ insert into public.diagram_collaborators (diagram_id, user_id, permission)
|
||||||
|
values ('b0000000-0000-0000-0000-000000000001', '22222222-2222-2222-2222-222222222222', 'edit') $$,
|
||||||
|
'42501'::char(5), null,
|
||||||
|
'bob cannot add himself as a collaborator on alice''s diagram'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '11111111-1111-1111-1111-111111111111', true);
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ insert into public.diagram_collaborators (diagram_id, user_id, permission)
|
||||||
|
values ('b0000000-0000-0000-0000-000000000001', '22222222-2222-2222-2222-222222222222', 'view') $$,
|
||||||
|
'alice (owner) can add bob as a view-only collaborator'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '22222222-2222-2222-2222-222222222222', true);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select count(*)::int from public.diagrams where id = 'b0000000-0000-0000-0000-000000000001'),
|
||||||
|
1,
|
||||||
|
'bob can now see alice''s diagram as a view collaborator'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Bob's collaborator permission is 'view', so diagrams_update's USING
|
||||||
|
-- clause doesn't match at all for him — silent no-op, not an error.
|
||||||
|
update public.diagrams set name = 'Bob was here' where id = 'b0000000-0000-0000-0000-000000000001';
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select name from public.diagrams where id = 'b0000000-0000-0000-0000-000000000001'),
|
||||||
|
'Alice''s Rig',
|
||||||
|
'bob (view-only) cannot update alice''s diagram (update is a no-op)'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '11111111-1111-1111-1111-111111111111', true);
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ update public.diagram_collaborators set permission = 'edit'
|
||||||
|
where diagram_id = 'b0000000-0000-0000-0000-000000000001' and user_id = '22222222-2222-2222-2222-222222222222' $$,
|
||||||
|
'alice (owner) can upgrade bob to edit access'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '22222222-2222-2222-2222-222222222222', true);
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ update public.diagrams set name = 'Bob was here' where id = 'b0000000-0000-0000-0000-000000000001' $$,
|
||||||
|
'bob (edit collaborator) can now update alice''s diagram'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '33333333-3333-3333-3333-333333333333', true);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select count(*)::int from public.diagrams where id = 'b0000000-0000-0000-0000-000000000001'),
|
||||||
|
0,
|
||||||
|
'carol (admin, not super admin) has no special visibility into alice''s diagram'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '44444444-4444-4444-4444-444444444444', true);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select count(*)::int from public.diagrams where id = 'b0000000-0000-0000-0000-000000000001'),
|
||||||
|
1,
|
||||||
|
'dave (super admin) can see any diagram'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
-- Catalog submissions
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '22222222-2222-2222-2222-222222222222', true);
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ insert into public.catalog_submissions (entity_type, proposed_data, submitter_id)
|
||||||
|
values ('device_category', '{"name":"Bob''s New Category"}'::jsonb, '22222222-2222-2222-2222-222222222222') $$,
|
||||||
|
'bob can submit a new catalog entry for review'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '11111111-1111-1111-1111-111111111111', true);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select count(*)::int from public.catalog_submissions where submitter_id = '22222222-2222-2222-2222-222222222222'),
|
||||||
|
0,
|
||||||
|
'alice cannot see bob''s submission'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '33333333-3333-3333-3333-333333333333', true);
|
||||||
|
|
||||||
|
select is(
|
||||||
|
(select count(*)::int from public.catalog_submissions where submitter_id = '22222222-2222-2222-2222-222222222222'),
|
||||||
|
1,
|
||||||
|
'carol (admin) can see bob''s submission'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
-- Profiles / role escalation
|
||||||
|
-- ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '11111111-1111-1111-1111-111111111111', true);
|
||||||
|
|
||||||
|
select throws_ok(
|
||||||
|
$$ update public.profiles set role = 'admin' where id = '11111111-1111-1111-1111-111111111111' $$,
|
||||||
|
'42501'::char(5), null,
|
||||||
|
'alice cannot promote her own role'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claim.sub', '44444444-4444-4444-4444-444444444444', true);
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ update public.profiles set role = 'admin' where id = '11111111-1111-1111-1111-111111111111' $$,
|
||||||
|
'dave (super admin) can change another user''s role'
|
||||||
|
);
|
||||||
|
|
||||||
|
select * from finish();
|
||||||
|
|
||||||
|
rollback;
|
||||||
@@ -5,4 +5,11 @@ import { defineConfig } from 'vite'
|
|||||||
// https://vite.dev/config/
|
// https://vite.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react(), tailwindcss()],
|
plugins: [react(), tailwindcss()],
|
||||||
|
// Pinned (rather than Vite's default floating port) so local Supabase
|
||||||
|
// Auth's redirect allow-list (supabase/config.toml) stays valid instead of
|
||||||
|
// silently breaking if 5173 happens to be busy and Vite picks another one.
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
strictPort: true,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user