Direct API Boilerplate & Code
Production-ready client implementations, typed SDK classes, and end-to-end integration patterns for calling Sherlock trust modules directly from TypeScript, JavaScript, Python, or shell scripts.
1. Environment Setup
Store your Sherlock integration credentials in your server environment:
SHERLOCK_BASE_URL="http://localhost:3000" # or "https://api.yourdomain.com" SHERLOCK_API_KEY="sk_sherlock_your_43_character_secret_token"
2. TypeScript / JavaScript Client Boilerplate
Zero-dependency, typed client implementation compatible with Node.js 18+, Next.js, Express, Fastify, Bun, and Deno:
export class SherlockApiError extends Error {
constructor(public status: number, public code: string, message: string) {
super(message);
this.name = "SherlockApiError";
}
}
export class SherlockClient {
private baseUrl: string;
private apiKey: string;
constructor(options?: { baseUrl?: string; apiKey?: string }) {
this.baseUrl = (options?.baseUrl || process.env.SHERLOCK_BASE_URL || "http://localhost:3000").replace(/\/+$/, "");
this.apiKey = options?.apiKey || process.env.SHERLOCK_API_KEY || "";
if (!this.apiKey) {
throw new Error("SherlockClient: SHERLOCK_API_KEY must be configured.");
}
}
/** Generic invocation for any supported Sherlock module */
async callModule<TInput extends Record<string, unknown>, TOutput>(
module: "policy" | "voiceprint" | "pulse" | "passport" | "frontdoor" | "gate" | "ledger",
operation: string,
input: TInput
): Promise<TOutput> {
const url = `${this.baseUrl}/api/v1/modules/${module}`;
const response = await fetch(url, {
method: "POST",
headers: {
"Authorization": `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ operation, input }),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
throw new SherlockApiError(
response.status,
data.error || "unknown_error",
data.message || `Module call to '${module}.${operation}' failed with status ${response.status}`
);
}
return data.output as TOutput;
}
/** Policy Module: Evaluate symbolic risk and authorization rules */
readonly policy = {
evaluate: (input: {
authenticity: "PASS" | "FAIL" | "UNCERTAIN";
identity: "MATCH" | "NO_MATCH" | "UNCERTAIN";
action: "balance" | "statement" | "transfer" | "faq" | "limits" | "unknown";
budget: number;
stickyFail: boolean;
shortAudio: boolean;
amount?: number;
demoTransferThreshold?: number;
}) => this.callModule<typeof input, {
decision: "ALLOW" | "STEP_UP" | "HOLD" | "SPEAK_MORE";
ruleId: string;
explanation: string;
budgetMovement: number;
cost: number;
advisory: boolean;
}>("policy", "evaluate", input),
};
/** Voiceprint Module: Biometric spoof detection and speaker verification */
readonly voiceprint = {
detect: (input: { audio: string; consent: true }) =>
this.callModule<typeof input, { status: "PASS" | "FAIL" | "UNCERTAIN"; score: number; reference: string }>(
"voiceprint", "detect", input
),
verify: (input: { audio: string; consent: true; speakerId: string }) =>
this.callModule<typeof input, { status: "MATCH" | "NO_MATCH" | "UNCERTAIN"; score: number; reference: string }>(
"voiceprint", "verify", input
),
enrol: (input: { audio: string; consent: true; speakerId: string; name?: string }) =>
this.callModule<typeof input, { speakerId: string; status: string; audioHash: string }>(
"voiceprint", "enrol", input
),
speakerDelete: (speakerId: string) =>
this.callModule<{ speakerId: string }, { speakerId: string; deleted: boolean }>(
"voiceprint", "speaker_delete", { speakerId }
),
credits: () =>
this.callModule<Record<string, never>, { providerAvailable: boolean; usage: Array<{ operation: string; attempts: number }>; window: string }>(
"voiceprint", "credits", {}
),
};
/** Frontdoor Module: Intent parsing and bounded AI assistance proposals */
readonly frontdoor = {
propose: (transcript: string) =>
this.callModule<{ transcript: string }, {
intent: string;
reply: string;
toolRequest: { action: string; parameters: Record<string, unknown> } | null;
delegationTranscript?: string;
executionAuthorized: boolean;
}>("frontdoor", "propose", { transcript }),
};
/** Gate Module: Cryptographic parameter hashing */
readonly gate = {
hash: (parameters: Record<string, string | number | boolean>) =>
this.callModule<typeof parameters, { parametersHash: string; executionAuthorized: boolean }>(
"gate", "hash", parameters
),
};
/** Pulse Module: Trust telemetry and latency aggregation */
readonly pulse = {
observe: (input: { samples: number[]; latencies?: number[] }) =>
this.callModule<typeof input, { count: number; latest: number | null; mean: number | null; meanLatencyMs: number | null }>(
"pulse", "observe", input
),
};
/** Ledger Module: Cryptographic hash chain audit verification */
readonly ledger = {
verify: (input: { epoch: string; entries: unknown[] }) =>
this.callModule<typeof input, { valid: boolean; count: number; headHash: string; errorIndex?: number; reason?: string }>(
"ledger", "verify", input
),
};
}3. Python Client Boilerplate
Clean, idiomatic Python 3 implementation with typed error handling:
import os
import json
import urllib.request
import urllib.error
from typing import Dict, Any, Optional
class SherlockApiError(Exception):
def __init__(self, status: int, code: str, message: str):
super().__init__(f"[{status}] {code}: {message}")
self.status = status
self.code = code
self.message = message
class SherlockClient:
def __init__(self, base_url: Optional[str] = None, api_key: Optional[str] = None):
self.base_url = (base_url or os.getenv("SHERLOCK_BASE_URL", "http://localhost:3000")).rstrip("/")
self.api_key = api_key or os.getenv("SHERLOCK_API_KEY", "")
if not self.api_key:
raise ValueError("SherlockClient requires SHERLOCK_API_KEY to be set.")
def call_module(self, module: str, operation: str, input_data: Dict[str, Any]) -> Dict[str, Any]:
url = f"{self.base_url}/api/v1/modules/{module}"
payload = json.dumps({"operation": operation, "input": input_data}).encode("utf-8")
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
req = urllib.request.Request(url, data=payload, headers=headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=45) as response:
result = json.loads(response.read().decode("utf-8"))
return result.get("output", {})
except urllib.error.HTTPError as e:
try:
err_data = json.loads(e.read().decode("utf-8"))
code = err_data.get("error", "http_error")
msg = err_data.get("message", e.reason)
except Exception:
code, msg = "http_error", e.reason
raise SherlockApiError(e.code, code, msg)
# Convenience Module Methods
def evaluate_policy(self, authenticity: str, identity: str, action: str, budget: int = 100, **kwargs):
data = {"authenticity": authenticity, "identity": identity, "action": action, "budget": budget, "stickyFail": False, "shortAudio": False, **kwargs}
return self.call_module("policy", "evaluate", data)
def detect_voice(self, base64_audio: str):
return self.call_module("voiceprint", "detect", {"audio": base64_audio, "consent": True})
def verify_voice(self, base64_audio: str, speaker_id: str):
return self.call_module("voiceprint", "verify", {"audio": base64_audio, "consent": True, "speakerId": speaker_id})
def propose_action(self, transcript: str):
return self.call_module("frontdoor", "propose", {"transcript": transcript})
def hash_parameters(self, params: Dict[str, Any]):
return self.call_module("gate", "hash", params)4. End-to-End Use Case Recipes
Recipe 1: Pre-Transaction Policy Check (E-commerce / Banking)
Evaluate symbolic risk thresholds before authorizing a financial transfer or high-value checkout operation in your existing backend:
import { SherlockClient } from "./sherlock-client";
const sherlock = new SherlockClient();
export async function processTransfer(userId: string, amountMinorUnits: number) {
// Step 1: Query symbolic policy rules
const policyResult = await sherlock.policy.evaluate({
authenticity: "PASS",
identity: "MATCH",
action: "transfer",
amount: amountMinorUnits,
budget: 95,
stickyFail: false,
shortAudio: false,
});
// Step 2: Handle policy decision
if (policyResult.decision === "STEP_UP") {
return { status: "step_up_required", reason: policyResult.explanation };
}
if (policyResult.decision !== "ALLOW") {
throw new Error(`Transfer blocked by policy: ${policyResult.explanation}`);
}
// Step 3: Compute canonical parameter hash for audit ledger
const gateResult = await sherlock.gate.hash({
userId,
amount: amountMinorUnits,
currency: "INR",
ruleId: policyResult.ruleId,
});
return {
status: "authorized",
parametersHash: gateResult.parametersHash,
remainingBudget: 95 + policyResult.budgetMovement,
};
}Recipe 2: Voice Biometrics & Anti-Spoofing in Call Centers / IVR
Verify caller voice authenticity and speaker identity from incoming PCM16 audio buffers before granting access to sensitive account operations:
import { SherlockClient } from "./sherlock-client";
const sherlock = new SherlockClient();
export async function verifyCallerAudio(callerSpeakerId: string, pcm16WavBuffer: Buffer) {
const base64Audio = pcm16WavBuffer.toString("base64");
// Step 1: Detect spoofing, deepfakes, or replay attacks
const detection = await sherlock.voiceprint.detect({
audio: base64Audio,
consent: true,
});
if (detection.status !== "PASS") {
return {
verified: false,
reason: "Voice authenticity failed. Synthetic speech or replay detected.",
traceRef: detection.reference,
};
}
// Step 2: 1:1 Biometric speaker verification
const verification = await sherlock.voiceprint.verify({
audio: base64Audio,
consent: true,
speakerId: callerSpeakerId,
});
return {
verified: verification.status === "MATCH",
confidence: verification.score,
traceRef: verification.reference,
};
}Recipe 3: Conversational AI Intent Proposal
Translate customer voice or text inquiries into safe, bounded action proposals:
import { SherlockClient } from "./sherlock-client";
const sherlock = new SherlockClient();
export async function handleCustomerMessage(messageText: string) {
const proposal = await sherlock.frontdoor.propose(messageText);
console.log("Customer Intent:", proposal.intent);
console.log("Proposed Assistant Reply:", proposal.reply);
if (proposal.toolRequest) {
console.log("Proposed Action:", proposal.toolRequest.action);
console.log("Action Parameters:", proposal.toolRequest.parameters);
}
// Remember: executionAuthorized is always false. Pass tool proposals
// to your server Policy checks before performing any real mutations.
return proposal;
}Recipe 4: Batch Audit Verification with Ledger
Periodically verify exported cryptographic hash chains to ensure offline compliance and unbroken audit integrity:
import { SherlockClient } from "./sherlock-client";
const sherlock = new SherlockClient();
export async function auditEpoch(epochId: string, chainEntries: any[]) {
const result = await sherlock.ledger.verify({
epoch: epochId,
entries: chainEntries,
});
if (!result.valid) {
console.error(`Audit violation in epoch ${epochId} at index ${result.errorIndex}: ${result.reason}`);
throw new Error("Audit chain tampered or corrupted.");
}
console.log(`Successfully verified ${result.count} audit entries. Head Hash: ${result.headHash}`);
return result;
}5. Complete cURL Command Cookbook
Quick reference commands for testing all active module endpoints from any terminal:
# 1. Policy Evaluation
curl -X POST "$SHERLOCK_BASE_URL/api/v1/modules/policy" \
-H "Authorization: Bearer $SHERLOCK_API_KEY" \
-H "Content-Type: application/json" \
-d '{"operation":"evaluate","input":{"authenticity":"PASS","identity":"MATCH","action":"balance","budget":100,"stickyFail":false,"shortAudio":false}}'
# 2. Voiceprint Anti-Spoof Detection
curl -X POST "$SHERLOCK_BASE_URL/api/v1/modules/voiceprint" \
-H "Authorization: Bearer $SHERLOCK_API_KEY" \
-H "Content-Type: application/json" \
-d '{"operation":"detect","input":{"audio":"UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=","consent":true}}'
# 3. Frontdoor AI Intent Proposal
curl -X POST "$SHERLOCK_BASE_URL/api/v1/modules/frontdoor" \
-H "Authorization: Bearer $SHERLOCK_API_KEY" \
-H "Content-Type: application/json" \
-d '{"operation":"propose","input":{"transcript":"I would like to check my savings balance"}}'
# 4. Gate Parameter Hashing
curl -X POST "$SHERLOCK_BASE_URL/api/v1/modules/gate" \
-H "Authorization: Bearer $SHERLOCK_API_KEY" \
-H "Content-Type: application/json" \
-d '{"operation":"hash","input":{"accountId":"acc_101","payeeId":"acc_202","amount":5000}}'
# 5. Pulse Telemetry Aggregation
curl -X POST "$SHERLOCK_BASE_URL/api/v1/modules/pulse" \
-H "Authorization: Bearer $SHERLOCK_API_KEY" \
-H "Content-Type: application/json" \
-d '{"operation":"observe","input":{"samples":[92,88,95],"latencies":[120,140,110]}}'
# 6. Passport Integration Identification
curl -X POST "$SHERLOCK_BASE_URL/api/v1/modules/passport" \
-H "Authorization: Bearer $SHERLOCK_API_KEY" \
-H "Content-Type: application/json" \
-d '{"operation":"identity","input":{}}'