@forge12interactive/silentshield-sdk-js
v1.0.1
Published
SilentShield JavaScript SDK for invisible bot protection
Downloads
27
Maintainers
Readme
🚀 Quick Start
Frontend (Browser)
import { SilentShield } from '@forge12interactive/silentshield-sdk-js';
// Initialisierung
const shield = new SilentShield({
siteKey: 'your-site-key-here',
debug: process.env.NODE_ENV === 'development'
});
// Event Listener
shield.addEventListener('ready', () => {
console.log('🛡️ SilentShield ist bereit!');
});
shield.addEventListener('error', (event) => {
console.error('❌ Fehler:', event.detail);
});
// Initialisieren
await shield.initialize();CDN (Browser ohne Build)
<script src="https://unpkg.com/@forge12interactive/[email protected]/dist/index.min.js"></script>
<script>
const shield = new SilentShieldSDK.SilentShield({
siteKey: 'your-site-key-here'
});
shield.addEventListener('ready', () => {
console.log('🛡️ SilentShield bereit!');
});
shield.initialize();
</script>Backend Verifikation (Node.js)
import { SilentShield } from '@forge12interactive/silentshield-sdk-js';
// Nonce vom Frontend verifizieren
try {
const result = await SilentShield.verifyNonce(
'nonce-from-frontend',
'your-api-key',
'https://api.silentshield.io'
);
console.log('Verifikation:', result);
if (result.success) {
// Bot-Schutz bestanden ✅
console.log('✅ Human verified');
} else {
// Bot erkannt ❌
console.log('❌ Bot detected');
}
} catch (error) {
console.error('Verifikation fehlgeschlagen:', error.message);
}📖 Detaillierte Dokumentation
Konfiguration
interface SilentShieldConfig {
siteKey: string; // Ihr Site Key (erforderlich)
apiEndpoint?: string; // Custom API Endpoint
debug?: boolean; // Debug Modus aktivieren
timeout?: number; // Request Timeout (ms)
language?: string; // UI Sprache ('de', 'en', 'fr', ...)
version?: string; // SDK Version
autoFormIntegration?: boolean; // Automatische Formular-Integration
nonceFieldName?: string; // Name des Nonce-Feldes
}
const shield = new SilentShield({
siteKey: 'sk_live_...',
debug: false,
timeout: 10000,
language: 'de',
autoFormIntegration: true,
nonceFieldName: 'captcha_nonce'
});Event System
// Bereit für Verwendung
shield.addEventListener('ready', () => {
console.log('SilentShield bereit');
});
// Fehler aufgetreten
shield.addEventListener('error', (event) => {
console.error('Fehler:', event.detail.code, event.detail.message);
});
// Custom Events
const readyEvent = new CustomEvent('ready');
const errorEvent = new CustomEvent('error', {
detail: { code: 'ERROR_CODE', message: 'Error message' }
});API Methoden
// Status prüfen
if (shield.isReady()) {
console.log('Shield ist bereit');
}
// Ressourcen freigeben
shield.destroy();
// Statische Backend-Verifikation
const verification = await SilentShield.verifyNonce(
'nonce-string',
'api-key',
'https://api.silentshield.io' // optional
);🌐 Framework Integration
React
import React, { useEffect, useState } from 'react';
import { SilentShield } from '@forge12interactive/silentshield-sdk-js';
function ContactForm() {
const [shield, setShield] = useState<SilentShield | null>(null);
const [isReady, setIsReady] = useState(false);
useEffect(() => {
const initShield = async () => {
const instance = new SilentShield({
siteKey: process.env.REACT_APP_SILENT_SHIELD_KEY!,
debug: process.env.NODE_ENV === 'development'
});
instance.addEventListener('ready', () => setIsReady(true));
instance.addEventListener('error', (event) => {
console.error('Shield Error:', event.detail);
});
await instance.initialize();
setShield(instance);
};
initShield();
return () => {
shield?.destroy();
};
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!shield || !isReady) {
alert('Shield noch nicht bereit');
return;
}
// Formular wird automatisch mit Nonce-Feld erweitert
// durch autoFormIntegration: true
const formData = new FormData(e.target as HTMLFormElement);
const response = await fetch('/api/contact', {
method: 'POST',
body: formData
});
if (response.ok) {
alert('Nachricht gesendet!');
}
};
return (
<form onSubmit={handleSubmit}>
<input name="name" type="text" placeholder="Name" required />
<input name="email" type="email" placeholder="E-Mail" required />
<textarea name="message" placeholder="Nachricht" required></textarea>
<button type="submit" disabled={!isReady}>
{isReady ? '📤 Senden' : '⏳ Lade...'}
</button>
{!isReady && (
<p>🛡️ Bot-Schutz wird geladen...</p>
)}
</form>
);
}
export default ContactForm;Vue.js
<template>
<form @submit.prevent="handleSubmit">
<input v-model="form.name" name="name" type="text" placeholder="Name" required />
<input v-model="form.email" name="email" type="email" placeholder="E-Mail" required />
<textarea v-model="form.message" name="message" placeholder="Nachricht" required></textarea>
<button type="submit" :disabled="!isShieldReady">
{{ isShieldReady ? '📤 Senden' : '⏳ Lade...' }}
</button>
</form>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { SilentShield } from '@forge12interactive/silentshield-sdk-js';
const shield = ref<SilentShield | null>(null);
const isShieldReady = ref(false);
const form = ref({
name: '',
email: '',
message: ''
});
onMounted(async () => {
const instance = new SilentShield({
siteKey: import.meta.env.VITE_SILENT_SHIELD_KEY,
debug: import.meta.env.DEV
});
instance.addEventListener('ready', () => {
isShieldReady.value = true;
});
await instance.initialize();
shield.value = instance;
});
onUnmounted(() => {
shield.value?.destroy();
});
const handleSubmit = async () => {
if (!shield.value || !isShieldReady.value) return;
// Automatische Nonce-Integration durch das SDK
const formData = new FormData();
Object.entries(form.value).forEach(([key, value]) => {
formData.append(key, value);
});
await fetch('/api/contact', {
method: 'POST',
body: formData
});
alert('✅ Nachricht gesendet!');
};
</script>Node.js Backend
import express from 'express';
import { SilentShield } from '@forge12interactive/silentshield-sdk-js';
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// API Route mit Bot-Schutz
app.post('/api/contact', async (req, res) => {
const { captcha_nonce, name, email, message } = req.body;
if (!captcha_nonce) {
return res.status(400).json({
error: 'Nonce fehlt - Bot-Schutz erforderlich'
});
}
try {
// Nonce vom Frontend verifizieren
const result = await SilentShield.verifyNonce(
captcha_nonce,
process.env.SILENT_SHIELD_API_KEY!,
'https://api.silentshield.io'
);
if (!result.success) {
return res.status(403).json({
error: 'Bot-Verdacht - Verifikation fehlgeschlagen'
});
}
// Hier normale Verarbeitung
console.log(`Nachricht von ${name} (${email}): ${message}`);
// E-Mail senden, DB speichern, etc.
res.json({
success: true,
message: 'Nachricht erhalten'
});
} catch (error) {
console.error('Verifikationsfehler:', error);
res.status(500).json({ error: 'Server Fehler' });
}
});
app.listen(3000, () => {
console.log('🚀 Server läuft auf Port 3000');
});🔧 Konfiguration & Umgebung
Umgebungsvariablen
# .env Frontend
REACT_APP_SILENT_SHIELD_KEY=sk_live_your_key_here
VITE_SILENT_SHIELD_KEY=sk_live_your_key_here
# .env Backend
SILENT_SHIELD_API_KEY=sk_secret_your_secret_here
SILENT_SHIELD_API_ENDPOINT=https://api.silentshield.ioTypeScript Konfiguration
// tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2022",
"DOM"
],
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true
}
}📊 Error Handling
import { SilentShieldError } from '@forge12interactive/silentshield-sdk-js';
shield.addEventListener('error', (event) => {
const error = event.detail;
if (error instanceof SilentShieldError) {
switch (error.code) {
case 'INITIALIZATION_FAILED':
console.log('Initialisierung fehlgeschlagen:', error.message);
break;
case 'VERIFICATION_FAILED':
console.log('Verifikation fehlgeschlagen:', error.message);
break;
default:
console.log('Unbekannter Fehler:', error.message);
}
}
});🧪 Testing
import { SilentShield } from '@forge12interactive/silentshield-sdk-js';
describe('SilentShield SDK', () => {
let shield: SilentShield;
beforeEach(() => {
shield = new SilentShield({
siteKey: 'test-key',
debug: true
});
});
afterEach(() => {
shield.destroy();
});
it('should initialize correctly', async () => {
await shield.initialize();
expect(shield.isReady()).toBe(true);
});
it('should verify nonce', async () => {
const result = await SilentShield.verifyNonce(
'test-nonce',
'test-api-key'
);
expect(result).toBeDefined();
});
it('should handle errors gracefully', async () => {
// Test mit ungültiger Konfiguration
const invalidShield = new SilentShield({ siteKey: '' });
await expect(invalidShield.initialize()).rejects.toThrow();
});
});🚀 Performance
Bundle Size
- Core: ~8KB (gzipped)
- With dependencies: ~15KB (gzipped)
- Tree-shakeable: ✅
Benchmarks
// Performance Test
const start = performance.now();
const shield = new SilentShield({siteKey: 'test'});
await shield.initialize();
const end = performance.now();
console.log(`Total time: ${end - start}ms`); // ~45ms average🔒 Sicherheit
Best Practices
Site Keys richtig verwenden
// ✅ Frontend - Public Key const shield = new SilentShield({ siteKey: 'sk_live_...' // Public Key }); // ✅ Backend - Secret Key für Verifikation const result = await SilentShield.verifyNonce( nonce, 'sk_secret_...' // Secret Key nur im Backend! );Nonce immer im Backend verifizieren
// Backend Verifikation app.post('/api/action', async (req, res) => { const { captcha_nonce } = req.body; const result = await SilentShield.verifyNonce( captcha_nonce, process.env.SILENT_SHIELD_API_KEY ); if (!result.success) { return res.status(403).json({ error: 'Bot detected' }); } // Sichere Aktion ausführen });Rate Limiting implementieren
import rateLimit from 'express-rate-limit'; const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 Minuten max: 100 // Limit auf 100 Requests pro IP }); app.use('/api/', limiter);
🌍 Browser Unterstützung
| Browser | Version | |---------|---------| | Chrome | 90+ | | Firefox | 88+ | | Safari | 14+ | | Edge | 90+ |
Polyfills
// Für ältere Browser
import 'whatwg-fetch';
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch';
const shield = new SilentShield({
siteKey: 'your-key',
// Polyfills werden automatisch erkannt
});🛠️ Entwicklung
Setup
git clone https://github.com/forge12interactive/silentshield-sdk-js.git
cd silentshield-sdk-js
npm install
npm run build
npm testScripts
npm run build # TypeScript kompilieren
npm run test # Tests ausführen
npm run test:watch # Tests im Watch Mode
npm run lint # Code linting
npm run format # Code formatierung
npm run docs # Dokumentation generieren❓ FAQ
Q: Ist SilentShield DSGVO-konform?
A: Ja, SilentShield verarbeitet keine personenbezogenen Daten und ist vollständig DSGVO-konform.
Q: Funktioniert es mit Content Security Policy (CSP)?
A: Ja, fügen Sie folgende Direktiven hinzu:
script-src 'self' [https://api.silentshield.io](https://api.silentshield.io); connect-src 'self' [https://api.silentshield.io](https://api.silentshield.io);Q: Wie funktioniert die automatische Formular-Integration?
A: Das SDK fügt automatisch ein verstecktes captcha_nonce Feld zu Ihren Formularen hinzu, wenn autoFormIntegration: true gesetzt ist.
Q: Kann ich mehrere Instanzen verwenden?
A: Ja, jede Instanz kann unterschiedliche Konfigurationen haben.
📄 Lizenz
MIT License - siehe LICENSE für Details.
🆘 Support
- 📧 Email: [email protected]
- 💬 Discord: SilentShield Community
- 📖 Docs: silentshield.io/documentation
- 🐛 Issues: GitHub Issues
🙏 Credits
Erstellt mit ❤️ von Forge12 Interactive GmbH
🛡️ Schütze deine Website ohne CAPTCHAs zu nerven!
