К основному содержанию
скилл CX Codex GP ChatGPT официальный · OpenAI

supabase — скилл для Codex: что делает и как установить

Скилл помогает настраивать базу данных, аутентификацию и RLS в Supabase без скрытых дыр в безопасности.

Установить в Codex · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add openai/plugins --skill supabase -a codex
Открыть на GitHub

Что делает supabase

Скилл задаёт правила для агента при работе со службами Supabase. Он требует проверять свежий чейнджлог перед правками. Сигнатуры функций и параметры config.toml часто меняются между версиями. После любых правок агент обязан запускать проверочный запрос.

Внутри собраны требования по безопасности. Правила запрещают использовать user_metadata в JWT для авторизации. Таблицы в схеме public необходимо закрывать через RLS. Скилл указывает на частые ошибки в Postgres: для операции UPDATE нужно правило SELECT, а функции SECURITY DEFINER обходят RLS. Если агент упирается в ошибку после двух или трех попыток, скилл заставляет сменить подход, а не повторять команду.

Ставить расширение стоит тем, кто строит бэкенд на Supabase и хочет избежать утечек данных через неверный RLS.

Какие задачи решает

  • закрыть публичные таблицы политиками RLS
  • настроить авторизацию без уязвимостей в JWT
  • исправить неработающий UPDATE в политиках безопасности
  • проверить права доступа к Data API для ролей базы

Примеры запросов агенту

  • Напиши RLS политику для таблицы profiles в Supabase
  • Проверь безопасность функции SECURITY DEFINER в схеме public
  • Создай миграцию с расширением pg_vector и настрой права доступа

Как установить supabase

1Через Skills CLI (Vercel)

npx skills add openai/plugins --skill supabase -a codex

2Вручную: положить файлы

.agents/skills/supabase/SKILL.md

Для всех проектов — ~/.agents/skills/

Из того же набора201

Весь набор →
remotion-render официальный Remotion Экспортирует видео и отдельные кадры из проектов Remotion через консольные команды. CX Codex GP ChatGPT 3установок figma-create-new-file официальный Figma Создаёт пустые файлы Figma, FigJam или Slides в черновиках нужной команды. Скилл готовит параметры и planKey перед запуском MCP-инструментов. CX Codex GP ChatGPT 6установок swiftui-performance-audit официальный OpenAI Находит причины просадок кадров, долгого рендеринга и утечек памяти в SwiftUI. Помогает разобрать код вьюшек или подготовить замеры для профилирования. CX Codex GP ChatGPT 109установок swiftui-liquid-glass официальный OpenAI Скилл помогает создавать и проверять интерфейсы SwiftUI с Liquid Glass для iOS 26+. Он нужен при внедрении эффекта, ревью и проверке fallback-сценариев. CX Codex GP ChatGPT 121установок swiftui-ui-patterns официальный OpenAI Скилл помогает собирать и рефакторить SwiftUI-интерфейсы: навигацию, состояние, компоновку и контролы. Подойдёт для новых экранов и правок существующего проекта. CX Codex GP ChatGPT 114установок swiftui-view-refactor официальный OpenAI Скилл наводит порядок в коде SwiftUI: делит разросшиеся экраны на отдельные структуры View и выносит побочные эффекты из body. CX Codex GP ChatGPT 113установок ios-memgraph-leaks официальный OpenAI Скилл захватывает и разбирает утечки памяти iOS из симулятора или .memgraph. Нужен для поиска удерживающих связей и проверки исправлений. CX Codex GP ChatGPT 1 054установок status официальный Vercel Labs Проверяет состояние проекта Vercel, последние деплои, домены и настройки наблюдаемости прямо через диалог с моделью. CX Codex GP ChatGPT 348установок

Похожие

migration JuliusBrussee Скилл задаёт правила безопасных миграций схем, данных и API с обязательным откатом. Пригодится при изменениях, где нельзя терять данные или ломать совместимость. Claude Code CX Codex Cursor +1 102 900установок caveman-setup JuliusBrussee Перенаправляет вызовы LLM в репозитории через шлюз Caveman Cloud для замера расходов без изменения логики приложения. Пригодится для мониторинга трат на нейросети. Claude Code CX Codex Cursor +1 102 500установок performance-optimization addyosmani Скилл для агентов ИИ-кодинга: сначала замеряет, потом чинит узкое место — от Core Web Vitals до N+1 запросов и индексов в базе. Claude Code CX Codex Cursor +1 64 500установок api-and-interface-design addyosmani Помогает проектировать API и границы модулей так, чтобы их было проще использовать и менять. Подходит для REST, GraphQL и публичных интерфейсов. Claude Code CX Codex Cursor +1 61 900установок ai-sdk vercel Скилл помогает писать код на базе Vercel AI SDK и не допускать устаревших API. Он проверяет локальную документацию пакета перед генерацией. Claude Code CX Codex Cursor +1 66 000установок observability-and-instrumentation addyosmani Скилл учит агента добавлять структурированные логи, метрики и трейсы в код до деплоя. Пригодится при выпуске новых эндпоинтов, фоновых задач и интеграций. Claude Code CX Codex Cursor +1 54 200установок mcp-builder официальный anthropics Скилл проводит через создание MCP-сервера на TypeScript или Python: от изучения протокола до тестов и оценки качества. Claude Code Claude.ai 130 949установок google-agents-cli-adk-code официальный Google Скилл даёт примеры и справку по Agent Development Kit: агентам, инструментам, колбэкам, состоянию и графовым workflow. Нужен при написании кода. Claude Code CX Codex Cursor +1 511 400установок

Вопросы о supabase

Как установить supabase в Codex?

Установите скилл командой npx skills add openai/plugins --skill supabase в терминале проекта.

Что делает скилл supabase?

Он инструктирует ИИ проверять чейнджлоги, тестировать изменения и следовать правилам безопасности при настройке базы.

Почему скилл запрещает user_metadata для проверок доступа?

Поле raw_user_meta_data может менять сам пользователь, поэтому доверять ему в политиках нельзя. Для авторизации нужно сохранять данные в app_metadata.

Исходный текст

SKILL.md · MIT
---
name: supabase
description: "Use when doing ANY task involving Supabase. Triggers: Supabase products (Database, Auth, Edge Functions, Realtime, Storage, Vectors, Cron, Queues); client libraries and SSR integrations (supabase-js, @supabase/ssr) in Next.js, React, SvelteKit, Astro, Remix; auth issues (login, logout, sessions, JWT, cookies, getSession, getUser, getClaims, RLS); Supabase CLI or MCP server; schema changes, migrations, security audits, Postgres extensions (pg_graphql, pg_cron, pg_vector)."
metadata:
  author: supabase
  version: "0.1.2"
---

# Supabase

## Core Principles

**1. Supabase changes frequently — verify against changelog and current docs before implementing.**
Do not rely on training data for Supabase features. Function signatures, config.toml settings, and API conventions change between versions.

First, fetch `https://supabase.com/changelog.md` (a lightweight summary index — not a heavy pull), scan for `breaking-change` tags relevant to your task, and follow the linked page for any that apply. Then look up the relevant topic using the documentation access methods below.

**2. Verify your work.**
After implementing any fix, run a test query to confirm the change works. A fix without verification is incomplete.

**3. Recover from errors, don't loop.**
If an approach fails after 2-3 attempts, stop and reconsider. Try a different method, check documentation, inspect the error more carefully, and review relevant logs when available. Supabase issues are not always solved by retrying the same command, and the answer is not always in the logs, but logs are often worth checking before proceeding.

**4. Exposing tables to the Data API:** Depending on the user's [Data API settings](https://supabase.com/dashboard/project/<ref>/integrations/data_api/settings), newly created tables may not be automatically exposed via the Data (REST) API. If this is the case, `anon` and `authenticated` roles will need to be explicitly granted access.

> Note that this is separate from RLS, which controls which _rows_ are visible once a table is accessible, not whether the table is accessible at all.

When a user reports a SQL-created table is unexpectedly inaccessible, check their Data API settings and whether the roles have been granted access via explicit `GRANT` SQL. When granting public (`anon`/`authenticated`) access, always enable RLS too. See [Exposing a Table to the Data API](https://supabase.com/docs/guides/api/securing-your-api.md) for the full setup workflow.

**5. RLS in exposed schemas.**
Enable RLS on every table in any exposed schema, which includes `public` by default. This is critical in Supabase because tables in exposed schemas can be reachable through the Data API when the `anon`/`authenticated` roles have access (see [Exposing a Table to the Data API](https://supabase.com/docs/guides/api/securing-your-api.md)). For private schemas, prefer RLS as defense in depth. After enabling RLS, create policies that match the actual access model rather than defaulting every table to the same `auth.uid()` pattern.

**6. Security checklist.**
When working on any Supabase task that touches auth, RLS, views, storage, or user data, run through this checklist. These are Supabase-specific security traps that silently create vulnerabilities:

- **Auth and session security**
  - **Never use `user_metadata` claims in JWT-based authorization decisions.** In Supabase, `raw_user_meta_data` is user-editable and can appear in `auth.jwt()`, so it is unsafe for RLS policies or any other authorization logic. Store authorization data in `raw_app_meta_data` / `app_metadata` instead.
  - **Deleting a user does not invalidate existing access tokens.** Sign out or revoke sessions first, keep JWT expiry short for sensitive apps, and for strict guarantees validate `session_id` against `auth.sessions` on sensitive operations.
  - **If you use `app_metadata` or `auth.jwt()` for authorization, remember JWT claims are not always fresh until the user's token is refreshed.**

- **API key and client exposure**
  - **Never expose the `service_role` or secret key in public clients.** Prefer publishable keys for frontend code. Legacy `anon` keys are only for compatibility. In Next.js, any `NEXT_PUBLIC_` env var is sent to the browser.

- **RLS, views, and privileged database code**
  - **Views bypass RLS by default.** In Postgres 15 and above, use `CREATE VIEW ... WITH (security_invoker = true)`. In older versions of Postgres, protect your views by revoking access from the `anon` and `authenticated` roles, or by putting them in an unexposed schema.
  - **UPDATE requires a SELECT policy.** In Postgres RLS, an UPDATE needs to first SELECT the row. Without a SELECT policy, updates silently return 0 rows — no error, just no change.
  - **`auth.role()` is deprecated — use the `TO` clause instead.** Supabase has deprecated `auth.role()` in favour of specifying the target role directly on the policy with `TO authenticated` or `TO anon`. Beyond deprecation, `auth.role() = 'authenticated'` breaks silently when anonymous sign-ins are enabled, because anonymous users carry the `authenticated` Postgres role and pass the check regardless of whether the user is genuinely signed in.
    ```sql
    -- Deprecated (do not use)
    create policy "example" on table_name for select
    using ( auth.role() = 'authenticated' );
    ```
  - **`TO authenticated` alone is authentication without authorization (BOLA / IDOR).** Using `TO authenticated` only checks the role — it does not restrict which rows a user can access. The correct pattern combines `TO authenticated` with an ownership predicate in `USING`:
    ```sql
    create policy "example" on table_name for select
    to authenticated
    using ( (select auth.uid()) = user_id );
    ```
  - **UPDATE policies require both `USING` and `WITH CHECK`.** Without `WITH CHECK`, a user can reassign a row's `user_id` to another user:
    ```sql
    create policy "example" on table_name for update
    to authenticated
    using ( (select auth.uid()) = user_id )
    with check ( (select auth.uid()) = user_id );
    ```
  - **`SECURITY DEFINER` functions bypass RLS.** A `SECURITY DEFINER` function runs with its creator's privileges — typically a role with `bypassrls` (e.g., `postgres`). Never add `SECURITY DEFINER` to resolve a permission error; it silently removes access control without fixing the underlying cause. Prefer `SECURITY INVOKER`.
  - **`SECURITY DEFINER` functions in `public` are callable by all roles.** Postgres grants `EXECUTE` to `PUBLIC` by default for every new function, so any `SECURITY DEFINER` function in `public` is a public API endpoint callable by `anon` and `authenticated` (which inherit from `PUBLIC`) without any additional grant. When `SECURITY DEFINER` is genuinely needed (e.g., bypassing RLS on an internal lookup table), keep the function in a non-exposed schema, always include an `auth.uid()` check in the function body, and run `supabase db advisors` after making changes.

- **Storage access control**
  - **Storage upsert requires INSERT + SELECT + UPDATE.** Granting only INSERT allows new uploads but file replacement (upsert) silently fails. You need all three.

- **Dependency and supply-chain security**
  - **Always pin package versions and commit lockfiles** when installing Supabase packages (`supabase-js`, `@supabase/ssr`, `supabase-py`, etc.). See the [npm security guide](https://supabase.com/docs/guides/security/npm-security.md) for the full checklist.

For any security concern not covered above, fetch the Supabase product security index: `https://supabase.com/docs/guides/security/product-security.md`

## Supabase CLI

Always discover commands via `--help` — never guess. The CLI structure changes between versions.

```bash
supabase --help                    # All top-level commands
supabase <group> --help            # Subcommands (e.g., supabase db --help)
supabase <group> <command> --help  # Flags for a specific command
```

**Supabase CLI Known gotchas:**

- `supabase db query` requires **CLI v2.79.0+** → use MCP `execute_sql` or `psql` as fallback
- `supabase db advisors` requires **CLI v2.81.3+** → use MCP `get_advisors` as fallback
- When you need a new migration SQL file, **always** create it with `supabase migration new <name>` first. Never invent a migration filename or rely on memory for the expected format.

**Version check and upgrade:** Run `supabase --version` to check. For CLI changelogs and version-specific features, consult the [CLI documentation](https://supabase.com/docs/reference/cli/introduction) or [GitHub releases](https://github.com/supabase/cli/releases).

## Supabase MCP Server

For setup instructions, server URL, and configuration, see the [MCP setup guide](https://supabase.com/docs/guides/getting-started/mcp).

**Troubleshooting connection issues** — follow these steps in order:

1. **Check if the server is reachable:**
   `curl -so /dev/null -w "%{http_code}" https://mcp.supabase.com/mcp`
   A `401` is expected (no token) and means the server is up. Timeout or "connection refused" means it may be down.

2. **Check `.mcp.json` configuration:**
   Verify the project root has a valid `.mcp.json` with the correct server URL. If missing, create one pointing to `https://mcp.supabase.com/mcp`.

3. **Authenticate the MCP server:**
   If the server is reachable and `.mcp.json` is correct but tools aren't visible, the user needs to authenticate. The Supabase MCP server uses OAuth 2.1 — tell the user to trigger the auth flow in their agent, complete it in the browser, and reload the session.

## Supabase Documentation

Before implementing any Supabase feature, find the relevant documentation. Use these methods in priority order:

1. **MCP `search_docs` tool** (preferred — returns relevant snippets directly)
2. **Fetch docs pages as markdown** — any docs page can be fetched by appending `.md` to the URL path.
3. **Web search** for Supabase-specific topics when you don't know which page to look at.

## Making and Committing Schema Changes

**To make schema changes, use `execute_sql` (MCP) or `supabase db query` (CLI).** These run SQL directly on the database without creating migration history entries, so you can iterate freely and generate a clean migration when ready.

Do NOT use `apply_migration` to change a local database schema — it writes a migration history entry on every call, which means you can't iterate, and `supabase db diff` / `supabase db pull` will produce empty or conflicting diffs. If you use it, you'll be stuck with whatever SQL you passed on the first try.

**When ready to commit** your changes to a migration file:

1. **Run advisors** → `supabase db advisors` (CLI v2.81.3+) or MCP `get_advisors`. Fix any issues.
2. **Review the Security Checklist above** if your changes involve views, functions, triggers, or storage.
3. **Generate the migration** → `supabase db pull <descriptive-name> --local --yes`
4. **Verify** → `supabase migration list --local`

## Reference Guides

- **Skill Feedback** → [references/skill-feedback.md](references/skill-feedback.md)
  **MUST read when** the user reports that this skill gave incorrect guidance or is missing information.

© supabase · MIT · openai/plugins

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой