[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M793JY7B7DNAMGRBFZBE07K5":3,"skill-same:01M793JY7B7DNAMGRBFZBE07K5":56},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":33,"commitSha":34,"skillDirectory":35,"forksCount":36,"repositoryHtmlUrl":37,"repositoryHomepageUrl":6,"ownerHtmlUrl":38,"ownerBlogUrl":39,"ownerDescription":40,"updatedAt":41,"install":42,"resources":55},"01M793JY7B7DNAMGRBFZBE07K5","notion-enterprise-rbac",null,"Configure Notion enterprise access control with OAuth, workspace permissions, and audit logging.\nUse when implementing OAuth public integrations, managing multi-workspace access,\nor building permission-aware Notion applications.\nTrigger with phrases like \"notion SSO\", \"notion RBAC\",\n\"notion enterprise\", \"notion OAuth\", \"notion permissions\", \"notion multi-workspace\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--notion-pack--notion-enterprise-rbac\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: notion-enterprise-rbac\ndescription: |\n  Configure Notion enterprise access control with OAuth, workspace permissions, and audit logging.\n  Use when implementing OAuth public integrations, managing multi-workspace access,\n  or building permission-aware Notion applications.\n  Trigger with phrases like \"notion SSO\", \"notion RBAC\",\n  \"notion enterprise\", \"notion OAuth\", \"notion permissions\", \"notion multi-workspace\".\nallowed-tools: Read, Write, Edit\nversion: 1.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, productivity, notion]\ncompatible-with: claude-code\n---\n\n# Notion Enterprise RBAC\n\n## Overview\n\nImplement enterprise-grade access control for Notion integrations. This covers the full OAuth 2.0 authorization flow for public integrations (multi-tenant), per-workspace token storage with encryption at rest, Notion's page-level permission model and how to handle `ObjectNotFound` vs `RestrictedResource`, an application-level role system (admin\u002Feditor\u002Fviewer) layered on top of Notion's permissions, comprehensive audit logging to a Notion database, and workspace deauthorization cleanup.\n\n## Prerequisites\n\n- Notion public integration created at https:\u002F\u002Fwww.notion.so\u002Fmy-integrations (for OAuth)\n- `@notionhq\u002Fclient` v2+ installed (`npm install @notionhq\u002Fclient`)\n- Python alternative: `notion-client` (`pip install notion-client`)\n- Database for storing per-workspace tokens (PostgreSQL, DynamoDB, etc.)\n- HTTPS endpoint for OAuth callback (required by Notion)\n\n## Instructions\n\n### Step 1: OAuth 2.0 Authorization Flow\n\nNotion uses OAuth 2.0 for public integrations to access external workspaces:\n\n```typescript\nimport { Client } from '@notionhq\u002Fclient';\nimport crypto from 'crypto';\n\n\u002F\u002F Step 1: Build the authorization URL\nfunction getAuthorizationUrl(state: string): string {\n  const params = new URLSearchParams({\n    client_id: process.env.NOTION_OAUTH_CLIENT_ID!,\n    response_type: 'code',\n    owner: 'user',       \u002F\u002F 'user' = user-level token, 'workspace' = workspace-level\n    redirect_uri: process.env.NOTION_REDIRECT_URI!,\n    state,               \u002F\u002F CSRF protection — must verify on callback\n  });\n  return `https:\u002F\u002Fapi.notion.com\u002Fv1\u002Foauth\u002Fauthorize?${params}`;\n}\n\n\u002F\u002F Step 2: Exchange authorization code for access token\nasync function exchangeCodeForToken(code: string): Promise\u003C{\n  access_token: string;\n  bot_id: string;\n  workspace_id: string;\n  workspace_name: string;\n  workspace_icon: string | null;\n  owner: { type: string; user?: { id: string; name: string } };\n  duplicated_template_id: string | null;\n}> {\n  const credentials = Buffer.from(\n    `${process.env.NOTION_OAUTH_CLIENT_ID}:${process.env.NOTION_OAUTH_CLIENT_SECRET}`\n  ).toString('base64');\n\n  const response = await fetch('https:\u002F\u002Fapi.notion.com\u002Fv1\u002Foauth\u002Ftoken', {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      Authorization: `Basic ${credentials}`,\n    },\n    body: JSON.stringify({\n      grant_type: 'authorization_code',\n      code,\n      redirect_uri: process.env.NOTION_REDIRECT_URI,\n    }),\n  });\n\n  if (!response.ok) {\n    const error = await response.json();\n    throw new Error(`OAuth token exchange failed: ${error.error}`);\n  }\n\n  return response.json();\n}\n\n\u002F\u002F Step 3: Create a Client for a specific workspace\nfunction createWorkspaceClient(accessToken: string): Client {\n  return new Client({ auth: accessToken, timeoutMs: 30_000 });\n}\n\n\u002F\u002F Express route handlers\napp.get('\u002Fauth\u002Fnotion', (req, res) => {\n  const state = crypto.randomUUID();\n  req.session.oauthState = state;\n  res.redirect(getAuthorizationUrl(state));\n});\n\napp.get('\u002Fauth\u002Fnotion\u002Fcallback', async (req, res) => {\n  \u002F\u002F Verify CSRF state\n  if (req.query.state !== req.session.oauthState) {\n    return res.status(403).send('Invalid state — possible CSRF attack');\n  }\n\n  if (req.query.error) {\n    return res.status(400).send(`Authorization denied: ${req.query.error}`);\n  }\n\n  const tokenData = await exchangeCodeForToken(req.query.code as string);\n  await storeWorkspaceToken(tokenData);\n\n  res.redirect(`\u002Fdashboard?workspace=${encodeURIComponent(tokenData.workspace_name)}`);\n});\n```\n\n**Python — OAuth flow:**\n\n```python\nimport base64\nimport requests\nfrom notion_client import Client\n\ndef exchange_code_for_token(code: str) -> dict:\n    credentials = base64.b64encode(\n        f\"{os.environ['NOTION_OAUTH_CLIENT_ID']}:{os.environ['NOTION_OAUTH_CLIENT_SECRET']}\".encode()\n    ).decode()\n\n    response = requests.post(\n        \"https:\u002F\u002Fapi.notion.com\u002Fv1\u002Foauth\u002Ftoken\",\n        headers={\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Basic {credentials}\",\n        },\n        json={\n            \"grant_type\": \"authorization_code\",\n            \"code\": code,\n            \"redirect_uri\": os.environ[\"NOTION_REDIRECT_URI\"],\n        },\n    )\n    response.raise_for_status()\n    return response.json()\n\ndef create_workspace_client(access_token: str) -> Client:\n    return Client(auth=access_token, timeout_ms=30_000)\n```\n\n### Step 2: Token Storage and Permission-Aware API Calls\n\n**Per-workspace token management:**\n\n```typescript\nimport { isNotionClientError, APIErrorCode } from '@notionhq\u002Fclient';\n\ninterface WorkspaceToken {\n  botId: string;          \u002F\u002F Primary key — unique per installation\n  workspaceId: string;\n  workspaceName: string;\n  accessToken: string;    \u002F\u002F MUST be encrypted at rest\n  ownerUserId: string;\n  authorizedAt: Date;\n  lastUsedAt: Date;\n}\n\n\u002F\u002F In production, use a database with encryption (e.g., AWS KMS, column-level encryption)\nclass TokenStore {\n  private tokens = new Map\u003Cstring, WorkspaceToken>();\n\n  async store(tokenData: any): Promise\u003Cvoid> {\n    const entry: WorkspaceToken = {\n      botId: tokenData.bot_id,\n      workspaceId: tokenData.workspace_id,\n      workspaceName: tokenData.workspace_name,\n      accessToken: tokenData.access_token,  \u002F\u002F Encrypt before storing!\n      ownerUserId: tokenData.owner?.user?.id ?? '',\n      authorizedAt: new Date(),\n      lastUsedAt: new Date(),\n    };\n    this.tokens.set(entry.botId, entry);\n  }\n\n  async getClient(botId: string): Promise\u003CClient> {\n    const token = this.tokens.get(botId);\n    if (!token) {\n      throw new Error(`No token found for bot ${botId}. User needs to re-authorize.`);\n    }\n    token.lastUsedAt = new Date();\n    return new Client({ auth: token.accessToken, timeoutMs: 30_000 });\n  }\n\n  async revoke(botId: string): Promise\u003Cvoid> {\n    this.tokens.delete(botId);\n  }\n\n  async listWorkspaces(): Promise\u003C{ botId: string; name: string; authorizedAt: Date }[]> {\n    return Array.from(this.tokens.values()).map(t => ({\n      botId: t.botId,\n      name: t.workspaceName,\n      authorizedAt: t.authorizedAt,\n    }));\n  }\n}\n\nconst tokenStore = new TokenStore();\n```\n\n**Permission-aware API calls — handle Notion's page-level permissions:**\n\n```typescript\n\u002F\u002F Notion returns ObjectNotFound for pages not shared with the integration\n\u002F\u002F This is NOT the same as the page being deleted\nasync function safePageAccess(notion: Client, pageId: string) {\n  try {\n    return await notion.pages.retrieve({ page_id: pageId });\n  } catch (error) {\n    if (!isNotionClientError(error)) throw error;\n\n    switch (error.code) {\n      case APIErrorCode.ObjectNotFound:\n        \u002F\u002F Page exists but is NOT shared with this integration\n        \u002F\u002F User needs to share it via the \"...\" menu > Connections\n        console.log(`Page ${pageId} not accessible. Ask user to share via Connections.`);\n        return null;\n\n      case APIErrorCode.RestrictedResource:\n        \u002F\u002F Integration lacks the required capability (read\u002Fupdate\u002Finsert\u002Fdelete)\n        console.log(`Integration lacks capability for ${pageId}. Check integration settings.`);\n        return null;\n\n      case APIErrorCode.Unauthorized:\n        \u002F\u002F Token was revoked — user needs to re-authorize\n        console.log(`Token revoked. User needs to re-authorize.`);\n        return null;\n\n      default:\n        throw error;\n    }\n  }\n}\n\n\u002F\u002F List all pages accessible to the integration (discovers shared content)\nasync function discoverAccessiblePages(notion: Client): Promise\u003Cstring[]> {\n  const pageIds: string[] = [];\n  let cursor: string | undefined;\n\n  do {\n    const response = await notion.search({\n      filter: { property: 'object', value: 'page' },\n      page_size: 100,\n      start_cursor: cursor,\n    });\n    pageIds.push(...response.results.map(r => r.id));\n    cursor = response.has_more ? response.next_cursor ?? undefined : undefined;\n  } while (cursor);\n\n  return pageIds;\n}\n```\n\n### Step 3: Application-Level Roles and Audit Logging\n\n**Role-based access control layered on top of Notion permissions:**\n\n```typescript\nenum AppRole {\n  Admin = 'admin',\n  Editor = 'editor',\n  Viewer = 'viewer',\n}\n\nconst ROLE_PERMISSIONS: Record\u003CAppRole, {\n  canRead: boolean;\n  canWrite: boolean;\n  canDelete: boolean;\n  canManageIntegration: boolean;\n}> = {\n  admin:  { canRead: true, canWrite: true, canDelete: true, canManageIntegration: true },\n  editor: { canRead: true, canWrite: true, canDelete: false, canManageIntegration: false },\n  viewer: { canRead: true, canWrite: false, canDelete: false, canManageIntegration: false },\n};\n\ninterface AppUser {\n  id: string;\n  email: string;\n  role: AppRole;\n  workspaceBotId: string;  \u002F\u002F Links to stored workspace token\n}\n\nfunction checkPermission(user: AppUser, action: 'read' | 'write' | 'delete' | 'manage'): boolean {\n  const perms = ROLE_PERMISSIONS[user.role];\n  switch (action) {\n    case 'read': return perms.canRead;\n    case 'write': return perms.canWrite;\n    case 'delete': return perms.canDelete;\n    case 'manage': return perms.canManageIntegration;\n  }\n}\n\n\u002F\u002F Express middleware\nfunction requirePermission(action: 'read' | 'write' | 'delete' | 'manage') {\n  return (req: any, res: any, next: any) => {\n    if (!checkPermission(req.user, action)) {\n      auditLog({\n        userId: req.user.id,\n        workspaceId: req.user.workspaceBotId,\n        action: `${action}_denied`,\n        resource: { type: 'endpoint', id: req.path },\n        result: 'denied',\n      });\n      return res.status(403).json({ error: `Requires \"${action}\" permission` });\n    }\n    next();\n  };\n}\n\n\u002F\u002F Route examples\napp.get('\u002Fapi\u002Fpages\u002F:id', requirePermission('read'), async (req, res) => {\n  const notion = await tokenStore.getClient(req.user.workspaceBotId);\n  const page = await safePageAccess(notion, req.params.id);\n  res.json(page);\n});\n\napp.post('\u002Fapi\u002Fpages', requirePermission('write'), async (req, res) => {\n  const notion = await tokenStore.getClient(req.user.workspaceBotId);\n  const page = await notion.pages.create(req.body);\n  res.json(page);\n});\n```\n\n**Audit logging — write to structured logs and optionally to a Notion database:**\n\n```typescript\ninterface AuditEntry {\n  timestamp: string;\n  userId: string;\n  workspaceId: string;\n  action: string;\n  resource: { type: string; id: string };\n  result: 'success' | 'denied' | 'error';\n  metadata?: Record\u003Cstring, unknown>;\n}\n\nasync function auditLog(entry: Omit\u003CAuditEntry, 'timestamp'>): Promise\u003Cvoid> {\n  const full: AuditEntry = {\n    ...entry,\n    timestamp: new Date().toISOString(),\n  };\n\n  \u002F\u002F Always log to structured logging (searchable in log aggregator)\n  console.log(JSON.stringify({ level: 'audit', ...full }));\n\n  \u002F\u002F Optionally write to a Notion audit database\n  if (process.env.NOTION_AUDIT_DB_ID) {\n    try {\n      const notion = await tokenStore.getClient(entry.workspaceId);\n      await notion.pages.create({\n        parent: { database_id: process.env.NOTION_AUDIT_DB_ID },\n        properties: {\n          Action: { title: [{ text: { content: entry.action } }] },\n          User: { rich_text: [{ text: { content: entry.userId } }] },\n          Result: { select: { name: entry.result } },\n          Resource: {\n            rich_text: [{ text: { content: `${entry.resource.type}:${entry.resource.id}` } }],\n          },\n          Timestamp: { date: { start: full.timestamp } },\n        },\n      });\n    } catch (error) {\n      \u002F\u002F Audit log writes should never crash the application\n      console.error('Failed to write audit log to Notion:', error);\n    }\n  }\n}\n\n\u002F\u002F Handle workspace deauthorization (user removes integration)\nasync function handleDeauthorization(botId: string): Promise\u003Cvoid> {\n  const workspaces = await tokenStore.listWorkspaces();\n  const workspace = workspaces.find(w => w.botId === botId);\n\n  if (workspace) {\n    await auditLog({\n      userId: 'system',\n      workspaceId: botId,\n      action: 'workspace_deauthorized',\n      resource: { type: 'workspace', id: botId },\n      result: 'success',\n      metadata: { workspaceName: workspace.name },\n    });\n\n    await tokenStore.revoke(botId);\n  }\n}\n```\n\n## Output\n\n- Complete OAuth 2.0 flow for multi-workspace access (TypeScript + Python)\n- Per-workspace token storage with encryption guidance\n- Permission-aware API calls handling ObjectNotFound vs RestrictedResource\n- Content discovery via `search` endpoint\n- Application-level role system (admin\u002Feditor\u002Fviewer) with Express middleware\n- Comprehensive audit logging to structured logs and optionally to Notion database\n- Workspace deauthorization cleanup handler\n\n## Error Handling\n\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| OAuth callback fails | Redirect URI mismatch | Must match exactly in integration settings (including trailing slash) |\n| `invalid_grant` on token exchange | Code expired or already used | Authorization codes are single-use; restart OAuth flow |\n| `ObjectNotFound` on page access | Page not shared with integration | User must share via \"...\" menu > Connections |\n| `RestrictedResource` | Integration missing capability | Edit capabilities at notion.so\u002Fmy-integrations |\n| `Unauthorized` (401) | Token revoked by user | Prompt re-authorization; clean up stored token |\n| State mismatch on callback | CSRF attack or session expired | Reject the callback; redirect to start OAuth again |\n\n## Examples\n\n### Full OAuth Integration (Express)\n\n```typescript\nimport express from 'express';\nimport session from 'express-session';\nimport crypto from 'crypto';\n\nconst app = express();\napp.use(session({ secret: process.env.SESSION_SECRET!, resave: false, saveUninitialized: false }));\n\napp.get('\u002Fauth\u002Fnotion', (req, res) => {\n  const state = crypto.randomUUID();\n  (req.session as any).oauthState = state;\n  res.redirect(getAuthorizationUrl(state));\n});\n\napp.get('\u002Fauth\u002Fnotion\u002Fcallback', async (req, res) => {\n  if (req.query.state !== (req.session as any).oauthState) {\n    return res.status(403).send('Invalid state');\n  }\n  const tokenData = await exchangeCodeForToken(req.query.code as string);\n  await tokenStore.store(tokenData);\n\n  await auditLog({\n    userId: tokenData.owner?.user?.id ?? 'unknown',\n    workspaceId: tokenData.bot_id,\n    action: 'workspace_authorized',\n    resource: { type: 'workspace', id: tokenData.workspace_id },\n    result: 'success',\n  });\n\n  res.redirect(`\u002Fdashboard?workspace=${encodeURIComponent(tokenData.workspace_name)}`);\n});\n\napp.get('\u002Fworkspaces', async (_req, res) => {\n  const workspaces = await tokenStore.listWorkspaces();\n  res.json(workspaces);\n});\n```\n\n## Resources\n\n- [Notion OAuth Authorization](https:\u002F\u002Fdevelopers.notion.com\u002Fdocs\u002Fauthorization) — full OAuth guide\n- [Create a Token (OAuth)](https:\u002F\u002Fdevelopers.notion.com\u002Freference\u002Fcreate-a-token) — token exchange endpoint\n- [Authentication Reference](https:\u002F\u002Fdevelopers.notion.com\u002Freference\u002Fauthentication) — auth header format\n- [Notion Capabilities](https:\u002F\u002Fdevelopers.notion.com\u002Fdocs\u002Fcreate-a-notion-integration#capabilities) — read\u002Fupdate\u002Finsert\u002Fdelete\n- [Sharing and Permissions](https:\u002F\u002Fdevelopers.notion.com\u002Fdocs\u002Fcreate-a-notion-integration#sharing-and-permissions) — page-level model\n\n## Next Steps\n\nFor migrating data to and from Notion, see `notion-migration-deep-dive`.\n","# Notion Enterprise RBAC\n\n## Overview\n\nImplement enterprise-grade access control for Notion integrations. This covers the full OAuth 2.0 authorization flow for public integrations (multi-tenant), per-workspace token storage with encryption at rest, Notion's page-level permission model and how to handle `ObjectNotFound` vs `RestrictedResource`, an application-level role system (admin\u002Feditor\u002Fviewer) layered on top of Notion's permissions, comprehensive audit logging to a Notion database, and workspace deauthorization cleanup.\n\n## Prerequisites\n\n- Notion public integration created at https:\u002F\u002Fwww.notion.so\u002Fmy-integrations (for OAuth)\n- `@notionhq\u002Fclient` v2+ installed (`npm install @notionhq\u002Fclient`)\n- Python alternative: `notion-client` (`pip install notion-client`)\n- Database for storing per-workspace tokens (PostgreSQL, DynamoDB, etc.)\n- HTTPS endpoint for OAuth callback (required by Notion)\n\n## Instructions\n\n### Step 1: OAuth 2.0 Authorization Flow\n\nNotion uses OAuth 2.0 for public integrations to access external workspaces:\n\n```typescript\nimport { Client } from '@notionhq\u002Fclient';\nimport crypto from 'crypto';\n\n\u002F\u002F Step 1: Build the authorization URL\nfunction getAuthorizationUrl(state: string): string {\n  const params = new URLSearchParams({\n    client_id: process.env.NOTION_OAUTH_CLIENT_ID!,\n    response_type: 'code',\n    owner: 'user',       \u002F\u002F 'user' = user-level token, 'workspace' = workspace-level\n    redirect_uri: process.env.NOTION_REDIRECT_URI!,\n    state,               \u002F\u002F CSRF protection — must verify on callback\n  });\n  return `https:\u002F\u002Fapi.notion.com\u002Fv1\u002Foauth\u002Fauthorize?${params}`;\n}\n\n\u002F\u002F Step 2: Exchange authorization code for access token\nasync function exchangeCodeForToken(code: string): Promise\u003C{\n  access_token: string;\n  bot_id: string;\n  workspace_id: string;\n  workspace_name: string;\n  workspace_icon: string | null;\n  owner: { type: string; user?: { id: string; name: string } };\n  duplicated_template_id: string | null;\n}> {\n  const credentials = Buffer.from(\n    `${process.env.NOTION_OAUTH_CLIENT_ID}:${process.env.NOTION_OAUTH_CLIENT_SECRET}`\n  ).toString('base64');\n\n  const response = await fetch('https:\u002F\u002Fapi.notion.com\u002Fv1\u002Foauth\u002Ftoken', {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      Authorization: `Basic ${credentials}`,\n    },\n    body: JSON.stringify({\n      grant_type: 'authorization_code',\n      code,\n      redirect_uri: process.env.NOTION_REDIRECT_URI,\n    }),\n  });\n\n  if (!response.ok) {\n    const error = await response.json();\n    throw new Error(`OAuth token exchange failed: ${error.error}`);\n  }\n\n  return response.json();\n}\n\n\u002F\u002F Step 3: Create a Client for a specific workspace\nfunction createWorkspaceClient(accessToken: string): Client {\n  return new Client({ auth: accessToken, timeoutMs: 30_000 });\n}\n\n\u002F\u002F Express route handlers\napp.get('\u002Fauth\u002Fnotion', (req, res) => {\n  const state = crypto.randomUUID();\n  req.session.oauthState = state;\n  res.redirect(getAuthorizationUrl(state));\n});\n\napp.get('\u002Fauth\u002Fnotion\u002Fcallback', async (req, res) => {\n  \u002F\u002F Verify CSRF state\n  if (req.query.state !== req.session.oauthState) {\n    return res.status(403).send('Invalid state — possible CSRF attack');\n  }\n\n  if (req.query.error) {\n    return res.status(400).send(`Authorization denied: ${req.query.error}`);\n  }\n\n  const tokenData = await exchangeCodeForToken(req.query.code as string);\n  await storeWorkspaceToken(tokenData);\n\n  res.redirect(`\u002Fdashboard?workspace=${encodeURIComponent(tokenData.workspace_name)}`);\n});\n```\n\n**Python — OAuth flow:**\n\n```python\nimport base64\nimport requests\nfrom notion_client import Client\n\ndef exchange_code_for_token(code: str) -> dict:\n    credentials = base64.b64encode(\n        f\"{os.environ['NOTION_OAUTH_CLIENT_ID']}:{os.environ['NOTION_OAUTH_CLIENT_SECRET']}\".encode()\n    ).decode()\n\n    response = requests.post(\n        \"https:\u002F\u002Fapi.notion.com\u002Fv1\u002Foauth\u002Ftoken\",\n        headers={\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Basic {credentials}\",\n        },\n        json={\n            \"grant_type\": \"authorization_code\",\n            \"code\": code,\n            \"redirect_uri\": os.environ[\"NOTION_REDIRECT_URI\"],\n        },\n    )\n    response.raise_for_status()\n    return response.json()\n\ndef create_workspace_client(access_token: str) -> Client:\n    return Client(auth=access_token, timeout_ms=30_000)\n```\n\n### Step 2: Token Storage and Permission-Aware API Calls\n\n**Per-workspace token management:**\n\n```typescript\nimport { isNotionClientError, APIErrorCode } from '@notionhq\u002Fclient';\n\ninterface WorkspaceToken {\n  botId: string;          \u002F\u002F Primary key — unique per installation\n  workspaceId: string;\n  workspaceName: string;\n  accessToken: string;    \u002F\u002F MUST be encrypted at rest\n  ownerUserId: string;\n  authorizedAt: Date;\n  lastUsedAt: Date;\n}\n\n\u002F\u002F In production, use a database with encryption (e.g., AWS KMS, column-level encryption)\nclass TokenStore {\n  private tokens = new Map\u003Cstring, WorkspaceToken>();\n\n  async store(tokenData: any): Promise\u003Cvoid> {\n    const entry: WorkspaceToken = {\n      botId: tokenData.bot_id,\n      workspaceId: tokenData.workspace_id,\n      workspaceName: tokenData.workspace_name,\n      accessToken: tokenData.access_token,  \u002F\u002F Encrypt before storing!\n      ownerUserId: tokenData.owner?.user?.id ?? '',\n      authorizedAt: new Date(),\n      lastUsedAt: new Date(),\n    };\n    this.tokens.set(entry.botId, entry);\n  }\n\n  async getClient(botId: string): Promise\u003CClient> {\n    const token = this.tokens.get(botId);\n    if (!token) {\n      throw new Error(`No token found for bot ${botId}. User needs to re-authorize.`);\n    }\n    token.lastUsedAt = new Date();\n    return new Client({ auth: token.accessToken, timeoutMs: 30_000 });\n  }\n\n  async revoke(botId: string): Promise\u003Cvoid> {\n    this.tokens.delete(botId);\n  }\n\n  async listWorkspaces(): Promise\u003C{ botId: string; name: string; authorizedAt: Date }[]> {\n    return Array.from(this.tokens.values()).map(t => ({\n      botId: t.botId,\n      name: t.workspaceName,\n      authorizedAt: t.authorizedAt,\n    }));\n  }\n}\n\nconst tokenStore = new TokenStore();\n```\n\n**Permission-aware API calls — handle Notion's page-level permissions:**\n\n```typescript\n\u002F\u002F Notion returns ObjectNotFound for pages not shared with the integration\n\u002F\u002F This is NOT the same as the page being deleted\nasync function safePageAccess(notion: Client, pageId: string) {\n  try {\n    return await notion.pages.retrieve({ page_id: pageId });\n  } catch (error) {\n    if (!isNotionClientError(error)) throw error;\n\n    switch (error.code) {\n      case APIErrorCode.ObjectNotFound:\n        \u002F\u002F Page exists but is NOT shared with this integration\n        \u002F\u002F User needs to share it via the \"...\" menu > Connections\n        console.log(`Page ${pageId} not accessible. Ask user to share via Connections.`);\n        return null;\n\n      case APIErrorCode.RestrictedResource:\n        \u002F\u002F Integration lacks the required capability (read\u002Fupdate\u002Finsert\u002Fdelete)\n        console.log(`Integration lacks capability for ${pageId}. Check integration settings.`);\n        return null;\n\n      case APIErrorCode.Unauthorized:\n        \u002F\u002F Token was revoked — user needs to re-authorize\n        console.log(`Token revoked. User needs to re-authorize.`);\n        return null;\n\n      default:\n        throw error;\n    }\n  }\n}\n\n\u002F\u002F List all pages accessible to the integration (discovers shared content)\nasync function discoverAccessiblePages(notion: Client): Promise\u003Cstring[]> {\n  const pageIds: string[] = [];\n  let cursor: string | undefined;\n\n  do {\n    const response = await notion.search({\n      filter: { property: 'object', value: 'page' },\n      page_size: 100,\n      start_cursor: cursor,\n    });\n    pageIds.push(...response.results.map(r => r.id));\n    cursor = response.has_more ? response.next_cursor ?? undefined : undefined;\n  } while (cursor);\n\n  return pageIds;\n}\n```\n\n### Step 3: Application-Level Roles and Audit Logging\n\n**Role-based access control layered on top of Notion permissions:**\n\n```typescript\nenum AppRole {\n  Admin = 'admin',\n  Editor = 'editor',\n  Viewer = 'viewer',\n}\n\nconst ROLE_PERMISSIONS: Record\u003CAppRole, {\n  canRead: boolean;\n  canWrite: boolean;\n  canDelete: boolean;\n  canManageIntegration: boolean;\n}> = {\n  admin:  { canRead: true, canWrite: true, canDelete: true, canManageIntegration: true },\n  editor: { canRead: true, canWrite: true, canDelete: false, canManageIntegration: false },\n  viewer: { canRead: true, canWrite: false, canDelete: false, canManageIntegration: false },\n};\n\ninterface AppUser {\n  id: string;\n  email: string;\n  role: AppRole;\n  workspaceBotId: string;  \u002F\u002F Links to stored workspace token\n}\n\nfunction checkPermission(user: AppUser, action: 'read' | 'write' | 'delete' | 'manage'): boolean {\n  const perms = ROLE_PERMISSIONS[user.role];\n  switch (action) {\n    case 'read': return perms.canRead;\n    case 'write': return perms.canWrite;\n    case 'delete': return perms.canDelete;\n    case 'manage': return perms.canManageIntegration;\n  }\n}\n\n\u002F\u002F Express middleware\nfunction requirePermission(action: 'read' | 'write' | 'delete' | 'manage') {\n  return (req: any, res: any, next: any) => {\n    if (!checkPermission(req.user, action)) {\n      auditLog({\n        userId: req.user.id,\n        workspaceId: req.user.workspaceBotId,\n        action: `${action}_denied`,\n        resource: { type: 'endpoint', id: req.path },\n        result: 'denied',\n      });\n      return res.status(403).json({ error: `Requires \"${action}\" permission` });\n    }\n    next();\n  };\n}\n\n\u002F\u002F Route examples\napp.get('\u002Fapi\u002Fpages\u002F:id', requirePermission('read'), async (req, res) => {\n  const notion = await tokenStore.getClient(req.user.workspaceBotId);\n  const page = await safePageAccess(notion, req.params.id);\n  res.json(page);\n});\n\napp.post('\u002Fapi\u002Fpages', requirePermission('write'), async (req, res) => {\n  const notion = await tokenStore.getClient(req.user.workspaceBotId);\n  const page = await notion.pages.create(req.body);\n  res.json(page);\n});\n```\n\n**Audit logging — write to structured logs and optionally to a Notion database:**\n\n```typescript\ninterface AuditEntry {\n  timestamp: string;\n  userId: string;\n  workspaceId: string;\n  action: string;\n  resource: { type: string; id: string };\n  result: 'success' | 'denied' | 'error';\n  metadata?: Record\u003Cstring, unknown>;\n}\n\nasync function auditLog(entry: Omit\u003CAuditEntry, 'timestamp'>): Promise\u003Cvoid> {\n  const full: AuditEntry = {\n    ...entry,\n    timestamp: new Date().toISOString(),\n  };\n\n  \u002F\u002F Always log to structured logging (searchable in log aggregator)\n  console.log(JSON.stringify({ level: 'audit', ...full }));\n\n  \u002F\u002F Optionally write to a Notion audit database\n  if (process.env.NOTION_AUDIT_DB_ID) {\n    try {\n      const notion = await tokenStore.getClient(entry.workspaceId);\n      await notion.pages.create({\n        parent: { database_id: process.env.NOTION_AUDIT_DB_ID },\n        properties: {\n          Action: { title: [{ text: { content: entry.action } }] },\n          User: { rich_text: [{ text: { content: entry.userId } }] },\n          Result: { select: { name: entry.result } },\n          Resource: {\n            rich_text: [{ text: { content: `${entry.resource.type}:${entry.resource.id}` } }],\n          },\n          Timestamp: { date: { start: full.timestamp } },\n        },\n      });\n    } catch (error) {\n      \u002F\u002F Audit log writes should never crash the application\n      console.error('Failed to write audit log to Notion:', error);\n    }\n  }\n}\n\n\u002F\u002F Handle workspace deauthorization (user removes integration)\nasync function handleDeauthorization(botId: string): Promise\u003Cvoid> {\n  const workspaces = await tokenStore.listWorkspaces();\n  const workspace = workspaces.find(w => w.botId === botId);\n\n  if (workspace) {\n    await auditLog({\n      userId: 'system',\n      workspaceId: botId,\n      action: 'workspace_deauthorized',\n      resource: { type: 'workspace', id: botId },\n      result: 'success',\n      metadata: { workspaceName: workspace.name },\n    });\n\n    await tokenStore.revoke(botId);\n  }\n}\n```\n\n## Output\n\n- Complete OAuth 2.0 flow for multi-workspace access (TypeScript + Python)\n- Per-workspace token storage with encryption guidance\n- Permission-aware API calls handling ObjectNotFound vs RestrictedResource\n- Content discovery via `search` endpoint\n- Application-level role system (admin\u002Feditor\u002Fviewer) with Express middleware\n- Comprehensive audit logging to structured logs and optionally to Notion database\n- Workspace deauthorization cleanup handler\n\n## Error Handling\n\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| OAuth callback fails | Redirect URI mismatch | Must match exactly in integration settings (including trailing slash) |\n| `invalid_grant` on token exchange | Code expired or already used | Authorization codes are single-use; restart OAuth flow |\n| `ObjectNotFound` on page access | Page not shared with integration | User must share via \"...\" menu > Connections |\n| `RestrictedResource` | Integration missing capability | Edit capabilities at notion.so\u002Fmy-integrations |\n| `Unauthorized` (401) | Token revoked by user | Prompt re-authorization; clean up stored token |\n| State mismatch on callback | CSRF attack or session expired | Reject the callback; redirect to start OAuth again |\n\n## Examples\n\n### Full OAuth Integration (Express)\n\n```typescript\nimport express from 'express';\nimport session from 'express-session';\nimport crypto from 'crypto';\n\nconst app = express();\napp.use(session({ secret: process.env.SESSION_SECRET!, resave: false, saveUninitialized: false }));\n\napp.get('\u002Fauth\u002Fnotion', (req, res) => {\n  const state = crypto.randomUUID();\n  (req.session as any).oauthState = state;\n  res.redirect(getAuthorizationUrl(state));\n});\n\napp.get('\u002Fauth\u002Fnotion\u002Fcallback', async (req, res) => {\n  if (req.query.state !== (req.session as any).oauthState) {\n    return res.status(403).send('Invalid state');\n  }\n  const tokenData = await exchangeCodeForToken(req.query.code as string);\n  await tokenStore.store(tokenData);\n\n  await auditLog({\n    userId: tokenData.owner?.user?.id ?? 'unknown',\n    workspaceId: tokenData.bot_id,\n    action: 'workspace_authorized',\n    resource: { type: 'workspace', id: tokenData.workspace_id },\n    result: 'success',\n  });\n\n  res.redirect(`\u002Fdashboard?workspace=${encodeURIComponent(tokenData.workspace_name)}`);\n});\n\napp.get('\u002Fworkspaces', async (_req, res) => {\n  const workspaces = await tokenStore.listWorkspaces();\n  res.json(workspaces);\n});\n```\n\n## Resources\n\n- [Notion OAuth Authorization](https:\u002F\u002Fdevelopers.notion.com\u002Fdocs\u002Fauthorization) — full OAuth guide\n- [Create a Token (OAuth)](https:\u002F\u002Fdevelopers.notion.com\u002Freference\u002Fcreate-a-token) — token exchange endpoint\n- [Authentication Reference](https:\u002F\u002Fdevelopers.notion.com\u002Freference\u002Fauthentication) — auth header format\n- [Notion Capabilities](https:\u002F\u002Fdevelopers.notion.com\u002Fdocs\u002Fcreate-a-notion-integration#capabilities) — read\u002Fupdate\u002Finsert\u002Fdelete\n- [Sharing and Permissions](https:\u002F\u002Fdevelopers.notion.com\u002Fdocs\u002Fcreate-a-notion-integration#sharing-and-permissions) — page-level model\n\n## Next Steps\n\nFor migrating data to and from Notion, see `notion-migration-deep-dive`.\n",{"name":5,"tags":24,"author":28,"license":15,"version":29,"description":30,"allowed-tools":31,"compatible-with":32},[25,26,27],"saas","productivity","notion","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","1.0.0","Configure Notion enterprise access control with OAuth, workspace permissions, and audit logging.\nUse when implementing OAuth public integrations, managing multi-workspace access,\nor building permission-aware Notion applications.\nTrigger with phrases like \"notion SSO\", \"notion RBAC\",\n\"notion enterprise\", \"notion OAuth\", \"notion permissions\", \"notion multi-workspace\".\n","Read, Write, Edit","claude-code","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--notion-pack--notion-enterprise-rbac",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":43,"prompt":53,"zipAvailable":54},[44,47,50],{"tool":45,"command":46},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill notion-enterprise-rbac",{"tool":48,"command":49},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill notion-enterprise-rbac",{"tool":51,"command":52},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill notion-enterprise-rbac","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--notion-pack--notion-enterprise-rbac\u002FSKILL.md",true,[],[57,64,71,78,85,93],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":89,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]