deepgram-enterprise-rbac

0
0
Source

Configure enterprise role-based access control for Deepgram integrations. Use when implementing team permissions, managing API key scopes, or setting up organization-level access controls. Trigger with phrases like "deepgram RBAC", "deepgram permissions", "deepgram access control", "deepgram team roles", "deepgram enterprise".

Install

mkdir -p .claude/skills/deepgram-enterprise-rbac && curl -L -o skill.zip "https://mcp.directory/api/skills/download/8925" && unzip -o skill.zip -d .claude/skills/deepgram-enterprise-rbac && rm skill.zip

Installs to .claude/skills/deepgram-enterprise-rbac

About this skill

Deepgram Enterprise RBAC

Overview

Role-based access control for enterprise Deepgram deployments. Maps five application roles to Deepgram API key scopes, implements scoped key provisioning via the Deepgram Management API, Express permission middleware, team management with auto-provisioned keys, and automated key rotation.

Deepgram Scope Reference

ScopePermissionUsed By
memberFull access (all scopes)Admin only
listenSTT transcriptionDevelopers, Services
speakTTS synthesisDevelopers, Services
manageProject/key managementAdmin
usage:readView usage metricsAnalysts, Auditors
keys:readList API keysAuditors
keys:writeCreate/delete keysAdmin

Instructions

Step 1: Define Roles and Scope Mapping

interface Role {
  name: string;
  deepgramScopes: string[];
  keyExpiry: number;        // Days
  description: string;
}

const ROLES: Record<string, Role> = {
  admin: {
    name: 'Admin',
    deepgramScopes: ['member'],
    keyExpiry: 90,
    description: 'Full access — project and key management',
  },
  developer: {
    name: 'Developer',
    deepgramScopes: ['listen', 'speak'],
    keyExpiry: 90,
    description: 'STT and TTS — no management access',
  },
  analyst: {
    name: 'Analyst',
    deepgramScopes: ['usage:read'],
    keyExpiry: 365,
    description: 'Read-only usage metrics',
  },
  service: {
    name: 'Service Account',
    deepgramScopes: ['listen'],
    keyExpiry: 90,
    description: 'STT only — for automated systems',
  },
  auditor: {
    name: 'Auditor',
    deepgramScopes: ['usage:read', 'keys:read'],
    keyExpiry: 30,
    description: 'Read-only audit access',
  },
};

Step 2: Scoped Key Provisioning

import { createClient } from '@deepgram/sdk';

class DeepgramKeyManager {
  private admin: ReturnType<typeof createClient>;
  private projectId: string;

  constructor(adminKey: string, projectId: string) {
    this.admin = createClient(adminKey);
    this.projectId = projectId;
  }

  async createScopedKey(userId: string, roleName: string): Promise<{
    keyId: string;
    key: string;
    scopes: string[];
    expiresAt: string;
  }> {
    const role = ROLES[roleName];
    if (!role) throw new Error(`Unknown role: ${roleName}`);

    const expirationDate = new Date(Date.now() + role.keyExpiry * 86400000);

    const { result, error } = await this.admin.manage.createProjectKey(
      this.projectId,
      {
        comment: `${roleName}:${userId}:${new Date().toISOString().split('T')[0]}`,
        scopes: role.deepgramScopes,
        expiration_date: expirationDate.toISOString(),
      }
    );

    if (error) throw new Error(`Key creation failed: ${error.message}`);

    console.log(`Created ${roleName} key for ${userId} (expires ${expirationDate.toISOString().split('T')[0]})`);

    return {
      keyId: result.key_id,
      key: result.key,
      scopes: role.deepgramScopes,
      expiresAt: expirationDate.toISOString(),
    };
  }

  async revokeKey(keyId: string) {
    const { error } = await this.admin.manage.deleteProjectKey(
      this.projectId, keyId
    );
    if (error) throw new Error(`Key revocation failed: ${error.message}`);
    console.log(`Revoked key: ${keyId}`);
  }

  async listKeys() {
    const { result, error } = await this.admin.manage.getProjectKeys(this.projectId);
    if (error) throw error;

    return result.api_keys.map((k: any) => ({
      keyId: k.api_key_id,
      comment: k.comment,
      scopes: k.scopes,
      created: k.created,
      expiration: k.expiration_date,
    }));
  }
}

Step 3: Permission Middleware

import { Request, Response, NextFunction } from 'express';

interface AuthenticatedRequest extends Request {
  user?: { id: string; role: string; deepgramKeyId: string };
}

function requireRole(...allowedRoles: string[]) {
  return (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
    if (!req.user) {
      return res.status(401).json({ error: 'Authentication required' });
    }

    if (!allowedRoles.includes(req.user.role)) {
      console.warn(`Access denied: user ${req.user.id} (${req.user.role}) tried to access ${req.path}`);
      return res.status(403).json({
        error: 'Insufficient permissions',
        required: allowedRoles,
        current: req.user.role,
      });
    }

    next();
  };
}

function requireScope(...requiredScopes: string[]) {
  return (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
    if (!req.user) {
      return res.status(401).json({ error: 'Authentication required' });
    }

    const role = ROLES[req.user.role];
    const hasScopes = requiredScopes.every(
      s => role.deepgramScopes.includes(s) || role.deepgramScopes.includes('member')
    );

    if (!hasScopes) {
      return res.status(403).json({
        error: 'Missing required Deepgram scopes',
        required: requiredScopes,
        current: role.deepgramScopes,
      });
    }

    next();
  };
}

// Route examples:
app.post('/api/transcribe', requireScope('listen'), transcribeHandler);
app.post('/api/tts', requireScope('speak'), ttsHandler);
app.get('/api/usage', requireScope('usage:read'), usageHandler);
app.post('/api/keys', requireRole('admin'), createKeyHandler);
app.get('/api/audit', requireRole('admin', 'auditor'), auditHandler);

Step 4: Team Management

interface Team {
  id: string;
  name: string;
  projectId: string;       // Deepgram project ID
  members: Array<{
    userId: string;
    role: string;
    keyId: string;
    joinedAt: string;
  }>;
}

class TeamManager {
  private keyManager: DeepgramKeyManager;

  constructor(adminKey: string, projectId: string) {
    this.keyManager = new DeepgramKeyManager(adminKey, projectId);
  }

  async addMember(team: Team, userId: string, role: string) {
    // Provision Deepgram key with role scopes
    const key = await this.keyManager.createScopedKey(userId, role);

    team.members.push({
      userId,
      role,
      keyId: key.keyId,
      joinedAt: new Date().toISOString(),
    });

    console.log(`Added ${userId} to ${team.name} as ${role}`);
    return key;
  }

  async removeMember(team: Team, userId: string) {
    const member = team.members.find(m => m.userId === userId);
    if (!member) throw new Error(`User ${userId} not in team`);

    // Revoke Deepgram key
    await this.keyManager.revokeKey(member.keyId);

    team.members = team.members.filter(m => m.userId !== userId);
    console.log(`Removed ${userId} from ${team.name}, key revoked`);
  }

  async changeRole(team: Team, userId: string, newRole: string) {
    const member = team.members.find(m => m.userId === userId);
    if (!member) throw new Error(`User ${userId} not in team`);

    // Revoke old key, create new key with new role scopes
    await this.keyManager.revokeKey(member.keyId);
    const newKey = await this.keyManager.createScopedKey(userId, newRole);

    member.role = newRole;
    member.keyId = newKey.keyId;

    console.log(`Changed ${userId} role to ${newRole}`);
    return newKey;
  }
}

Step 5: Automated Key Rotation

async function rotateExpiringKeys(
  keyManager: DeepgramKeyManager,
  db: any,
  daysBeforeExpiry = 7
) {
  const keys = await keyManager.listKeys();
  const now = Date.now();
  const threshold = now + daysBeforeExpiry * 86400000;
  let rotated = 0;

  for (const key of keys) {
    if (!key.expiration) continue;
    const expiresAt = new Date(key.expiration).getTime();

    if (expiresAt < threshold) {
      // Parse role from comment (format: "role:userId:date")
      const [role, userId] = (key.comment ?? '').split(':');
      if (!role || !userId) {
        console.warn(`Cannot rotate key ${key.keyId} — unknown format: ${key.comment}`);
        continue;
      }

      console.log(`Rotating key for ${userId} (${role}), expires ${key.expiration}`);

      // Create new key
      const newKey = await keyManager.createScopedKey(userId, role);

      // Update database with new key ID
      await db.query(
        'UPDATE team_members SET key_id = $1 WHERE user_id = $2',
        [newKey.keyId, userId]
      );

      // Revoke old key (after a grace period, or immediately)
      await keyManager.revokeKey(key.keyId);
      rotated++;
    }
  }

  console.log(`Rotated ${rotated} keys expiring within ${daysBeforeExpiry} days`);
  return rotated;
}

Step 6: Access Control Matrix

ActionAdminDeveloperAnalystServiceAuditor
Transcribe (STT)YesYesNoYesNo
Text-to-SpeechYesYesNoNoNo
View usageYesNoYesNoYes
Manage keysYesNoNoNoNo
View audit logsYesNoNoNoYes
Create projectsYesNoNoNoNo

Output

  • Five-role permission model with Deepgram scope mapping
  • Scoped API key provisioning via Management API
  • Express middleware (role-based and scope-based)
  • Team management with auto-provisioned/revoked keys
  • Automated key rotation for expiring keys

Error Handling

IssueCauseSolution
403 ForbiddenKey lacks scopeCreate new key with correct scopes
Key expiredNo rotation configuredEnable automated rotation
manage.createProjectKey failsAdmin key missing member scopeUse key with member scope
Team member can't transcribeWrong role assignedChange role to developer or service

Resources

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

6532

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

9029

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

15922

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4915

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

12014

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

5110

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,4071,302

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,2201,024

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

9001,013

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

958658

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

970608

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,033496

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.