@torknetwork/sdk
v2.0.0
Published
Tork Governance SDK - PII detection, policy enforcement, and AI agent governance for JavaScript/TypeScript
Downloads
204
Maintainers
Readme
@torknetwork/sdk
Official JavaScript/TypeScript SDK for Tork Governance - AI agent governance, PII detection, and policy enforcement.
Installation
npm install @torknetwork/sdkQuick Start
PII Detection & Redaction
import { PIIRedactor } from '@torknetwork/sdk';
const redactor = new PIIRedactor();
// Detect PII
const matches = redactor.detect('Email: [email protected], SSN: 123-45-6789');
console.log(matches);
// [
// { type: 'EMAIL', value: '[email protected]', start: 7, end: 23, confidence: 0.95 },
// { type: 'SSN', value: '123-45-6789', start: 30, end: 41, confidence: 0.95 }
// ]
// Redact PII
const result = redactor.redact('My email is [email protected]');
console.log(result.redacted);
// 'My email is [EMAIL]'Governance Engine (Local)
import { GovernanceEngine } from '@torknetwork/sdk';
const engine = new GovernanceEngine();
const result = engine.evaluate({
agentId: 'my-agent',
payload: { message: 'User SSN is 123-45-6789' }
});
console.log(result.decision); // 'block'
console.log(result.score); // 25
console.log(result.piiMatches); // [{ type: 'SSN', ... }]
console.log(result.receipt.id); // 'tork_xxx_yyy'API Client
import { TorkClient } from '@torknetwork/sdk';
const client = new TorkClient({
apiKey: 'your-api-key'
});
// Govern content via the live API (POST /api/v1/govern)
const result = await client.govern('Hello world', { agentId: 'my-agent' });
console.log(result.action, result.governance_dna.score);
// Structured-payload convenience wrapper (also hits /govern)
const evaluated = await client.evaluate({
agentId: 'my-agent',
payload: { message: 'Hello world' }
});Express Middleware
import express from 'express';
import { torkMiddleware } from '@torknetwork/sdk/express';
const app = express();
app.use(express.json());
// Add governance middleware
app.use('/api', torkMiddleware({
agentId: 'my-api',
mode: 'enforce',
localMode: true,
excludePaths: ['/health']
}));
app.post('/api/chat', (req, res) => {
// req.body is automatically redacted if PII was found
// req.tork contains the governance result
res.json({ received: req.body });
});Features
PII Detection (20+ Types)
| Type | Example |
|------|---------|
| EMAIL | [email protected] |
| PHONE | (555) 123-4567 |
| SSN | 123-45-6789 |
| CREDIT_CARD | 4532-0151-1283-0366 |
| IP_ADDRESS | 192.168.1.1 |
| AWS_ACCESS_KEY | AKIAIOSFODNN7EXAMPLE |
| AWS_SECRET_KEY | wJalrXUtnFEMI/K7MDENG... |
| GITHUB_TOKEN | ghp_xxxxxxxxxxxx |
| STRIPE_KEY | sk_live_xxxxx |
| JWT_TOKEN | eyJhbGciOiJ... |
| IBAN | DE89370400440532013000 |
| PASSPORT | A12345678 |
| PRIVATE_KEY | -----BEGIN PRIVATE KEY----- |
| And more... | |
Governance Decisions
allow- Request is safeblock- Request contains high-risk contentredact- PII detected and redactedreview- Flagged for human review
Risk Scoring
Each PII type has a risk weight (0-35). Scores are calculated based on:
- Type of PII found
- Detection confidence
- Number of occurrences
| Risk Level | Score Range | |------------|-------------| | Low | 0-20 | | Medium | 20-50 | | High | 50-80 | | Critical | 80-100 |
API Reference
PIIRedactor
const redactor = new PIIRedactor({
types: ['EMAIL', 'SSN'], // Filter PII types
minConfidence: 0.8, // Minimum confidence threshold
replacement: '[REDACTED]', // Custom replacement text
});
redactor.detect(text: string): PIIMatch[]
redactor.redact(text: string): RedactionResult
redactor.containsPII(text: string): boolean
redactor.getSummary(text: string): Record<PIIType, number>GovernanceEngine
const engine = new GovernanceEngine({
policies: [...], // Custom policy rules
piiTypes: ['EMAIL', 'SSN'], // PII types to scan
thresholds: {
block: 80,
review: 50,
redact: 20,
},
});
engine.evaluate(request): EvaluationResult
engine.addPolicy(policy): void
engine.removePolicy(policyId): boolean
engine.getPolicies(): PolicyRule[]TorkClient
const client = new TorkClient({
apiKey: 'xxx',
// baseUrl includes the /api/v1 prefix; methods use bare paths.
baseUrl: 'https://tork.network/api/v1',
timeout: 30000,
retries: 3,
});
await client.govern(content, options?): GovernResponse // POST /api/v1/govern
await client.evaluate({ agentId, payload }): EvaluateResponse // -> /govern
await client.redact(text): RedactResponse // -> /govern (mode: redact)
await client.getAuditLogs(options?): AuditLogsResponse // GET /api/v1/audit-logs
await client.health(): { status, version } // GET /api/v1/health
getScore()was removed in favour ofgovern().governance_dna.score— the API has no standalone per-agent score endpoint.
Express Middleware
import { torkMiddleware, piiRedactionMiddleware } from '@torknetwork/sdk/express';
// Full governance
app.use(torkMiddleware({
agentId: 'my-api',
mode: 'enforce', // 'enforce' | 'warn' | 'audit'
localMode: true, // Use local engine (no API calls)
apiKey: 'xxx', // Required if localMode: false
excludePaths: ['/health'],
onDecision: (result, req, res) => { ... },
}));
// PII redaction only
app.use(piiRedactionMiddleware({
agentId: 'my-api',
}));Custom Policies
const engine = new GovernanceEngine({
policies: [
{
id: 'block-secrets',
name: 'Block Secrets',
condition: {
piiTypes: ['AWS_SECRET_KEY', 'PRIVATE_KEY'],
},
action: 'block',
priority: 100,
},
{
id: 'review-keywords',
name: 'Review Sensitive Keywords',
condition: {
keywords: ['confidential', 'internal only'],
riskScoreThreshold: 30,
},
action: 'review',
priority: 50,
},
{
id: 'custom-check',
name: 'Custom Check',
condition: {
custom: (request, piiMatches) => {
return request.context?.userId === 'admin';
},
},
action: 'allow',
priority: 200,
},
],
});License
MIT - see LICENSE
