DE

deepgram-enterprise-rbac

Sets up role-based access control for Deepgram by mapping application roles to specific API key scopes and management permissions.

Install

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

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

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Configure enterprise role-based access control for Deepgram integrations.
73 charsno explicit “when” trigger
Advanced

Key capabilities

  • Maps roles to Deepgram API scopes
  • Provisions scoped API keys via Management API
  • Implements Express permission middleware
  • Automates key rotation for security
  • Manages team access levels

How it works

The tool uses the Deepgram Management API to create keys with specific scopes based on predefined roles, and provides middleware to enforce these roles in applications.

Inputs & outputs

You give it
User role and project ID
You get back
Scoped API key and permission configuration

When to use deepgram-enterprise-rbac

  • Define admin vs developer API key scopes
  • Implement key rotation policies
  • Setup scoped permissions for TTS versus STT access
  • Provision team-specific access keys

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

When not to use it

  • For simple applications with a single user
  • When managing non-Deepgram resources

Prerequisites

Deepgram Admin API keyProject ID

Limitations

  • Requires an Admin key with member scope
  • Role definitions must be maintained in code

How it compares

It provides a structured framework for enterprise-grade access control, whereas manual key management often leads to over-privileged keys.

Compared to similar skills

deepgram-enterprise-rbac side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
deepgram-enterprise-rbac (this skill)027dReviewAdvanced
twilio-communications36moReviewIntermediate
lindy-install-auth427dCautionBeginner
clay-install-auth027dCautionBeginner

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

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.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

twilio-communications

davila7

Build communication features with Twilio: SMS messaging, voice calls, WhatsApp Business API, and user verification (2FA). Covers the full spectrum from simple notifications to complex IVR systems and multi-channel authentication. Critical focus on compliance, rate limits, and error handling. Use when: twilio, send SMS, text message, voice call, phone verification.

324

lindy-install-auth

jeremylongshore

Install and configure Lindy AI SDK/CLI authentication. Use when setting up a new Lindy integration, configuring API keys, or initializing Lindy in your project. Trigger with phrases like "install lindy", "setup lindy", "lindy auth", "configure lindy API key".

410

clay-install-auth

jeremylongshore

Install and configure Clay SDK/CLI authentication. Use when setting up a new Clay integration, configuring API keys, or initializing Clay in your project. Trigger with phrases like "install clay", "setup clay", "clay auth", "configure clay API key".

06

evernote-install-auth

jeremylongshore

Install and configure Evernote SDK and OAuth authentication. Use when setting up a new Evernote integration, configuring API keys, or initializing Evernote in your project. Trigger with phrases like "install evernote", "setup evernote", "evernote auth", "configure evernote API", "evernote oauth".

14

instantly-install-auth

jeremylongshore

Install and configure Instantly SDK/CLI authentication. Use when setting up a new Instantly integration, configuring API keys, or initializing Instantly in your project. Trigger with phrases like "install instantly", "setup instantly", "instantly auth", "configure instantly API key".

12

openrouter-install-auth

jeremylongshore

Execute set up OpenRouter API authentication and configure API keys. Use when starting a new OpenRouter integration or troubleshooting auth issues. Trigger with phrases like 'openrouter setup', 'openrouter api key', 'openrouter authentication', 'configure openrouter'.

03

Search skills

Search the agent skills registry