Text Classification
Transformers
Safetensors
English
deberta-v2
secret-detection
secrets
security
cybersecurity
devsecops
sast
code-security
code-analysis
supply-chain-security
pre-commit
ci-cd
github-actions
password-detection
api-key-detection
token-detection
credential-detection
secure-coding
deberta
deberta-v3
binary-classification
Eval Results (legacy)
text-embeddings-inference
Instructions to use hypn05/secrets-sentinel with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use hypn05/secrets-sentinel with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="hypn05/secrets-sentinel")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("hypn05/secrets-sentinel") model = AutoModelForSequenceClassification.from_pretrained("hypn05/secrets-sentinel", device_map="auto") - Notebooks
- Google Colab
- Kaggle
v4.0.0: Reduced FP on GitHub Actions SHAs, .env.example placeholders, PHP config nulls/hashids/routes, test emails, Spring annotations, DAV dates, installer curls, localhost URLs. Trained last-4-layers on data_v9 + 5608 real-world labeled examples from OWASP apps and scanner fixture repos.
Browse filesFiles changed (2)
- README.md+591-452
- model.safetensors+1-1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452---license: mitbase_model:- microsoft/deberta-v3-basepipeline_tag: text-classificationlibrary_name: transformerstags:- deberta-v2- secrets- secret-detection- secure-codeing- Github-pipeline- deberta- cybersecurity- code-analysis---# Secrets Sentinel## The ProblemSecrets pushed to repositories like GitHub create a critical security vulnerability. Once exposed:- **Difficult to Remove**: Requires coordination across multiple teams- **Wide Impact**: Secret rotation becomes mandatory and expensive- **Persistent Risk**: History can be exploited even after deletion## The SolutionA **fast, accurate Small Language Model (SLM)** that detects secrets in code before they reach your repository. Designed to run in **pre-receive hooks and CI/CD pipelines** with a hard 5-second time limit.## Why This Model?| Approach | Speed | Accuracy | Cost | Generic Secrets ||----------|-------|----------|------|-----------------|| ✗ Regex Tools | Fast | Low | Free | ✗ Poor || ✗ Large LLMs | Slow (>30s) | High | Expensive | ✓ Great || ✓ **This SLM** | **Ultra-Fast (<500ms)** | **High** | **Cheap** | **✓ Excellent** |**Key Advantage**: Detects *generic secrets* (not just patterns) using context-aware AI, unlike regex tools that rely on predefined patterns.## Model Details- **Architecture**: DeBERTa v3 Base (86M parameters)- **Task**: Binary sequence classification- **Detection Labels**:- `LABEL_0`: Normal code- `LABEL_1`: Secret detected- **Inference Speed**: ~100-200ms per line (GPU), ~500ms (CPU)- **Fine-tuned for**: Git diff lines and code snippets## Training Configuration- **Loss**: Weighted cross-entropy (handles class imbalance)- **Optimization Metric**: F1-score- **Training Tech**: BF16 precision, gradient checkpointing## Quick Start### Simple Pipeline Usage```pythonfrom transformers import pipeline# Load the pipeline with the secrets detection modelclassifier = pipeline("text-classification",model="hypn05/secrets-sentinel")# Define the input examplesinputs = ["password='supersecret123'", # Expected: Secret"api_key = 'sk-1234567890abc'", # Expected: Secret"print('Hello, world!')", # Expected: Safe"def calculate_sum(a, b):", # Expected: Safe]# Run the classifier on the inputsresults = classifier(inputs)# Print the actual input string and the result ("Secret" if LABEL_1, else "Safe")for input_text, result in zip(inputs, results):label = "Secret" if result['label'] == "LABEL_1" else "Safe"print(f"{label} | {input_text}")```## Advanced Usage### Production-Ready IntegrationPerfect for **pre-receive hooks** with strict time constraints:```pythonimport torchfrom transformers import AutoTokenizer, AutoModelForSequenceClassificationfrom typing import List, Tupleclass SecretDetector:def __init__(self, device: str = None, compile: bool = True):"""Initialize the secret detector with optional compilation."""self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")print(f"Loading model on {self.device.upper()}...")model_name = "hypn05/secrets-sentinel"self.tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)self.model = AutoModelForSequenceClassification.from_pretrained(model_name,torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,attn_implementation="eager").to(self.device).eval()# ⚡ Compile for max speed (first run slower, subsequent runs 2-3x faster)if compile and self.device == "cuda":try:self.model = torch.compile(self.model)print("✓ Model compiled for production speed")except Exception as e:print(f"Compilation skipped: {e}")def detect_secrets(self, texts: List[str], threshold: float = 0.7) -> List[Tuple[str, str, float]]:"""Detect secrets in a batch of code snippets."""inputs = self.tokenizer(texts,padding=True,truncation=True,max_length=512,return_tensors="pt").to(self.device)with torch.no_grad():outputs = self.model(**inputs)logits = outputs.logitsscores = torch.softmax(logits, dim=-1)predictions = torch.argmax(logits, dim=-1)# Map to labelsactual_model = self.model._orig_mod if hasattr(self.model, '_orig_mod') else self.modelresults = []for text, pred_idx, score in zip(texts, predictions, scores[:, 1]):label = actual_model.config.id2label[pred_idx.item()]confidence = score.item()results.append((text, label, confidence))return results# Example: Pre-receive hook integrationdef pre_receive_hook(git_diff: str, threshold: float = 0.5) -> bool:"""Check git diff for secrets.Returns True if safe to push, False if secrets detected."""detector = SecretDetector(compile=True) # Warm up on first call# Extract lines from diffdiff_lines = [line for line in git_diff.split('\n') if line.startswith(('+', '-'))]results = detector.detect_secrets(diff_lines, threshold=threshold)secrets_found = []for text, label, confidence in results:if label == "Secret" and confidence > threshold:secrets_found.append((text, confidence))if secrets_found:print(f"\n PUSH REJECTED: {len(secrets_found)} secret(s) detected!")for text, conf in secrets_found:print(f" [{conf:.1%}] {text[:80]}")return Falseprint("✓ No secrets detected. Push allowed.")return Trueif __name__ == "__main__":# Example usagedetector = SecretDetector()test_cases = ["password='secret123'","api_token = 'ghp_abcd1234efgh5678ijkl'", # GitHub token"db_password = os.environ.get('DB_PASS')","print('Hello, world!')","def authenticate(username, password):","AWS_SECRET_ACCESS_KEY = b'abc123xyz789'","The weather is nice today",]print("\n" + "="*70)print("SECRET DETECTION RESULTS")print("="*70)results = detector.detect_secrets(test_cases)for text, label, confidence in results:status = "" if label == "Secret" else "✓"display_text = (text[:55] + "...") if len(text) > 55 else textprint(f"{status} [{confidence:>6.1%}] {label:>8} | {display_text}")print("="*70)```## Use Cases & Integration Scenarios### 1. **Git Pre-Receive Hook** (5-second limit)Prevent secrets from ever reaching your repository:```bash#!/bin/bash# .git/hooks/pre-receivepython3 << 'EOF'import sysfrom secret_detector import pre_receive_hookgit_diff = sys.stdin.read()if not pre_receive_hook(git_diff, threshold=0.5):sys.exit(1) # Reject pushEOF```**Impact**: Stops secrets at the source, zero rotation overhead### 2. **GitHub Actions / GitLab CI Pipeline**Scan pull requests before merge:```yaml# .github/workflows/secret-check.ymlname: Secret Detectionon: [pull_request]jobs:scan:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v3with:fetch-depth: 0- name: Scan for secretsrun: |pip install transformers torchpython3 scan_secrets.py```**Impact**: Catch secrets in code review, before they hit main branch### 3. **Splunk/SIEM Integration**Monitor for secrets in historical codebase scans:```pythondef splunk_integration(code_snippets: List[str]):"""Log detected secrets to Splunk for compliance."""detector = SecretDetector()results = detector.detect_secrets(code_snippets)for text, label, confidence in results:if label == "Secret":log_to_splunk({"event": "secret_detected","confidence": confidence,"snippet": text[:100],"severity": "HIGH" if confidence > 0.9 else "MEDIUM"})```### 4. **Confluence / Document Scanning**Scan shared documents for accidentally pasted secrets:```pythondef scan_confluence_pages(pages: List[str]) -> List[dict]:"""Identify secrets in Confluence pages."""detector = SecretDetector()findings = []for page_id, content in pages:results = detector.detect_secrets([content])for text, label, confidence in results:if label == "Secret" and confidence > 0.7:findings.append({"page_id": page_id,"secret": text,"confidence": confidence})return findings```### 5. **Local Development**Developer-friendly warning before commits:```bash# install-hook.shpip install transformers torchpython3 -m huggingface_hub login# Copy pre-commit hookcp ./pre_commit_secret_check.py .git/hooks/pre-commitchmod +x .git/hooks/pre-commit```**Impact**: Developers get instant feedback on typos/mistakes## Performance Benchmarks| Scenario | Latency | Throughput | Notes ||----------|---------|-----------|-------|| Single line (CPU) | ~500ms | - | First run includes model load || Single line (CPU, cached) | ~50ms | - | Subsequent runs || Single line (GPU) | ~100ms | - | With torch.compile || Batch 32 lines (GPU) | ~150ms | 213 lines/sec | Optimal for CI/CD || Batch 128 lines (GPU) | ~400ms | 320 lines/sec | Maximum throughput |**Model Architecture**: DeBERTa-v3-base with 86M parameters**Model Size**: 750MB (safetensors format)**GPU Memory**: ~800MB (inference only)**RAM Usage**: ~800MB (CPU inference)**Vocabulary**: 128K tokens## What Secrets Does It Detect?The model is trained on **generic secret patterns** and can identify:✓ Hardcoded passwords✓ API keys (AWS, GitHub, OpenAI, etc.)✓ Database connection strings✓ OAuth tokens✓ Private keys✓ Authentication credentials (any context)✓ Generic "secret" assignments**Unlike regex tools**, it understands *context* - words like "password123" in comments or documentation won't trigger false positives.## Installation & Requirements```bashpip install transformers torch# Optional: For GPU supportpip install torch --index-url https://download.pytorch.org/whl/cu118```## Deployment Recommendations### Development (CPU)```pythondetector = SecretDetector(device="cpu", compile=False)```- **Setup Time**: ~5 seconds- **Per-line Latency**: ~50-500ms- **Use Case**: Local development, testing### Production (GPU)```pythondetector = SecretDetector(device="cuda", compile=True)```- **Setup Time**: ~15 seconds (first run, compilation included)- **Per-line Latency**: ~100-200ms- **Use Case**: CI/CD pipelines, high-volume scanning### CI/CD Best Practices```yaml# Optimize for speed in pipelinesstrategy:matrix:os: [ubuntu-latest]python-version: ["3.10"]cache:- uses: actions/cache@v3with:path: ~/.cache/huggingfacekey: huggingface-models # Reuse cached model weights```## FAQ**Q: How accurate is this model?**A: Trained on real secret examples, optimized for F1-score. Achieves high precision/recall for generic secrets while minimizing false positives on code comments and documentation.**Q: Can it run in 5 seconds for a pre-receive hook?**A: Yes! Single run takes <100ms (GPU) or <500ms (CPU). Model loading is cached by Git. On first push, allow ~2-3 seconds for initial load.**Q: Does it detect all secrets?**A: It excels at generic secrets (any password/token/key assignment). Highly specific patterns (proprietary internal formats) may need custom fine-tuning.**Q: Is my code sent to Hugging Face?**A: No. Run it locally or on your servers. The model is just weights - inference is completely on-premise.**Q: What about false positives?**A: The model learns context, so `password_hint = "12345"` in documentation won't trigger false alarms like regex tools would.**Q: Can I fine-tune it on my organization's patterns?**A: Yes! The base model is open-source. If you have labeled examples of secrets you want to catch, you can fine-tune a copy.## Limitations- **Single-Line Processing**: Analyzes **one line at a time** (128 tokens max). This means:- Multi-line private keys (PEM format, etc.) won't be fully caught—use regex tools for those- Multi-line JWTs *will* be flagged- For maximum coverage, combine with regex scanners for traditional key formats- **Language Bias**: Trained mainly on Python/JavaScript - other languages may be less accurate- **Redacted Patterns**: `ACCESS_TOKEN_REDACTED` won't be flagged (by design)- **Comments**: Intentional documentation of secrets (for educational purposes) may be flagged## ContributingHave secret patterns your regex tools miss? Want to improve accuracy for specific languages?1. Fork the [model repo](https://huggingface.co/hypn05/secrets-sentinel)2. Fine-tune with your labeled examples3. Share improvements back with the community## LicenseMIT License - Free to use, modify, and deploy in commercial systems. Please include attribution when using this model in your projects.```MIT LicenseCopyright (c) 2026 Hypn05Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.```## CitationIf you use this model in your security workflow, please cite:```bibtex@model{secrets_sentinel_2026,title={Secrets Sentinel},author={Hypn05},year={2026},url={https://huggingface.co/hypn05/secrets-sentinel}}```---**Happy secure coding!**123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591---license: mitlanguage:- enbase_model:- microsoft/deberta-v3-basepipeline_tag: text-classificationlibrary_name: transformerstags:- secret-detection- secrets- security- cybersecurity- devsecops- sast- code-security- code-analysis- supply-chain-security- pre-commit- ci-cd- github-actions- password-detection- api-key-detection- token-detection- credential-detection- secure-coding- deberta- deberta-v2- deberta-v3- text-classification- binary-classificationdatasets:- custommetrics:- f1- precision- recall- accuracywidget:- text: "AWS_SECRET_ACCESS_KEY = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'"example_title: AWS Secret Key- text: "api_key = 'sk-proj-1234567890abcdefghijklmnopqrstuvwxyz'"example_title: OpenAI-style API Key- text: "password = os.environ.get('DB_PASSWORD')"example_title: Safe — env var reference- text: "uses: actions/checkout@v4"example_title: Safe — GitHub Actions step- text: "DB_PASSWORD=null"example_title: Safe — placeholder template- text: "MYSQL_ROOT_PASSWORD: s3cr3tP@ssw0rd#2024"example_title: Hardcoded DB password- text: "ghp_abcDEF123456ghiJKL789012mnoP345678"example_title: GitHub Personal Access Token- text: "private_key = '-----BEGIN RSA PRIVATE KEY-----'"example_title: RSA Private Key headermodel-index:- name: secrets-sentinelresults:- task:type: text-classificationname: Secret / Credential Detectiondataset:name: Synthetic + Real-World Labeled (data_v9 + scan_vuln.db)type: customsplit: testmetrics:- type: f1value: 0.9992name: F1 Score- type: precisionvalue: 0.9983name: Precision- type: recallvalue: 1.0000name: Recall- type: accuracyvalue: 0.9992name: Accuracy---# Secrets Sentinel — v4.0.0> **Context-aware AI secret detection for CI/CD pipelines, pre-commit hooks, and code scanners.**> Fine-tuned DeBERTa-v3-base · F1 = 0.9992 · Precision = 1.0 · <500ms inference · Runs fully on-prem.[](https://huggingface.co/hypn05/secrets-sentinel)[](https://huggingface.co/hypn05/secrets-sentinel-cpu)[](https://opensource.org/licenses/MIT)---## What's New in v4.0.0v4 significantly reduces false positives identified from scanning real-world open-source codebasesand deliberate security testing repositories (OWASP WebGoat, OWASP juice-shop, OWASP wrongsecrets,TruffleHog fixtures, Gitleaks testdata, Plazmaz/leaky-repo, and more):| Pattern Fixed | Example (now correctly classified as safe) ||---|---|| **GitHub Actions pinned SHAs** | `uses: docker/login-action@5e57cd118...ef # v3.6.0` || **`.env.example` placeholders** | `REDIS_PASSWORD=null`, `DB_PASSWORD=YOURPASSWORD` || **PHP config null values** | `'smtp_password' => null,` || **PHP hashids alphabets** | `'alphabet' => 'XKyIAR7mgt8jD2vbqPrOSVenNG...'` || **Laravel route `uses` key** | `'uses' => 'Auth\SamlController@login'` || **Test email addresses** | `enableAdminCC('cc@example.com')` || **Git commit SHAs in test strings** | `"foo [link user@be6a8cc1c1ec...]"` || **Spring annotation values** | `value = "LDAPInjectionVulnerability"` || **JWT expired test payloads** | `{"iat": 1508639612, "exp": 9999999999}` || **DAV/iCal date fields** | `'BDAY' => '20251106'` || **Public installer curls** | `curl -fsSL https://getcomposer.org/installer` || **Localhost service URLs** | `curl http://localhost:8080/health` || **PHP redirect assertions** | `$response->assertRedirect('/login')` || **Dockerfile ENV var refs** | `ENV DB_PASSWORD="${DB_PASSWORD}"` |---## The ProblemSecrets pushed to repositories create a critical, expensive security incident:- **Credential rotation is mandatory** the moment a key hits git history — even for 1 second- **Regex scanners miss generic secrets** (`password = "s3cr3t!"` has no known pattern)- **LLMs are too slow** for pre-receive hooks with 5-second time limits- **False positives kill adoption** — developers disable scanners that cry wolf---## Why This Model?| Approach | Speed | Generic Secrets | FP Rate | Cost ||---|---|---|---|---|| Regex (gitleaks, trufflehog) | ⚡ Fast | ✗ Pattern-only | High | Free || Large LLMs (GPT-4, Claude) | 🐢 >30s | ✓ Excellent | Low | High || **Secrets Sentinel (this model)** | **⚡ <500ms** | **✓ Excellent** | **Very Low** | **Free** |**Key advantage:** Context-aware inference. `password = os.environ.get('DB_PASS')` is safe; `password = "hunter2"` is not. Regex tools can't tell the difference.---## Model Details| Property | Value ||---|---|| **Architecture** | DeBERTa-v3-base (Microsoft) || **Parameters** | 86M || **Task** | Binary sequence classification || **Input** | Single code line or diff line (max 128 tokens) || **Output** | `LABEL_0` = safe, `LABEL_1` = secret detected || **Max line length** | 128 tokens (~500 characters) || **Inference (GPU)** | ~100–200ms/line, ~5ms/line batched || **Inference (CPU)** | ~500ms/line, ~50ms/line batched || **Model size** | ~750 MB (safetensors), ~244 MB (ONNX INT8) || **GPU memory** | ~800 MB (inference) || **License** | MIT |### Training Data (v4)| Source | Lines | Label ||---|---|---|| Synthetic generator (data_v9) | ~135,000 | Mixed || Real-world scan — OWASP apps | ~2,600 | Labeled || Scanner fixture repos (TruffleHog, Gitleaks, leaky-repo, detect-secrets) | ~2,000 | Labeled || Synthetic FP negatives (15 pattern categories) | ~2,700 | Negative || **Total** | **~144,000** | — |### Evaluation History| Version | F1 | Precision | Recall | Accuracy | eval_loss ||---|---|---|---|---|---|| v1.0.0 | 0.9910 | 0.9905 | 0.9915 | 0.9920 | — || v2.0.0 | 0.9976 | 0.9975 | 0.9977 | 0.9977 | 0.0112 || v3.0.0 | 0.9994 | 0.9994 | 0.9994 | 0.9995 | 0.0051 || **v4.0.0** | **0.9992** | **0.9983** | **1.0000** | **0.9992** | **~0.001** |v4 achieves **Recall = 1.0** (zero missed secrets on the held-out eval set) while maintaining near-perfect precision, with the key improvement being elimination of false positives from real-world codebases (GitHub Actions pinned SHAs, `.env.example` templates, PHP config patterns, test fixtures).---## Quick Start### Simplest Usage```pythonfrom transformers import pipelinedetector = pipeline("text-classification", model="hypn05/secrets-sentinel")lines = ["AWS_SECRET_ACCESS_KEY = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'","password = os.environ.get('DB_PASSWORD')","api_key = 'sk-proj-abc123def456ghi789'","uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef","DB_PASSWORD=null",]for line, result in zip(lines, detector(lines)):label = "SECRET" if result["label"] == "LABEL_1" else "safe "print(f"[{label}] {result['score']:.1%} {line[:70]}")```Output:```[SECRET] 100.0% AWS_SECRET_ACCESS_KEY = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'[safe ] 99.8% password = os.environ.get('DB_PASSWORD')[SECRET] 99.9% api_key = 'sk-proj-abc123def456ghi789'[safe ] 99.9% uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef[safe ] 99.7% DB_PASSWORD=null```### Production Class (Batched, GPU-Optimised)```pythonimport torchfrom transformers import AutoTokenizer, AutoModelForSequenceClassificationfrom typing import List, Tupleclass SecretsScanner:"""Production-ready secret scanner with batched inference.Designed for pre-receive hooks (5-second budget) and CI/CD pipelines."""def __init__(self, threshold: float = 0.85, device: str = None, batch_size: int = 256):self.threshold = thresholdself.batch_size = batch_sizeself.device = device or ("cuda" if torch.cuda.is_available() else "cpu")model_id = "hypn05/secrets-sentinel"self.tok = AutoTokenizer.from_pretrained(model_id, use_fast=True)self.mdl = AutoModelForSequenceClassification.from_pretrained(model_id,torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,).to(self.device).eval()def scan(self, lines: List[str]) -> List[Tuple[str, float, bool]]:"""Returns list of (line, confidence, is_secret) tuples.Only lines with confidence >= threshold are flagged."""results = []for i in range(0, len(lines), self.batch_size):batch = lines[i : i + self.batch_size]enc = self.tok(batch, padding=True, truncation=True,max_length=128, return_tensors="pt").to(self.device)with torch.inference_mode():probs = torch.softmax(self.mdl(**enc).logits, dim=1)[:, 1]for line, prob in zip(batch, probs.cpu().tolist()):results.append((line, prob, prob >= self.threshold))return resultsdef scan_diff(self, diff: str) -> List[Tuple[str, float]]:"""Scan a git diff — only checks added lines (starting with +)."""added = [l[1:].strip() for l in diff.splitlines()if l.startswith("+") and not l.startswith("+++")]return [(line, conf) for line, conf, flag in self.scan(added) if flag]```---## Integration Examples### 1. Git Pre-Receive Hook```bash#!/usr/bin/env python3# Save as: .git/hooks/pre-receive (chmod +x)import sys, subprocess, torchfrom transformers import AutoTokenizer, AutoModelForSequenceClassificationTHRESHOLD = 0.85MODEL_ID = "hypn05/secrets-sentinel"tok = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=True)mdl = AutoModelForSequenceClassification.from_pretrained(MODEL_ID).eval()def check_push(old, new, ref):diff = subprocess.check_output(["git", "diff", old, new, "--unified=0"], text=True, errors="ignore")added = [l[1:] for l in diff.splitlines() if l.startswith("+") and not l.startswith("+++")]if not added:return []enc = tok(added, padding=True, truncation=True, max_length=128, return_tensors="pt")probs = torch.softmax(mdl(**enc).logits, dim=1)[:, 1].tolist()return [(line, p) for line, p in zip(added, probs) if p >= THRESHOLD]secrets = []for line in sys.stdin:old, new, ref = line.split()secrets.extend(check_push(old, new, ref))if secrets:print(f"\n\033[31m✗ PUSH REJECTED — {len(secrets)} secret(s) detected:\033[0m")for line, conf in secrets[:5]:print(f" [{conf:.0%}] {line[:100]}")sys.exit(1)print("\033[32m✓ No secrets detected.\033[0m")```### 2. GitHub Actions Workflow```yaml# .github/workflows/secret-scan.ymlname: Secret Detectionon:pull_request:push:branches: [main, master, develop]jobs:scan:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4with:fetch-depth: 0- uses: actions/setup-python@v5with:python-version: "3.11"- name: Install dependenciesrun: pip install transformers torch --quiet- name: Scan for secretsrun: |python3 - <<'EOF'import subprocess, sys, torchfrom transformers import pipelinedetector = pipeline("text-classification", model="hypn05/secrets-sentinel",device=0 if torch.cuda.is_available() else -1)base = subprocess.check_output(["git", "merge-base", "HEAD", "origin/main"], text=True).strip()diff = subprocess.check_output(["git", "diff", base, "HEAD", "--unified=0"], text=True, errors="ignore")lines = [l[1:] for l in diff.splitlines()if l.startswith("+") and not l.startswith("+++") and l[1:].strip()]if not lines:print("No changed lines to scan.")sys.exit(0)results = detector(lines, batch_size=64, truncation=True, max_length=128)findings = [(l, r["score"]) for l, r in zip(lines, results)if r["label"] == "LABEL_1" and r["score"] >= 0.85]if findings:print(f"::error::Found {len(findings)} potential secret(s)!")for line, conf in findings:print(f" [{conf:.0%}] {line[:120]}")sys.exit(1)print(f"✓ Scanned {len(lines)} lines — no secrets detected.")EOF```### 3. Pre-Commit Hook (local development)```yaml# .pre-commit-config.yamlrepos:- repo: localhooks:- id: secrets-sentinelname: Secrets Sentinellanguage: pythonentry: python3 -c "import sys, torchfrom transformers import pipelinedetector = pipeline('text-classification', model='hypn05/secrets-sentinel')lines = [l for l in sys.stdin.read().splitlines() if l.strip()]results = detector(lines, batch_size=32, truncation=True, max_length=128)found = [(l,r) for l,r in zip(lines,results) if r['label']=='LABEL_1' and r['score']>0.85]if found:print(f'BLOCKED: {len(found)} secret(s) detected')sys.exit(1)"pass_filenames: falsealways_run: true```### 4. Python Scanner Script```python#!/usr/bin/env python3"""scan_repo.py — scan an entire directory for hardcoded secrets."""import sysfrom pathlib import Pathfrom transformers import pipelineSKIP_EXTS = {".lock", ".min.js", ".map", ".png", ".jpg", ".pdf"}SKIP_DIRS = {"node_modules", ".git", "vendor", "__pycache__", "dist", "build"}THRESHOLD = 0.85detector = pipeline("text-classification", model="hypn05/secrets-sentinel")root = Path(sys.argv[1] if len(sys.argv) > 1 else ".")findings = []for path in sorted(root.rglob("*")):if not path.is_file():continueif any(d in path.parts for d in SKIP_DIRS):continueif path.suffix.lower() in SKIP_EXTS:continuetry:lines = [l.rstrip() for l in path.read_text(errors="ignore").splitlines()if 4 <= len(l.strip()) <= 500]except Exception:continueif not lines:continueresults = detector(lines, batch_size=64, truncation=True, max_length=128)for ln, (line, result) in enumerate(zip(lines, results), 1):if result["label"] == "LABEL_1" and result["score"] >= THRESHOLD:findings.append((path, ln, line, result["score"]))if findings:print(f"\nFound {len(findings)} potential secret(s):\n")for path, ln, line, conf in sorted(findings, key=lambda x: -x[3]):print(f" [{conf:.0%}] {path}:{ln}")print(f" {line[:100]}")else:print("No secrets detected.")```### 5. CPU-Optimised ONNX VersionFor CPU-only environments (CI agents, lightweight containers):```pythonfrom optimum.onnxruntime import ORTModelForSequenceClassificationfrom transformers import AutoTokenizerimport torch# ~244 MB vs 750 MB, ~4× faster on CPUmodel_id = "hypn05/secrets-sentinel-cpu"tok = AutoTokenizer.from_pretrained(model_id)model = ORTModelForSequenceClassification.from_pretrained(model_id)lines = ["password = 'hunter2'", "name = os.environ.get('USER')"]enc = tok(lines, padding=True, truncation=True, max_length=128, return_tensors="pt")probs = torch.softmax(model(**enc).logits, dim=1)[:, 1]for line, prob in zip(lines, probs):print(f"[{'SECRET' if prob >= 0.85 else 'safe '}] {prob:.1%} {line}")```---## What It DetectsThe model understands **context**, not just patterns. It catches generic secrets that regex tools miss:### True Positives (correctly flagged)```# Hardcoded passwordspassword = "s3cr3tP@ssw0rd#2024"'password' => 'Edward#2025'MYSQL_ROOT_PASSWORD: hunter2# API keys & tokensOPENAI_API_KEY = "sk-proj-abc123..."ghp_aBcDeFgHiJkLmNoPqRsTuVwXyZ123456 # GitHub PATSTRIPE_SECRET_KEY = "sk_live_abc123..."AWS_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"# Database connection stringsDATABASE_URL = "postgresql://admin:secret@db.prod.internal/myapp"MONGODB_URI = "mongodb://root:p@ssword@cluster.mongodb.net/prod"# Private keysprivate_key = "-----BEGIN RSA PRIVATE KEY-----"ssh_key = "-----BEGIN OPENSSH PRIVATE KEY-----"# Webhook secretsWEBHOOK_SECRET = "whsec_abc123xyz789"SLACK_SIGNING_SECRET = "abc123def456ghi789"```### True Negatives (correctly ignored)```# Environment variable references (not hardcoded)password = os.environ.get("DB_PASSWORD")api_key = process.env.API_KEYsecret = System.getenv("JWT_SECRET")# Template / example filesDB_PASSWORD=nullREDIS_PASSWORD=YOURPASSWORDMAIL_PASSWORD=changeme# Code comments and logging# TODO: add password validationlogger.info("Checking password strength")# GitHub Actions (pinned SHAs are NOT secrets)uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef# Test fixtures with obvious placeholdersexpect(user.email).toBe("test@example.com")DB_HOST=localhost```---## Performance Benchmarks| Scenario | Device | Latency | Throughput ||---|---|---|---|| Single line | CPU | ~500ms | — || Single line (cached) | CPU | ~50ms | — || Batch 64 lines | CPU | ~800ms | 80 lines/s || Single line | GPU (A100) | ~8ms | — || Batch 256 lines | GPU (A100) | ~120ms | 2,100 lines/s || Batch 256 lines | GPU (T4) | ~350ms | 730 lines/s || ONNX INT8, batch 64 | CPU | ~200ms | 320 lines/s |**For pre-receive hooks:** A typical 200-line diff scans in <2 seconds on CPU (batch mode).---## Limitations- **Single-line context only** — analyzes one line at a time (128-token max). Multi-line PEM blocks need a dedicated regex check alongside this model.- **Context window** — very long lines are truncated at 128 tokens.- **Custom internal formats** — proprietary secret formats not seen during training may be missed. Fine-tune on your own labeled examples for best results.- **Redacted patterns** — `REDACTED`, `***`, `<secret>` placeholders are intentionally ignored.---## Related Resources- **CPU/ONNX version**: [hypn05/secrets-sentinel-cpu](https://huggingface.co/hypn05/secrets-sentinel-cpu) — INT8-quantized, ~244 MB, 4× smaller- **Base model**: [microsoft/deberta-v3-base](https://huggingface.co/microsoft/deberta-v3-base)- **Similar tools**: [gitleaks](https://github.com/gitleaks/gitleaks), [trufflehog](https://github.com/trufflesecurity/trufflehog), [detect-secrets](https://github.com/Yelp/detect-secrets)---## FAQ**Q: How does it compare to regex-based tools like gitleaks or trufflehog?**A: Those tools excel at known-format secrets (AWS AKIA keys, GitHub `ghp_` tokens). This model catches *generic* secrets — any `password = "..."` or `token = "..."` regardless of format — at the cost of slightly higher false positive rates on edge cases. Best results come from using both: regex tools for known formats, this model for everything else.**Q: Can I fine-tune it on my organisation's patterns?**A: Yes — the base model is MIT-licensed. Label a few hundred examples of your internal secret formats and fine-tune. The architecture (DeBERTa-v3) is well-suited to incremental adaptation.**Q: Does it send my code anywhere?**A: No. Run the model locally or on your own infrastructure. Inference is fully on-premise — only model weights are downloaded from HuggingFace once.**Q: What confidence threshold should I use?**A: `0.85` for pre-receive hooks (low FP, may miss some edge cases). `0.60` for retrospective scans where you want higher recall and can accept some FP for manual review.**Q: How often is the model updated?**A: Continuously — each version is trained on newly identified FP and FN patterns from real-world scanning. v4 specifically addresses GitHub Actions workflow files, PHP config templates, and Laravel test fixtures.---## Citation```bibtex@model{secrets_sentinel_2026,title = {Secrets Sentinel: Context-Aware Secret Detection for CI/CD Pipelines},author = {hypn05},year = {2026},url = {https://huggingface.co/hypn05/secrets-sentinel},note = {Fine-tuned DeBERTa-v3-base for binary secret/safe line classification}}```---## LicenseMIT — free to use, modify, and deploy in commercial systems. Attribution appreciated.---*Built to stop the #1 cause of cloud credential theft: secrets accidentally committed to git.*
123version https://git-lfs.github.com/spec/v1oid sha256:8d1920c33ef031fa6cbe5f78dcf7d25cc619e8e85ac097b6107f21a3302d8e4esize 737719272123version https://git-lfs.github.com/spec/v1oid sha256:24abae7bc410d6bcbfc8a8e2af5c02a9934ca362cb4c7c03dc4402ce43d36a90size 737719272
README.md+591-452
model.safetensors+1-1