JavaScript / TypeScript SDK
The @surfinguard/sdk package provides a Guard class that works in two modes: local (on-device, zero-latency) and API (cloud-powered with LLM enhancement).
Installation
npm install @surfinguard/sdkRequires Node.js 20 or later. The package is ESM-only.
Quick Start
import { Guard } from '@surfinguard/sdk';
// Local mode - no API key needed, zero network calls
const guard = await Guard.create({ mode: 'local' });
const result = guard.checkUrl('https://example.com');
console.log(result.level); // "SAFE"Guard Modes
Local Mode
Local mode runs the full CoreEngine on-device. All 18 analyzers execute locally with zero network calls.
const guard = await Guard.create({ mode: 'local' });
// Synchronous - returns CheckResult directly
const result = guard.checkUrl('https://example.com');Use Guard.create() (async factory) for local mode. This initializes the CoreEngine and pattern databases.
API Mode
API mode sends requests to the Surfinguard cloud API. Supports LLM enhancement for deeper analysis.
const guard = new Guard({
mode: 'api',
apiKey: 'sg_live_your_key_here',
baseUrl: 'https://api.surfinguard.com', // optional, uses default
});
// Asynchronous - returns Promise<CheckResult>
const result = await guard.checkUrl('https://example.com');For API mode, use new Guard() (synchronous constructor).
Recommendation: Always await check methods regardless of mode. Local mode returns a value that is safe to await, so your code works in both modes.
Check Methods
All 18 action types have dedicated check methods:
// URL analysis
guard.checkUrl(url: string): CheckResult
// Command analysis
guard.checkCommand(command: string): CheckResult
// Text / prompt injection detection
guard.checkText(text: string): CheckResult
// File operations
guard.checkFileRead(path: string): CheckResult
guard.checkFileWrite(path: string, content?: string): CheckResult
// API call analysis
guard.checkApiCall(value: string, metadata?: object): CheckResult
// Database query analysis
guard.checkQuery(query: string): CheckResult
// Code analysis
guard.checkCode(code: string, metadata?: object): CheckResult
// Message analysis
guard.checkMessage(message: string, metadata?: object): CheckResult
// Transaction analysis
guard.checkTransaction(value: string, metadata?: object): CheckResult
// Auth action analysis
guard.checkAuth(value: string, metadata?: object): CheckResult
// Git operation analysis
guard.checkGit(value: string, metadata?: object): CheckResult
// UI action analysis
guard.checkUiAction(value: string, metadata?: object): CheckResult
// Infrastructure analysis
guard.checkInfra(value: string, metadata?: object): CheckResult
// Agent communication analysis
guard.checkAgentComm(value: string, metadata?: object): CheckResult
// Data pipeline analysis
guard.checkDataPipeline(value: string, metadata?: object): CheckResult
// Document analysis
guard.checkDocument(value: string, metadata?: object): CheckResult
// IoT analysis
guard.checkIot(value: string, metadata?: object): CheckResultUniversal Check
The check() method accepts any action type:
const result = guard.check({
type: 'url',
value: 'https://g00gle-login.tk/verify',
});
// With metadata
const result = guard.check({
type: 'command',
value: 'rm -rf /tmp/build',
metadata: { workingDirectory: '/home/user' },
});Batch Check
Check multiple actions in a single call (API mode only):
const results = await guard.checkBatch([
{ type: 'url', value: 'https://example.com' },
{ type: 'command', value: 'ls -la' },
{ type: 'text', value: 'Hello world' },
]);
// Returns CheckResult[]CheckResult Type
Every check method returns a CheckResult:
interface CheckResult {
score: number; // 0-10 composite score
level: 'SAFE' | 'CAUTION' | 'DANGER';
primitives: {
DESTRUCTION: number;
EXFILTRATION: number;
ESCALATION: number;
PERSISTENCE: number;
MANIPULATION: number;
};
reasons: string[]; // Human-readable explanations
threats: Threat[]; // Detailed threat matches
metadata?: object; // Additional context
}
interface Threat {
id: string; // e.g., "U05"
name: string; // e.g., "Brand impersonation"
score: number; // Base score for this threat
primitive: string; // Which primitive it maps to
}Policy Enforcement
Policies define what happens when an action exceeds a risk level:
const guard = await Guard.create({
mode: 'local',
policy: 'strict', // 'permissive' | 'moderate' | 'strict'
});
try {
guard.checkUrl('https://g00gle-login.tk/verify');
} catch (error) {
if (error instanceof NotAllowedError) {
console.log('Action blocked by policy');
console.log(error.result); // The underlying CheckResult
}
}| Policy | SAFE | CAUTION | DANGER |
|---|---|---|---|
permissive | Allow | Allow | Allow |
moderate | Allow | Allow | Throw NotAllowedError |
strict | Allow | Throw NotAllowedError | Throw NotAllowedError |
Session Tracking
Track actions within a session to detect multi-step attack chains:
const session = await guard.getSession('session-123');
console.log(session); // { id, actions, chainPatterns }
// Reset a session
await guard.resetSession('session-123');Health Check
const health = await guard.health();
console.log(health);
// { version: "6.0.0", analyzers: 18, uptime: ... }Error Handling
The SDK provides a typed error hierarchy:
import {
SurfinguardError,
AuthenticationError,
RateLimitError,
APIError,
NotAllowedError,
} from '@surfinguard/sdk';
try {
await guard.checkUrl('https://example.com');
} catch (error) {
if (error instanceof AuthenticationError) {
// Invalid or expired API key (401)
} else if (error instanceof RateLimitError) {
// Rate limit exceeded (429)
console.log(error.retryAfter); // seconds until reset
} else if (error instanceof NotAllowedError) {
// Policy blocked the action
console.log(error.result); // CheckResult that triggered the block
} else if (error instanceof APIError) {
// Other API errors (4xx/5xx)
console.log(error.statusCode);
}
}TypeScript Types
All types are exported from the package:
import type {
CheckResult,
Threat,
RiskLevel,
RiskPrimitive,
ActionType,
GuardOptions,
} from '@surfinguard/sdk';Telemetry
Opt-in anonymous telemetry helps improve threat detection:
const guard = await Guard.create({
mode: 'local',
telemetry: true, // opt-in
});Telemetry sends SHA-256 hashed action values (never plaintext) to the threat intelligence feed. It is disabled by default.
Compliance
Assess EU AI Act compliance for your AI system:
const assessment = await guard.assessCompliance({
systemType: 'chatbot',
domain: 'customer-service',
hasHumanOversight: true,
});
console.log(assessment.riskLevel); // "limited"
console.log(assessment.requirements); // [...]