Безопасность Notion API: токены, OAuth2, минимальные права, доступ к страницам.

Звёзды2 926
Авторjeremylongshore

Установка

SKILL.md

Notion Security Basics

Overview

Security fundamentals for the Notion API: integration token management, internal vs public integration models, principle of least privilege for capabilities, page-level access auditing, token rotation, OAuth2 flows for public integrations, and webhook verification. All examples use @notionhq/client v2.x and target the 2022-06-28 API version.

This SKILL.md gives you the workflow at a high level with the essential skeletons inline. Drill into the linked references for the full code:

  • Token storage, secret scanning, and access auditing — Step 1 + Step 2 in full
  • Token rotation, OAuth2, and webhook verification — Step 3 in full
  • Worked examples — dual-integration .env + startup validation script

Prerequisites

  • Notion integration created at notion.so/my-integrations
  • Node.js 18+ with @notionhq/client installed (npm install @notionhq/client)
  • Understanding of environment variables and .env file patterns
  • For public integrations: OAuth2 client ID and secret from the integration dashboard

Instructions

Step 1: Secure Token Storage and .env Management

Integration tokens are secrets with the same sensitivity as database passwords. Notion tokens use the ntn_ prefix (current) or secret_ prefix (legacy). Both grant full access to every page shared with the integration. Two rules: never hardcode a token, and gitignore every .env variant BEFORE creating one.

Load from the environment and validate the token format before use:

import { Client } from '@notionhq/client';

const token = process.env.NOTION_TOKEN;
if (!token) throw new Error('NOTION_TOKEN is required (see notion.so/my-integrations).');
if (!token.startsWith('ntn_') && !token.startsWith('secret_')) {
  throw new Error('NOTION_TOKEN has an unexpected format (expected ntn_ or legacy secret_).');
}

const notion = new Client({ auth: token });

Add a CI secret-scan step (grep -rE "(ntn_|secret_)[a-zA-Z0-9]{30,}") so an accidentally committed token fails the build. Full .gitignore patterns, the .env.example template, and the complete GitHub Actions workflow are in token storage, secret scanning, and access auditing.

Step 2: Least-Privilege Capabilities and Access Auditing

Configure integration capabilities at the integration dashboard. Each integration should request only the capabilities it actually uses — grant "Read content" to a dashboard, never "Insert/Update"; keep "Read user info (with email)" off unless you truly look up users by email.

Split responsibilities across separate integrations (a read-only acme-reader, a mutating acme-writer) so a leaked reader token cannot write. Audit access with an empty-query notion.search(), which returns every page and database the integration can reach:

const response = await notion.search({ page_size: 100 });
// paginate on response.has_more / response.next_cursor to list all accessible objects

Remember the sharing hierarchy: sharing a parent cascades to children; sharing a child does not expose its parent; and the API returns object_not_found for both missing and unshared pages (intentional, to prevent leakage). The full capability matrix, the dual-client example, and the complete pagination-safe auditIntegrationAccess() function are in token storage, secret scanning, and access auditing.

Step 3: Token Rotation, OAuth2, and Webhook Verification

Rotation (internal integrations): regenerating the secret at the dashboard immediately invalidates the old token, so update your secrets manager (AWS Secrets Manager / GCP Secret Manager / Vault) and restart services FIRST, then verify with curl .../v1/users/me. No separate revocation step is needed.

OAuth2 (public integrations): distribute to other workspaces via the authorization-code flow — redirect to /v1/oauth/authorize with a CSRF state, then exchange the code at /v1/oauth/token using HTTP Basic auth (client_id:client_secret) and store the returned per-workspace access_token encrypted (never in a cookie).

Webhooks: answer the url_verification challenge during setup, validate every payload's shape, respond 200 immediately, and process the event asynchronously.

Full multi-provider rotation commands, the complete Express OAuth2 handlers, and the hardened webhook endpoint are in token rotation, OAuth2, and webhook verification.

Output

After applying this skill:

  • Integration tokens stored in environment variables, never in source code
  • .gitignore configured to exclude all .env variants
  • Git secret scanning workflow catches accidental token commits
  • Integration capabilities set to the minimum required for each role
  • Page access audited — you know exactly which pages the integration can reach
  • Token rotation procedure documented with cloud provider commands
  • OAuth2 flow implemented for public integrations (if applicable)
  • Webhook endpoint validates payloads and responds asynchronously

Error Handling

Security IssueDetectionMitigation
Token committed to gitCI secret scan, git log -p -S 'ntn_'Rotate immediately, rewrite git history with git filter-repo
Over-privileged integrationCapability audit at dashboardCreate new integration with minimal capabilities, migrate
Stale access to removed pagesAccess audit script returns unexpected pagesRevoke page sharing, re-audit
Token never rotatedTrack created_time of integrationSchedule quarterly rotation, automate with secrets manager
OAuth state mismatchCSRF validation in callbackReject the request, log the attempt
Webhook replay attacksDuplicate event IDsTrack processed event IDs, skip duplicates

Examples

The essential skeleton — load a validated token and audit its reach — appears inline in Steps 1 and 2 above. For a complete, copy-ready setup see worked examples, which covers:

  • A full .env for a dual-integration (reader/writer) architecture with OAuth2 vars
  • A validate-notion-config.ts startup script that fails fast on missing env vars, an invalid/expired token (unauthorized), or an unshared database (object_not_found)

Resources

  • Notion API Authorization — token types, OAuth2 flow, scopes
  • Create a Notion Integration — capabilities configuration
  • API Key Best Practices — storage and rotation
  • @notionhq/client npm — official SDK documentation
  • Notion API Reference — full endpoint reference

Next Steps

For production deployment checklists, see notion-prod-checklist. For rate limit handling and retry strategies, see notion-rate-limits. For enterprise RBAC patterns with Notion, see notion-enterprise-rbac.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: notion-security-basics](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-notion-security-basics)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Code Revieweraffaan-m · Эксперт по ревью кода. Проактивно проверяет код на качество, безопасность и…
225 587 ★
Csharp Revieweraffaan-m · Ревьюер C#: конвенции .NET, async, безопасность, nullable-типы, производительность.
225 587 ★
Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
225 587 ★
Django Revieweraffaan-m · Ревьюер Django: ORM, DRF, миграции, безопасность и production-практики.
225 587 ★
Fastapi Revieweraffaan-m · Проверяет FastAPI-приложения: async, DI, Pydantic, безопасность, OpenAPI и тесты.
225 587 ★
Java Revieweraffaan-m · Ревьюер Java для Spring Boot и Quarkus: архитектура, JPA, безопасность и конкурентность.
225 587 ★
Network Config Revieweraffaan-m · Проверяет конфигурации роутеров и свитчей: безопасность, ошибки и риски изменений.
225 587 ★
Php Revieweraffaan-m · Ревьюер PHP: PSR-12, типы, Eloquent, безопасность и производительность.
225 587 ★
Python Revieweraffaan-m · Ревьюер Python: PEP 8, идиомы, аннотации типов, безопасность и производительность.
225 587 ★
React Revieweraffaan-m · Ревьюер React/JSX: хуки, производительность, границы компонентов и безопасность.
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8