MI

mistral-security-basics

Configures security measures for Mistral AI, focusing on API key protection and prompt sanitization.

Install

mkdir -p .claude/skills/mistral-security-basics && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/4683" && unzip -o skill.zip -d .claude/skills/mistral-security-basics && rm skill.zip

Installs to .claude/skills/mistral-security-basics

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.

Apply Mistral AI security best practices for secrets, prompt injection,
71 charsno explicit “when” trigger
Advanced

Key capabilities

  • Manage API keys via secret managers
  • Filter user input for prompt injection patterns
  • Moderate content using mistral-moderation-latest
  • Sanitize model output for PII and script tags
  • Automate API key rotation

How it works

The skill provides a security layer that wraps user input to prevent injection, uses a moderation API to gate content, and sanitizes outputs to remove PII and malicious tags.

Inputs & outputs

You give it
Raw user input or model response
You get back
Sanitized and moderated content

When to use mistral-security-basics

  • Securing Mistral API keys
  • Implementing prompt injection defense
  • Auditing AI security configuration
  • Setting up content moderation

About this skill

Mistral Security Basics

Overview

Security practices for Mistral AI integrations: API key management, prompt injection defense, output sanitization, content moderation with mistral-moderation-latest, request logging without secrets, and key rotation.

Prerequisites

  • Mistral API key provisioned
  • Understanding of OWASP LLM Top 10 risks
  • Secret management infrastructure

Instructions

Step 1: API Key Management

import os

# NEVER: api_key = "sk-abc123"

# Development — env vars
api_key = os.environ.get("MISTRAL_API_KEY")
if not api_key:
    raise RuntimeError("MISTRAL_API_KEY not set")

# Production — secret manager
from google.cloud import secretmanager

def get_api_key() -> str:
    client = secretmanager.SecretManagerServiceClient()
    response = client.access_secret_version(
        name="projects/my-project/secrets/mistral-api-key/versions/latest"
    )
    return response.payload.data.decode("UTF-8")

Step 2: Prompt Injection Defense

function sanitizeUserInput(input: string): string {
  // Strip common injection patterns
  const patterns = [
    /ignore (?:previous|all|above) instructions/gi,
    /you are now/gi,
    /system prompt/gi,
    /\boverride\b/gi,
    /\bforget\b.*\binstructions\b/gi,
  ];

  let sanitized = input;
  for (const pattern of patterns) {
    sanitized = sanitized.replace(pattern, '[FILTERED]');
  }

  // Limit length to prevent context stuffing
  return sanitized.slice(0, 4000);
}

function buildSafeMessages(system: string, userInput: string) {
  return [
    { role: 'system', content: system },
    {
      role: 'user',
      content: `<user_query>\n${sanitizeUserInput(userInput)}\n</user_query>`,
    },
  ];
}

Step 3: Content Moderation with Mistral API

import { Mistral } from '@mistralai/mistralai';

const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });

async function moderateContent(text: string): Promise<{ safe: boolean; flags: string[] }> {
  const result = await client.classifiers.moderate({
    model: 'mistral-moderation-latest',
    inputs: [text],
  });

  const categories = result.results[0].categories;
  const flags = Object.entries(categories)
    .filter(([, flagged]) => flagged)
    .map(([category]) => category);

  return { safe: flags.length === 0, flags };
}

// Gate user input before processing
async function safeChatFlow(userInput: string) {
  const inputCheck = await moderateContent(userInput);
  if (!inputCheck.safe) {
    throw new Error(`Input flagged: ${inputCheck.flags.join(', ')}`);
  }

  const response = await client.chat.complete({
    model: 'mistral-small-latest',
    messages: [{ role: 'user', content: userInput }],
    safePrompt: true, // Built-in safety system prompt
  });

  const output = response.choices?.[0]?.message?.content ?? '';
  const outputCheck = await moderateContent(output);
  if (!outputCheck.safe) {
    return 'I cannot provide that response.';
  }

  return output;
}

Step 4: Output Sanitization

function sanitizeOutput(response: string): string {
  let cleaned = response;

  // Remove leaked system prompts
  cleaned = cleaned.replace(/(?:system prompt|instructions):?\s*.*/gi, '[REDACTED]');

  // Remove script tags (XSS prevention)
  cleaned = cleaned.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');

  // Remove PII patterns
  cleaned = cleaned.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]');
  cleaned = cleaned.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/gi, '[EMAIL]');

  return cleaned;
}

Step 5: Request Logging Without Secrets

function logRequest(model: string, messages: any[], response: any): void {
  // Log metadata ONLY — never log content (may contain PII)
  console.log(JSON.stringify({
    timestamp: new Date().toISOString(),
    model,
    messageCount: messages.length,
    inputChars: messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0),
    outputChars: response.choices?.[0]?.message?.content?.length ?? 0,
    usage: {
      promptTokens: response.usage?.promptTokens,
      completionTokens: response.usage?.completionTokens,
    },
    // NEVER log: API keys, message content, user identifiers
  }));
}

Step 6: API Key Rotation

class KeyRotator {
  private keys: string[];
  private current = 0;
  private lastRotated = Date.now();
  private readonly rotationIntervalMs = 3_600_000; // 1 hour

  constructor(keys: string[]) {
    if (keys.length === 0) throw new Error('At least one API key required');
    this.keys = keys;
  }

  getKey(): string {
    if (Date.now() - this.lastRotated > this.rotationIntervalMs) {
      this.rotate();
    }
    return this.keys[this.current];
  }

  reportAuthFailure(): void {
    console.error(`Key ${this.current} failed auth, rotating`);
    this.rotate();
  }

  private rotate(): void {
    this.current = (this.current + 1) % this.keys.length;
    this.lastRotated = Date.now();
  }
}

Security Audit Checklist

def audit_mistral_security():
    checks = {
        "api_key_from_env": bool(os.environ.get("MISTRAL_API_KEY")),
        "gitignore_has_env": ".env" in open(".gitignore").read() if os.path.exists(".gitignore") else False,
        "no_hardcoded_keys": True,  # scan src/ for patterns
        "moderation_enabled": True,  # verify in code
        "output_sanitization": True,  # verify in code
        "audit_logging": True,  # verify in code
    }
    passed = all(checks.values())
    return {"passed": passed, "checks": checks}

Error Handling

IssueCauseSolution
Key in logsLogging full requestLog metadata only
Prompt injectionUnsanitized user inputFilter + XML-wrap user content
PII in responsesModel generating PIISanitize output + use moderation
Key compromiseHardcoded or leakedUse secret manager, rotate immediately
XSS via outputModel generating HTML/JSStrip script tags before rendering

Resources

Output

  • API key management via secret managers
  • Prompt injection defense layer
  • Content moderation with mistral-moderation-latest
  • Output sanitization pipeline
  • Secure audit logging
  • Key rotation automation

When not to use it

  • Logging full request content
  • Hardcoding API keys in source code

Prerequisites

Mistral API keySecret management infrastructure

Limitations

  • Sanitization regex may not catch all PII patterns

How it compares

It provides a proactive sanitization pipeline and automated key rotation logic instead of relying on basic API authentication.

Compared to similar skills

mistral-security-basics side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
mistral-security-basics (this skill)127dReviewAdvanced
auth-patterns77moReviewIntermediate
clerk-incident-runbook127dCautionIntermediate
customerio-security-basics127dReviewIntermediate

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

auth-patterns

davepoon

This skill should be used when the user asks about "authentication in Next.js", "NextAuth", "Auth.js", "middleware auth", "protected routes", "session management", "JWT", "login flow", or needs guidance on implementing authentication and authorization in Next.js applications.

720

clerk-incident-runbook

jeremylongshore

Incident response procedures for Clerk authentication issues. Use when handling auth outages, security incidents, or production authentication problems. Trigger with phrases like "clerk incident", "clerk outage", "clerk down", "auth not working", "clerk emergency".

110

customerio-security-basics

jeremylongshore

Apply Customer.io security best practices. Use when implementing secure integrations, handling PII, or setting up proper access controls. Trigger with phrases like "customer.io security", "customer.io pii", "secure customer.io", "customer.io gdpr".

15

gamma-enterprise-rbac

jeremylongshore

Implement enterprise role-based access control for Gamma integrations. Use when configuring team permissions, multi-tenant access, or enterprise authorization patterns. Trigger with phrases like "gamma RBAC", "gamma permissions", "gamma access control", "gamma enterprise", "gamma roles".

12

jwt-auth

dadbodgeoff

Implement secure JWT authentication with refresh token rotation, secure storage, and automatic renewal. Use when building authentication for SPAs, mobile apps, or APIs that need stateless auth with refresh capabilities.

12

maintainx-security-basics

jeremylongshore

Configure MaintainX API security, credential management, and access control. Use when securing API keys, implementing access controls, or hardening your MaintainX integration. Trigger with phrases like "maintainx security", "maintainx api key security", "secure maintainx", "maintainx credentials", "maintainx access control".

11

Search skills

Search the agent skills registry