Synthèse automatique
Encadre l'écriture de code qui construit ou exécute du SQL contre la base Postgres réelle de l'utilisateur, en appliquant un modèle de sécurité fondé sur la « paternité prouvée » des fragments SQL.
Points forts
- Définit trois classes explicites de fragments SQL (codés en dur, influençables par un tiers, écrits par l'utilisateur) avec les utilitaires `safeSql` et `untrustedSql` correspondants
- S'appuie sur un typage « branded » (`SafeSqlFragment`, `UntrustedSqlFragment`) pour suivre la provenance au niveau du compilateur plutôt que par simple revue humaine
- Couvre les cas de contamination réaliste, comme un champ de saisie prérempli depuis un paramètre d'URL non assaini
- Rappelle de charger la compétence avant d'écrire le code, et pas seulement en relecture de diff
Limites
- Très spécifique à l'écosystème Supabase Studio et au paquet `@supabase/pg-meta` ; peu réutilisable tel quel ailleurs
- Le document fourni s'interrompt au milieu de l'exemple `SafeSqlInput`, donc certains détails d'implémentation manquent
- Suppose que l'équipe dispose déjà des types et utilitaires de provenance dans sa base de code
À charger dès qu'une tâche implique de générer, stocker ou exécuter du SQL dans Supabase Studio, y compris pour une fonctionnalité qui ne mentionne pas la sécurité.
À ignorer pour les changements qui ne touchent jamais au texte SQL ni à son exécution, comme du style, de la mise en page ou des hooks de données sans SQL.
Analyse de sécurité
SûrThis is a purely instructional markdown document about SQL provenance/branded-type patterns (safeSql, untrustedSql, SafeSqlFragment) for Supabase Studio. It declares no allowed-tools, contains no shell commands, no network calls, no file deletion, no obfuscated payloads, and no instructions to exfiltrate secrets or disable safety checks. The only 'powerful' guidance is to use branded types and sanitizers, which is defensive rather than risky.
Aucun point d'attention détecté
Comment cette analyse est faiteExemples
Add a search box to the SQL editor that takes the `q` query parameter from the URL and interpolates it into the WHERE clause of the generated query. Which pg-meta helper should I wrap it in?I'm building the policy editor 'Apply' button — it takes the policy definition stored in the database and executes it. How do I keep this safe under the proven-authorship model?Create a reusable text input for SQL snippets where the value can be promoted to SafeSqlFragment on change, so prefilled URL values can't contaminate user-authored SQL.name: safe-sql-execution description: >- Use whenever code will build, return, fetch, or execute SQL that runs against a user's real Postgres database — even when the request reads like an ordinary feature or bug fix and never says "security," "injection," or "SafeSqlFragment." This covers: writing or editing any pg-meta function, query builder, or endpoint that builds/returns SQL for database objects (tables, views, functions, DB triggers, indexes, RLS policies); interpolating a schema/table/column/search/route-param value into SQL text; storing, fetching, or re-running SQL that round-trips from the database (a policy's definition, a function/view definition, a snippet's saved content); and any "Run"/"Apply"/"Execute" action that sends SQL to a project's database (SQL editor run-selection, policy editor apply, snippet runner). Load this BEFORE writing such code, not only when reviewing a finished diff. Skip only for changes that never touch SQL text or execution — styling, unrelated data hooks, non-SQL form validation, or UI layout work.
Safe SQL execution
Supabase Studio executes SQL statements directly against the user's database. Because this is the authenticated user's own database, our security model is different from most frontend applications: a user should be able to execute any SQL statement, as long as it is proven that they themselves authored it. What we SHOULD NOT ALLOW is execution of SQL statements that can be influenced by an attacker, such as through URL parameters.
Security model
The security model for SQL execution in Supabase Studio is based on the principle of "proven authorship". This means that a user should only be able to execute SQL statements that they have explicitly authored, and not statements that can be influenced by external input.
There are three classes of SQL fragments:
-
Hardcoded within the application code. These are safe to execute because they cannot be influenced by an attacker. They can be marked with the
safeSqlutility withpg-meta:import { safeSql } from '@supabase/pg-meta' const sql = safeSql` SELECT * FROM users WHERE id = 1 `safeSqlautomatically creates a string of the branded typeSafeSqlFragment. (See Provenance Tracking below.) -
Third-party influenceable. These are SQL fragments that can be influenced by an attacker, such as through URL parameters or LLM output. These should be marked with the
untrustedSqlutility withpg-meta:import { untrustedSql } from '@supabase/pg-meta' const unsafeQuery = searchParams.get('query') const querySql = untrustedSql(unsafeQuery)untrustedSqlcreates a string of the branded typeUntrustedSqlFragment. (See Provenance Tracking below.) -
User-authored. These are SQL fragments that are authored by the user themselves within the UI, for example in a text input field. Because the user is the author, these should be considered safe to execute.
However, there is a caveat, where third-party and user-authored code can mix, contaminating the user-authored code (for example, if an input is prefilled from an unsanitized URL parameter). Provenance tracking helps us track these cases.
For example, a safe input component could be implemented as follows by requiring that its placeholder and controlled value are of type
SafeSqlFragment. In this case we can use its onChange to promote the user input toSafeSqlFragmenttype, because we know that the user is the author of the input. An implementation of this is in @apps/studio/components/ui/SafeSqlInput.tsx:import { rawSql, type SafeSqlFragment } from '@supabase/pg-meta' import type { ChangeEvent, ComponentProps } from 'react' import { Input } from 'ui-patterns/DataInputs/Input' type InputProps = ComponentProps<typeof Input> export type SafeSqlInputProps = Omit< InputProps, 'placeholder' | 'value' | 'onChange' > & { placeholder?: SafeSqlFragment value: SafeSqlFragment onChange?: (event: ChangeEvent<HTMLInputElement>, value: SafeSqlFragment) => void } export const SafeSqlInput = ({ onChange, ...props }: SafeSqlInputProps) => ( <Input {...props} onChange={(event) => onChange?.(event, rawSql(event.target.value))} /> )This is pretty much the ONLY VALID USE CASE of the rawSql export from pg-meta, and it should be used with caution.
Provenance tracking
Branded types are used to track the provenance of SQL fragments. The types,
exported from pg-meta, are:
SafeSqlFragment: represents SQL fragments that are safe to execute, because they are either hardcoded in the application or authored by the user themselves.UntrustedSqlFragment: represents SQL fragments that can be influenced by an attacker, such as through URL parameters or LLM output.
These are valid ways to generate a SafeSqlFragment:
- Using the
safeSqlutility frompg-metato create hardcoded SQL fragments. - Using the sanitization utilities from
pg-metato sanitize untrusted input and promote it to aSafeSqlFragment:identliteralkeyword
- Using the safe SQL manipulation utilities:
joinSqlFragmentstrimSafeSqlFragment
UntrustedSqlFragments can be generated from raw strings using
untrustedSql().
There is also a union type, DisplayableSqlFragment, which represents SQL fragments that can be safely displayed in the UI, but not necessarily executed. This includes both SafeSqlFragment and UntrustedSqlFragment.
Security of SQL round-tripped from the user's database
SQL derived directly from catalog tables (e.g., function definitions, RLS expressions, etc.) is considered safe, and it is promoted AT THE POINT OF BEING QUERIED from the database. In most cases, this is in an apps/studio/data/*/.ts file, in the utility function that makes the API or database fetch.
A critical exception to the safety of SQL round-tripped from the database is
user snippets. These must NEVER BE CONSIDERED SAFE because they are both (a)
externally influenceable and (b) auto-saved. The snippet type uses the
unchecked_sql property, which is an UntrustedSqlFragment, to enforce this.
Promoting SQL fragments to SafeSqlFragment type
Given an insecure string or UntrustedSqlFragment, how do we promote it safely
to a SafeSqlFragment?
Sanitization utilities
This is the preferred method when the input is sanitizable, e.g., it is a relation name, a column name, will be compared as a literal, etc.
The pg-meta library provides the following sanitization utilities that can be
used to safely promote untrusted input to SafeSqlFragment:
ident: for sanitizing identifiers such as table names or column names.literal: for sanitizing literal values that will be used in SQL statements.keyword: for sanitizing SQL keywords.
acceptUntrustedSql
Some untrusted SQL fragments cannot be sanitized with the above utilities. For
example, the USING expression in the RLS policy editor is an arbitrary SQL
expression.
In these cases, we can promote the SQL fragment upon explicit user action. User action indicates that the user has seen the SQL and is OK with running it. For example, an explicit user action could be clicking a "Run" button.
The promotion happens with the acceptUntrustedSql utility from pg-meta,
which takes an UntrustedSqlFragment and returns a SafeSqlFragment.
This utility MUST ONLY BE USED IN event handlers. It should NEVER be used in a useQuery, direct in the render body of a component, in a useEffect, or anywhere it could auto-run without explicit user action.
This is safe:
import { acceptUntrustedSql } from '@supabase/pg-meta'
function SafeComponent() {
const { mutate: execute } = useExecuteSqlMutation()
const handleRun = () => {
// ✅ GOOD: Safe because it is in an event handler which requires a user
// click
execute({ sql: acceptUntrustedSql(/* sql */) })
}
return (
<button onClick={handleRun}>Run</button>
)
}
This is unsafe:
import { acceptUntrustedSql } from '@supabase/pg-meta'
function UnsafeComponent() {
const { data } = useQuery({
queryKey: ['execute-sql', sql],
queryFn: () => {
// 🛑 BAD: Unsafe because it is in a query which could auto-run without
// explicit user action
return execute({ sql: acceptUntrustedSql(/* sql */) })
},
})
}
Type guarantees
SQL run against the user's Postgres database runs through the executeSql
function, which only takes arguments of type SafeSqlFragment for the SQL
parameter. Raw strings or UntrustedSqlFragments will error at compile time.
Examples
Hard-coded SQL
// ✅ GOOD: Automatically safe with `safeSql` utility
const selectStatement = safeSql`select 1`
SQL with sanitizable interpolations
// ✅ GOOD: `pg-meta` utilities sanitize the input
const tableName = ident(userInputTableName)
const searchString = literal(userInputSearchString)
const sqlStatement = safeSql`
SELECT *
FROM ${tableName}
WHERE search_column = ${searchString}
`
// 🛑 BAD: Passing raw strings will type error
const tableName = 'my_table'
const sqlStatement = safeSql`
SELECT *
FROM ${tableName}
`
Non-sanitizable SQL from a user input
// ✅ GOOD: SafeSqlInput only allows a value that is a SafeSqlFragment
import { SafeSqlInput } from '@apps/studio/components/ui/SafeSqlInput'
function MyComponent() {
const [sql, setSql] = useState<SafeSqlFragment>(safeSql``)
return (
<SafeSqlInput
placeholder={safeSql`Enter your SQL query here...`}
value={sql}
onChange={(event, value) => setSql(value)}
/>
)
}
// 🛑 BAD: This input mixes SafeSqlFragments and unsafe strings
function MyBadComponent() {
const [sql, setSql] = useState<SafeSqlFragment>(safeSql``)
return (
<Input
// 🛑 BAD: This is unsafe because the placeholder is a raw string
placeholder="Enter your SQL query here..."
value={sql}
onChange={(event) => setSql(event.target.value)}
/>
)
}
Round-tripping SQL from the database (NOT snippet content)
// ✅ GOOD: SQL from the database is promoted to SafeSqlFragment at the point
// of fetching
// data/function-definitions.ts
function markFunctionDefinitionSafe(
functionDefinition: FunctionDefinition
): SafeFunctionDefinition {
return {
...functionDefinition,
definition: functionDefinition.definition as SafeSqlFragment,
}
}
// data/function-definitions.ts
function getFunctionDefinitions() {
return GET(`/function-definitions`).then((functionDefinitions) =>
functionDefinitions.map(markFunctionDefinitionSafe)
)
}
// 🛑 BAD: Strings are promoted to SafeSqlFragment in a utility function, where
// it is impossible to easily determine the safety of the input
// utils.ts
function markFunctionDefinitionSafe(
functionDefinition: FunctionDefinition
): SafeFunctionDefinition {
return {
...functionDefinition,
definition: functionDefinition.definition as SafeSqlFragment,
}
}
// Component.ts
function MyComponent() {
const { data: functionDefinitions } = useFunctionDefinitions()
const safeFunctionDefinitions = functionDefinitions.map(markFunctionDefinitionSafe)
}
Snippet content is ALWAYS UNSAFE
Snippets are auto-persisted to the database and can be created or modified
through externally influenceable channels (e.g., prefilled from URL params).
The unchecked_sql property is typed as UntrustedSqlFragment to enforce this
— it must only be promoted to SafeSqlFragment via acceptUntrustedSql in an
event handler that requires explicit user action.
// 🛑 BAD: Snippet content is executed automatically via useQuery, with no
// explicit user action confirming that the user has reviewed the SQL.
import { acceptUntrustedSql } from '@supabase/pg-meta'
function UnsafeSnippetPreview({ snippet }: { snippet: Snippet }) {
const { data } = useExecuteSqlQuery({
sql: acceptUntrustedSql(snippet.content.unchecked_sql),
})
return <Results data={data} />
}
// 🛑 BAD: Casting bypasses the type system entirely. The snippet's
// `unchecked_sql` is `UntrustedSqlFragment` for a reason — never cast it.
function UnsafeSnippetRunner({ snippet }: { snippet: Snippet }) {
const { mutate: execute } = useExecuteSqlMutation()
useEffect(() => {
execute({ sql: snippet.content.unchecked_sql as SafeSqlFragment })
}, [snippet])
}
// ✅ GOOD: Snippet content is only promoted to SafeSqlFragment inside an event
// handler, after the user clicks Run. The user has seen the SQL in the editor
// and explicitly chosen to execute it.
import { acceptUntrustedSql } from '@supabase/pg-meta'
function SnippetRunner({ snippet }: { snippet: Snippet }) {
const { mutate: execute } = useExecuteSqlMutation()
const handleRun = () => {
execute({ sql: acceptUntrustedSql(snippet.content.unchecked_sql) })
}
return (
<>
<SnippetEditor snippet={snippet} />
<button onClick={handleRun}>Run</button>
</>
)
}
Analytics SQL (BigQuery / ClickHouse)
The same security model applies to analytics queries, which target BigQuery
or ClickHouse via the
/platform/projects/{ref}/analytics/endpoints/logs.all{,.otel} endpoints.
Filter keys and values from URL parameters and UI inputs are spliced into SQL
that runs against the project's logs, so the same injection risk exists.
The brand and helpers live in apps/studio/data/logs/safe-analytics-sql.ts,
intentionally disjoint from the pg-meta SafeSqlFragment brand:
SafeLogSqlFragment— branded type for analytics SQL.safeSql— template tag that only acceptsSafeLogSqlFragmentinterpolations.analyticsLiteral(value)— sanitizes string/number/boolean literals.quotedIdent(name)— validates and backtick-quotes dotted identifiers.keyword(value, allowed)— validates against an allow-list of operators.joinSqlFragments(fragments, separator)— composes already-branded fragments.
The brands are kept separate because escape semantics differ — Postgres-safe
E'…' strings, ::jsonb casts, and double-quoted identifiers are unsafe for
BigQuery and/or ClickHouse, and vice versa. Crossing the brands would silently
emit unsafe SQL.
The wire-boundary wrapper is executeAnalyticsSql in
apps/studio/data/logs/execute-analytics-sql.ts, analogous to pg-meta's
executeSql. It accepts only SafeLogSqlFragment for its sql parameter, so
raw strings are rejected at compile time. A grep-based vitest
(apps/studio/tests/unit/lints/analytics-sql-boundary.test.ts) prevents
regressions by failing the build if any file outside
execute-analytics-sql.ts calls post() or get() directly against
logs.all or logs.all.otel.
import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'
import { analyticsLiteral, quotedIdent, safeSql } from '@/data/logs/safe-analytics-sql'
// ✅ GOOD: every interpolation is sanitized.
const sql = safeSql`
SELECT timestamp, event_message
FROM ${quotedIdent(table)}
WHERE id = ${analyticsLiteral(id)}
`
await executeAnalyticsSql({
projectRef,
endpoint: '/platform/projects/{ref}/analytics/endpoints/logs.all',
sql,
iso_timestamp_start,
iso_timestamp_end,
})
// 🛑 BAD: raw string interpolation. This fails to type-check at the
// executeAnalyticsSql boundary because the result is `string`, not
// `SafeLogSqlFragment`.
const sql = `SELECT * FROM ${table} WHERE id = '${id}'`
await executeAnalyticsSql({ projectRef, endpoint, sql, ... })
Du fichier au premier essai
Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.
Consulter la source et ses fichiers annexesCe téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.
1. Télécharger le fichier
Télécharger SKILL.mdDepuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.
Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.
mkdir -p '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/safe-sql-execution-in-supabase-studio-mte1lfs6/download' --output '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6/SKILL.md.part' && mv '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6/SKILL.md.part' '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6/SKILL.md'2. Vérifier les prérequis
Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.
Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.
Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.
3. Charger la skill
Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.
Claude Code
test -f '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6/SKILL.md' && test -s '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/safe-sql-execution' && cp -R '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6' '.claude/skills/safe-sql-execution'Cursor
test -f '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6/SKILL.md' && test -s '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/safe-sql-execution' && cp -R '.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6' '.cursor/skills/safe-sql-execution'OpenSkills
OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.
Installation officielle d’OpenSkillsopenskills install './.skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6'openskills read 'safe-sql-execution-in-supabase-studio-mte1lfs6'La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.
Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.
openskills syncMode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.
4. Faire un premier essai
Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :
Lis .skill-downloads/safe-sql-execution-in-supabase-studio-mte1lfs6/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.
Sécurité AMM DeFi
Securite
Checklist de sécurité pour les contrats Solidity AMM, pools de liquidité et flux de swap. Couvre réentrance, attaques par donation, manipulation d'oracles, etc.
Créateur de règles Semgrep
Securite
Crée des règles Semgrep personnalisées pour détecter des vulnérabilités de sécurité, des motifs de bugs et des motifs de code. Inclut une méthodologie de test en premier, le support du mode taint et des étapes de validation. Utile pour construire des détections d'analyse statique ciblées.
Revue barre d'outils développement
Securite
Règles de sécurité pour la barre d'outils de développement, le client PostHog et les feature flags. À utiliser lors de la revue de modifications des composants dev-tools et connexes.