Vril.jsDocsv2.1.0

Introduction

Vril.js is the security-first React framework by VRIL LABS. It provides post-quantum cryptography, zero-trust security membranes, and crypto agility built into every layer of the React framework — with zero external dependencies. Every cryptographic operation uses the Web Crypto API natively available in modern browsers, ensuring maximum performance and minimum attack surface.

With 26 framework modules, 200+ exports, and full post-quantum support (ML-KEM-768, ML-DSA-65, SLH-DSA), Vril.js is designed for applications where security is not optional — it is foundational. The framework implements a 5-layer security architecture spanning browser hardening, transport security, cryptographic operations, application-level protections, and build-time integrity verification.

26
Modules
200+
Exports
0
Dependencies
Full
PQC

Installation

Create a new Vril.js project with the official CLI, or add Vril.js to an existing Next.js project.

ts
# Create a new project
npx create-vril-app@latest my-app
cd my-app
npm run dev

# Or add to existing project
npm install vril-js

# Verify installation
npx vril doctor

Requires Node.js 18.17+, React 19+, and a browser with Web Crypto API support (Chrome 96+, Firefox 94+, Safari 15.4+).

Configuration (vril.config.ts)

Vril.js uses a vril.config.tsfile at the project root, similar to Next.js's next.config.ts. This file controls all framework behavior including security policies, cryptography settings, routing, build security, and authentication.

ts
import { defineVrilConfig } from './src/lib/vril/config/define';

export default defineVrilConfig({
  security: {
    trustedTypes: true,
    apiMembrane: true,
    csp: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      objectSrc: ["'none'"],
    },
    csrf: {
      enabled: true,
      tokenHeader: 'x-vril-csrf',
      sameSite: 'Strict',
    },
  },
  crypto: {
    defaultAlgorithm: 'aes-256-gcm',
    kdfIterations: 600000,    // OWASP: 600K+
    pqcEnabled: true,
    hybridMode: true,
    keyRotationDays: 90,
  },
  build: {
    cspNonce: true,
    sriHashes: true,
    sbom: true,
  },
  auth: {
    sessionTTL: 86400000,
    passwordMinLength: 12,
  },
});

Quick Start

ts
import { createVrilApp, VrilVault, PQCHandler, signal } from '@/lib/vril';

// 1. Create your secure app
const app = createVrilApp({
  security: { trustedTypes: true, apiMembrane: true },
  crypto: { pqcEnabled: true, hybridMode: true },
});

// 2. Encrypt sensitive data with ΩVault
const vault = new VrilVault(600000);
const encrypted = await vault.encrypt('passphrase', 'sensitive data');
const decrypted = await vault.decrypt('passphrase', encrypted);

// 3. Post-quantum key exchange
const pqc = new PQCHandler();
const hybridKey = await pqc.generateHybridKeyPair();

// 4. Reactive state with ΩSignal
const count = signal(0);
const doubled = computed(() => count() * 2);
effect(() => console.log(`Count: ${count()}, Doubled: ${doubled()}`));
count.set(1);

vril/core

The core module provides framework initialization, environment detection, feature flags, plugin lifecycle management, and performance profiling. It is the entry point for configuring and bootstrapping a Vril.js application.

ExportTypeDescription
createVrilApp()functionCreate and configure a Vril.js application instance
DEFAULT_VRIL_CONFIGconstDefault security-first configuration object
detectEnvironment()functionDetect runtime: browser, server, edge, or Node.js
envconstPre-computed environment info (isServer, isClient, isEdge, isDev)
FeatureFlagsclassFeature flag system with rollout percentage support
PluginLifecycleRegistryclassRegister and invoke plugin lifecycle hooks
AppContextclassSingleton application context shared across modules
VersionTrackerclassFramework version tracking with migration support
PerformanceProfilerclassHigh-resolution timing for crypto and rendering ops
ts
import { createVrilApp, env, FeatureFlags } from '@/lib/vril/core';

const app = createVrilApp({
  security: { trustedTypes: true, apiMembrane: true },
  crypto: { pqcEnabled: true, hybridMode: true },
});

// Environment detection
console.log(env.isServer, env.isClient, env.isEdge);

// Feature flags with gradual rollout
const flags = new FeatureFlags();
flags.register('pqc-v2', { enabled: true, rollout: 25 }); // 25% rollout
if (flags.isEnabled('pqc-v2')) { /* use new PQC API */ }

vril/config

The config module provides type-safe configuration with validation, deep merging, environment-specific overrides, encrypted secrets management, and runtime config watching. It powers the vril.config.ts file.

ExportTypeDescription
createConfig()functionType-safe config builder with validation and secrets
ConfigValidatorclassValidate config values against a schema definition
ConfigMergerclassDeep merge with 4 conflict resolution strategies
EnvironmentConfigclassDev/staging/prod/test environment-specific overrides
ConfigSecretsclassAES-GCM encrypted secrets with PBKDF2 key derivation
ConfigWatcherclassWatch environment variables for runtime config changes
ts
import { createConfig, EnvironmentConfig } from '@/lib/vril/config';

const envConfig = EnvironmentConfig.createWithPresets();
const { config, validate } = createConfig({
  base: { crypto: { kdfIterations: 600000 } },
  environment: envConfig,
});

const result = validate();
if (!result.valid) {
  console.error('Config errors:', result.errors);
}

vril/plugin

Plugin architecture with lifecycle hooks, dependency resolution, sandboxed loading, and integrity verification. Plugins can extend any part of the framework without modifying core code.

ExportTypeDescription
createPlugin()functionFluent builder for type-safe plugin creation
PluginRegistryclassRegister, enable, disable, and configure plugins
PluginLoaderclassLoad plugins with SHA-256 integrity verification
PluginContextinterfaceShared context between plugins with crypto utilities
ts
import { createPlugin, PluginRegistry } from '@/lib/vril/plugin';

const auditPlugin = createPlugin('security-audit')
  .onInit((ctx) => { ctx.log('Audit plugin initialized'); })
  .onRequest((ctx) => { ctx.log('Request intercepted'); })
  .build();

const registry = new PluginRegistry();
registry.register(auditPlugin);
registry.initializeAll();

vril/types

Central type definitions including branded security types that provide compile-time guarantees. SecureString, Encrypted<T>, Hashed<T>, and Signed<T> prevent accidental misuse of sensitive data at the type level.

ExportTypeDescription
SecurityLevelenumnone | low | medium | high | critical
SecureStringtypeBranded string that has been security-validated
Encrypted&lt;T&gt;typeBranded type for encrypted data — cannot be used as plaintext
Hashed&lt;T&gt;typeBranded type for hashed data
Signed&lt;T&gt;typeBranded type for cryptographically signed data
AlgorithmIdentifiertypeUnion of all 23 supported algorithm identifiers
ts
import type { SecureString, Encrypted, SecurityLevel } from '@/lib/vril/types';

// Branded types prevent accidental misuse at compile time
function processSecure(input: SecureString) { /* ... */ }
// processSecure('plain'); // TypeScript error!
// processSecure(validate('plain') as SecureString); // OK

// Encrypted<T> cannot be accidentally treated as plaintext
function decrypt<T>(data: Encrypted<T>): T { /* ... */ }

vril/security

The security module provides Trusted Types enforcement, HTML sanitization, URL validation, Content Security Policy building, Permissions-Policy construction, and the zero-trust API membrane. It forms the outermost defense layer of Vril.js.

ExportTypeDescription
installTrustedTypes()functionInstall Trusted Types policy to prevent DOM XSS
installAPIMembrane()functionBlock dangerous browser APIs at runtime
DOMPSanitizerclassZero-dependency HTML sanitizer (no DOMPurify needed)
URLValidatorclassValidate URLs to prevent javascript:/data: XSS attacks
ContentSecurityPolicyclassFluent CSP builder with nonce and report support
PermissionsPolicyBuilderclassFluent Permissions-Policy builder
SecurityContextclassRuntime security context with state tracking
IntegrityCheckerclassSHA-256 integrity verification for DOM elements
ts
import { installTrustedTypes, installAPIMembrane, DOMPSanitizer } from '@/lib/vril/security';

// Install zero-trust membrane
installTrustedTypes();
installAPIMembrane(['WebTransport', 'RTCPeerConnection']);

// Sanitize untrusted HTML
const sanitizer = new DOMPSanitizer();
const safe = sanitizer.sanitize(untrustedHTML);

// Validate URLs
const validator = new URLValidator();
const result = validator.validate(userUrl, { allowedProtocols: ['https:'] });
Trusted Types must be installed before any DOM manipulation. Call installTrustedTypes() at the top of your application entry point.

vril/security/crypto/vault

The ΩVault provides zero-knowledge client-side encryption using AES-256-GCM with PBKDF2-SHA-512 key derivation at 600,000 iterations. It supports text and binary encryption, key wrapping, passphrase rotation, and secure memory operations.

ExportTypeDescription
VrilVaultclassAES-256-GCM vault with PBKDF2-SHA-512 (600K iterations)
encrypt()methodEncrypt text with passphrase, returns versioned bundle
decrypt()methodDecrypt bundle with passphrase, verifies integrity
encryptBlob()methodEncrypt binary data (ArrayBuffer)
wrapKey()methodAES-KW key wrapping for secure key storage
rotatePassphrase()methodRe-encrypt bundle with new passphrase
assessStrength()methodPassword strength scoring (0-6 scale)
SecureMemoryclassBest-effort zeroization of sensitive data in memory
ts
import { VrilVault } from '@/lib/vril/security/crypto/vault';

const vault = new VrilVault(600000);

// Encrypt sensitive data
const encrypted = await vault.encrypt('my-passphrase', 'sensitive data');
// encrypted = { v: 2, salt, iv, ciphertext, algorithm: 'AES-256-GCM', kdf: 'PBKDF2-SHA-512', kdfIterations: 600000 }

// Decrypt
const decrypted = await vault.decrypt('my-passphrase', encrypted);
// decrypted = { plaintext: 'sensitive data', algorithm: 'AES-256-GCM', verified: true }

// Check passphrase strength
const strength = vault.assessStrength('my-passphrase');
// strength = { score: 4, max: 6, label: 'moderate' }
Never store passphrases in localStorage or cookies. Use the SecureMemory class to zero out passphrase variables after use. KDF iterations below 600,000 do not meet OWASP 2023 recommendations.

vril/security/crypto/pqc

Post-quantum cryptography handler supporting ML-KEM-768, ML-KEM-1024, ML-DSA-65, ML-DSA-87, SLH-DSA-SHA2-128s, and SLH-DSA-SHA2-256f. All algorithms follow FIPS 203/204 standards. Where browser support is not yet available, the module simulates PQC operations with real classical fallbacks (ECDH-P256, ECDSA-P256).

ExportTypeDescription
PQCHandlerclassPost-quantum key encapsulation and digital signatures
generateKeyPair()methodGenerate PQC key pairs for KEM or signatures
encapsulate()methodKEM encapsulation (generate shared secret + ciphertext)
decapsulate()methodKEM decapsulation (recover shared secret)
sign()methodCreate digital signature (ECDSA-P256 real, ML-DSA simulated)
verify()methodVerify digital signature
benchmark()methodPerformance benchmark for key gen/encap/decap cycles
isSupported()methodCheck if a PQC algorithm is available
ts
import { PQCHandler } from '@/lib/vril/security/crypto/pqc';

const pqc = new PQCHandler();

// Check algorithm support
pqc.isSupported('ML-KEM-768'); // true
pqc.isSupported('ML-DSA-65');  // true

// Generate hybrid key pair
const keyPair = await pqc.generateKeyPair('X25519-ML-KEM-768');

// Key encapsulation
const result = await pqc.hybridKeyExchange(peerPublicKey);

// Get algorithm info
const info = pqc.getAlgorithmInfo('ML-KEM-768');
// info = { name: 'ML-KEM-768', standard: 'FIPS 203', securityLevel: 3, ... }
PQC algorithms not yet natively supported in browsers are simulated. The hybrid approach (X25519+ML-KEM-768) ensures classical security is always maintained. When browsers add native PQC support, Vril.js will automatically use the real implementations.

vril/security/crypto/hybrid

Hybrid cryptography combines classical algorithms with post-quantum algorithms, providing defense in depth. The shared secret is derived by combining both classical and PQC components through a SHA-256 KDF combiner: combined = SHA-256(classicalSecret || pqcSecret || contextInfo).

ExportTypeDescription
HybridKEMclassHybrid key encapsulation (X25519+ML-KEM-768)
HybridSignerclassHybrid digital signatures (ECDSA-P256+ML-DSA-65)
HybridKeyRotationclassKey rotation with overlap periods for zero-downtime migration
encapsulate()methodPerform both classical and PQC KEM, combine secrets
verify()methodVerify both signatures (AND logic — both must pass)
ts
import { HybridKEM, HybridSigner } from '@/lib/vril/security/crypto/hybrid';

// Hybrid key exchange
const kem = new HybridKEM();
const result = await kem.encapsulate();
// result.classicalAlgorithm = 'X25519'
// result.pqcAlgorithm = 'ML-KEM-768'
// result.combinedSecret = SHA-256(X25519_secret || ML-KEM_secret || ctx)

// Hybrid signing
const signer = new HybridSigner();
const signature = await signer.sign(message, keyPair);
const valid = await signer.verify(message, signature, publicKey);
// Both ECDSA-P256 AND ML-DSA-65 must verify

vril/security/crypto/agility

Crypto agility framework with a 12+ algorithm registry, migration executor, health monitoring, organizational crypto policies, and audit logging. Includes NIST 2035 quantum timeline milestones for proactive algorithm migration planning.

ExportTypeDescription
AlgorithmRegistryclassVersioned registry of 12+ algorithms with status tracking
MigrationExecutorclassExecute algorithm migrations with re-encryption/re-signing
AlgorithmHealthMonitorclassTrack NIST announcements and vulnerability reports
CryptoPolicyclassDefine org-wide policies: min key sizes, required/forbidden algos
AuditLoggerclassLog all crypto operations for compliance (SOC 2, FIPS)
CryptoAgilityclassHigh-level API combining registry, policy, and health
ts
import { CryptoAgility } from '@/lib/vril/security/crypto/agility';

const agility = new CryptoAgility();

// Check system status
const status = agility.getStatus();
// { totalAlgorithms: 12, activeAlgorithms: 8, migrationsPending: 2 }

// Select best algorithm by type
const bestKEM = agility.selectAlgorithm('kem'); // X25519+ML-KEM-768

// Plan migration
const registry = agility.getRegistry();
const plan = registry.migrate('x25519', 'ml-kem-768');
// plan = { success: true, message: 'Migrated from X25519 to ML-KEM-768' }

vril/security/hardening

Browser hardening module with cross-origin isolation, fingerprint resistance, timing attack mitigation, clickjacking protection, XSS shielding, and secure cookie management.

ExportTypeDescription
CrossOriginIsolationclassEnable COOP+COEP+CORP for SharedArrayBuffer access
FingerprintResistanceclassAnti-fingerprinting: canvas, WebGL, audio noise
TimingAttackMitigationclassConstant-time comparisons, request timing normalization
ClickjackingProtectionclassX-Frame-Options, CSP frame-ancestors, framing policies
XSSShieldclassDOM-based XSS prevention, innerHTML sanitization
CookieFortressclassSecure cookies: __Host- prefix, SameSite, Secure, HttpOnly
SecurityHeadersBuilderclassFluent API for building comprehensive security headers
ts
import { XSSShield, CookieFortress, CrossOriginIsolation } from '@/lib/vril/security/hardening';

// XSS protection
const shield = new XSSShield();
const safe = shield.sanitize(untrustedHTML);

// Secure cookies
const cookies = new CookieFortress();
cookies.set('session', token, { sameSite: 'Strict', httpOnly: true, secure: true });

// Cross-origin isolation for SharedArrayBuffer
const isolation = new CrossOriginIsolation();
isolation.enable();

vril/security/audit

Runtime security auditing with comprehensive scanners, CSP violation reporting, security scoring, vulnerability databases, and compliance checking against OWASP, NIST, and PCI-DSS.

ExportTypeDescription
SecurityAuditorclassComprehensive runtime security scanner (headers, DOM, crypto, permissions)
CSPViolationReporterclassCollect and report Content Security Policy violations
SecurityScoreCalculatorclassCalculate security score (0-100) based on multiple factors
VulnerabilityDatabaseclassCheck against known vulnerability patterns
ComplianceCheckerclassCheck compliance with OWASP/NIST/PCI-DSS requirements
generateSecurityReport()functionGenerate full security audit report with recommendations
ts
import { SecurityAuditor, generateSecurityReport } from '@/lib/vril/security/audit';

const auditor = new SecurityAuditor();
const headerResults = auditor.scanHeaders();
const domResults = auditor.scanDOM();
const cryptoResults = auditor.scanCrypto();

// Full audit report
const report = await generateSecurityReport();
console.log(report.score); // 0-100
console.log(report.findings); // VulnerabilityFinding[]
console.log(report.compliance); // ComplianceStatus

vril/signals

ΩSignal provides fine-grained reactive primitives: signal, computed, effect, batch, untrack, and store. Enhanced with lazy, async, resource, debounced, throttled, persisted, and encrypted signal variants. Includes devtools hooks and dependency graph tracking for debugging.

ExportTypeDescription
signal()functionCreate a reactive signal with get/set/peek
computed()functionCreate a derived signal that auto-updates
effect()functionRun side effects when dependencies change
batch()functionBatch multiple updates into one notification
store()functionCreate a proxy-based reactive object store
encryptedSignal()functionSignal that encrypts values in memory with AES-256-GCM
resourceSignal()functionFetch-like signal with SWR pattern
createSignalGraph()functionTrack signal dependencies for debugging
ts
import { signal, computed, effect, batch, encryptedSignal } from '@/lib/vril/signals';

const name = signal('World');
const greeting = computed(() => `Hello, ${name()}!`);

effect(() => console.log(greeting())); // "Hello, World!"
name.set('Vril');                      // "Hello, Vril!"

// Batch updates
batch(() => {
  name.set('Alice');
  // ... other updates
  // Only one notification after batch completes
});

// Encrypted signal (AES-256-GCM in memory)
const secret = encryptedSignal('sensitive-value', 'encryption-key');

vril/state

VrilStore provides full state management built on signals, with middleware pipeline, memoized selectors, time-travel debugging, field-level encryption, and persistence.

ExportTypeDescription
createStore()functionCreate a store with initial state and middleware
VrilStoreclassFull state management: get/set/select/dispatch/subscribe
StateEncryptionclassField-level AES-256-GCM encryption for sensitive state
StatePersistenceclassPersist state to storage with optional encryption
loggerMiddlewareconstLog all state transitions for debugging
encryptionMiddlewareconstAuto-encrypt sensitive fields on state change
ts
import { createStore, loggerMiddleware, encryptionMiddleware } from '@/lib/vril/state';

const store = createStore(
  { count: 0, user: null },
  { middleware: [loggerMiddleware, encryptionMiddleware(['user'])] }
);

store.setState({ count: 1 });
const count = store.select((s) => s.count);

// Subscribe to changes
store.subscribe((state, prev) => {
  console.log('State changed:', state);
});

vril/hooks

React hooks that integrate Vril.js framework features into components. Includes signal subscriptions, encrypted state, secure storage, CSRF tokens, and permission checks.

ExportTypeDescription
useSignal()hookSubscribe to a signal in a React component
useComputed()hookComputed value that auto-updates in React
useEncryptedState()hookReact state that encrypts values with AES-256-GCM
useSecureStorage()hooklocalStorage with encryption and serialization
useCSRFToken()hookGet and manage CSRF tokens for server actions
useRateLimiter()hookClient-side rate limiting for API calls
usePermission()hookCheck browser Permissions Policy for features
ts
import { useSignal, useEncryptedState, useCSRFToken } from '@/lib/vril/hooks';

function SecureForm() {
  const count = useSignal(signal(0));
  const [secret, setSecret] = useEncryptedState('field-key', 'initial');
  const csrfToken = useCSRFToken();

  return (
    <form>
      <input type="hidden" name="csrf" value={csrfToken} />
      <input value={secret} onChange={(e) => setSecret(e.target.value)} />
      <button type="button" onClick={() => count.set(c => c + 1)}>{count}</button>
    </form>
  );
}

vril/cache

Multi-tier intelligent caching with LRU memory cache, stale-while-revalidate, AES-256-GCM encrypted cache layer, cache registry, and tag-based invalidation.

ExportTypeDescription
MemoryCacheclassLRU cache with TTL, max entries, and memory pressure
StaleWhileRevalidateclassSWR pattern with background refresh
EncryptedCacheclassAES-256-GCM encrypted cache for sensitive data
CacheRegistryclassManage multiple named caches with different policies
CacheInvalidatorclassTag-based and pattern-based cache invalidation
distributedCacheKey()functionCollision-free cache keys with namespace isolation
ts
import { MemoryCache, EncryptedCache } from '@/lib/vril/cache';

const cache = new MemoryCache<string>({ maxSize: 1000, ttl: 60000 });
await cache.set('user:1', JSON.stringify(user));
const user = await cache.get('user:1');

// Encrypted cache for sensitive data
const encCache = new EncryptedCache({ passphrase: 'vault-key' });
await encCache.set('api-key', 'sk_live_abc123');
const key = await encCache.get('api-key');

vril/server

Server security utilities including RSC deserialization hardening (CVE-2025-55182 prevention), CSRF guard with double-submit pattern, edge request signing with HMAC-SHA256, encrypted environment variables, and supply chain integrity verification.

ExportTypeDescription
validateDeserializedPayload()functionValidate RSC payloads: depth, keys, prototype pollution
CSRFGuardclassGenerate/validate CSRF tokens with constant-time comparison
RequestSignerclassHMAC-SHA256 request signing with replay prevention
EnvEncryptionclassEncrypt environment variables for edge runtime
SupplyChainIntegrityclassSBOM v2.3 integrity verification
RSCSecurityBoundaryclassRSC flight data validation, action signing, rate limiting
SecurityMiddlewareChainclassComposable security checks with audit logging
ts
import { CSRFGuard, RequestSigner, validateDeserializedPayload } from '@/lib/vril/server';

// CSRF protection
const token = CSRFGuard.generateToken();
const isValid = CSRFGuard.validateToken(request, expectedToken);

// Request signing (edge → origin)
const signer = new RequestSigner(process.env.SIGNING_SECRET);
const signature = await signer.sign(payload, Date.now());

// Validate deserialized RSC data
const result = validateDeserializedPayload(data, { maxDepth: 16 });
if (!result.valid) throw new Error(result.reason);

vril/build

Build-time security with 20-point security audit, CSP nonce generation, multi-algorithm SRI, SBOM generation in CycloneDX format, build integrity verification, and platform-specific security headers output.

ExportTypeDescription
CSPNonceGeneratorclassPer-request CSP nonces with strict-dynamic support
SRIHasherclassMulti-algorithm SRI (sha256+sha384+sha512)
BuildSecurityCheckerclass20-point build security audit
BuildPluginclassBuild plugin for CSP manifest, SRI injection, security transforms
SBOMGeneratorclassCycloneDX SBOM with vulnerability matching
SecurityHeadersPluginclassAuto-generate headers for Vercel/Netlify/Cloudflare/Nginx
ts
import { BuildSecurityChecker, SRIHasher } from '@/lib/vril/build';

// Run 20-point security audit
const checker = new BuildSecurityChecker();
checker.pass('csp-nonce');
checker.pass('sri-hashes');
checker.pass('hsts-preload');
const status = checker.getStatus();
// { total: 20, passed: 3, failed: [...17 items] }

// Generate SRI attribute
const sri = await SRIHasher.compute(scriptContent, 'sha384');
// "sha384-..."

vril/router

Secure router with per-route CSRF, rate limits, method restrictions, CORS handling, and composable middleware. Includes route groups, security scanning, and client-side navigation guards to prevent tab-nabbing and URL injection.

ExportTypeDescription
RouteSecurityRegistryclassMap route patterns to security policies
createSecureHandler()functionCreate API route handler with built-in security
RouteMiddlewareclassComposable: withAuth, withCSRF, withRateLimit, withCORS
RouteGroupclassGroup routes with shared security: api(), public(), admin()
NavigationGuardclassClient-side URL validation, tab-nabbing prevention
RouteScannerclassScan route definitions for security issues
ts
import { RouteSecurityRegistry, createSecureHandler, RouteMiddleware } from '@/lib/vril/router';

const registry = new RouteSecurityRegistry();
registry.register({ path: '/api/*', security: { csrf: true, rateLimit: 60 } });

// Composable middleware
const handler = RouteMiddleware.compose(
  RouteMiddleware.withAuth,
  RouteMiddleware.withCSRF,
  RouteMiddleware.withRateLimit({ max: 100 }),
)(async (req) => Response.json({ ok: true }));

vril/auth

Authentication building blocks: session management with HMAC-SHA256 tokens, JWT-like token handling using Web Crypto, PBKDF2-SHA-512 password hashing, and hierarchical RBAC with role inheritance.

ExportTypeDescription
SessionManagerclassCreate/validate/rotate/destroy sessions with HMAC tokens
TokenHandlerclassJWT-like tokens: create, verify, refresh (Web Crypto)
PasswordHandlerclassPBKDF2-SHA-512 (600K iter) with constant-time verify
RBACclassHierarchical role-based access control with permission guards
LoginAttemptTrackerclassFailed login tracking with progressive lockout
ts
import { SessionManager, RBAC, PasswordHandler } from '@/lib/vril/auth';

// Sessions
const sessions = new SessionManager({ ttl: 86400000 });
const session = sessions.create({ userId: '123' });

// RBAC
const rbac = new RBAC();
rbac.defineRole('admin', ['read', 'write', 'delete']);
rbac.defineRole('user', ['read']);
const canDelete = rbac.checkPermission('admin', 'delete'); // true

// Passwords
const passwords = new PasswordHandler();
const hash = await passwords.hash('user-password');
const valid = await passwords.verify('user-password', hash);

vril/api

Type-safe API route builder with zero-dependency schema validation (no Zod needed), structured error handling, token-bucket rate limiting, and route versioning with deprecation warnings.

ExportTypeDescription
createAPIRoute()functionBuilder for API routes with validation, CSRF, rate limiting
APISchemaclassZero-dep schema builder: string, number, object, array, enum
APIErrorHandlerclassStructured error responses (safe in prod, verbose in dev)
APIRateLimiterclassToken bucket rate limiting per IP/route
APIVersioningclassRoute versioning with deprecation warnings
ts
import { createAPIRoute, APISchema } from '@/lib/vril/api';

const schema = APISchema.object({
  name: APISchema.string().min(1).max(100),
  email: APISchema.string().pattern(/^[^@]+@[^@]+$/),
});

const handler = createAPIRoute({
  validate: schema,
  rateLimit: { max: 100, window: 60000 },
  csrf: true,
}, async (req) => {
  return Response.json({ user: req.body });
});

vril/ssr

Server-side rendering with streaming support, security guard that validates SSR output for XSS and injection attacks before sending, and selective hydration with three strategies: immediate, visible, and idle.

ts
import { createSSRStream, SSRSecurityGuard, SelectiveHydration } from '@/lib/vril/ssr';

const guard = new SSRSecurityGuard();
const clean = guard.sanitize(ssrOutput);

const hydration = new SelectiveHydration();
hydration.mark('hero', 'immediate');
hydration.mark('comments', 'visible');
hydration.mark('analytics', 'idle');

vril/streaming

Streaming utilities for React Server Components with HMAC integrity validation, rate-limited streams to prevent DoS, secure content transformers, and streaming cache with stale-while-revalidate.

ts
import { StreamIntegrityValidator, RateLimitedStream } from '@/lib/vril/streaming';

const validator = new StreamIntegrityValidator('hmac-secret');
validator.addChunk(chunk);
const isValid = validator.verify(finalChunk, expectedHash);

const limited = new RateLimitedStream({ bytesPerSecond: 1024 * 1024 });

vril/edge

Edge runtime detection, key-value storage, geolocation with privacy controls, and edge-specific security including bot detection and IP allowlisting.

ts
import { EdgeRuntime, EdgeKV, EdgeSecurity } from '@/lib/vril/edge';

const runtime = new EdgeRuntime();
if (runtime.isEdge()) { /* edge-specific code */ }

const kv = new EdgeKV<string>({ namespace: 'sessions', ttl: 3600 });
await kv.set('user:1', JSON.stringify(session));

const edgeSec = new EdgeSecurity({ preset: 'strict' });
const isBot = edgeSec.detectBot(userAgent);

vril/diagnostics

Runtime diagnostics and monitoring: performance profiling with high-resolution timing, security health monitoring, crypto operation profiling, network request tracking, and memory leak detection.

ts
import { PerformanceMonitor, SecurityDiagnostics } from '@/lib/vril/diagnostics';

const perf = new PerformanceMonitor();
perf.start('encryption');
await vault.encrypt(key, data);
perf.end('encryption');
// encryption: 42ms

const diag = new SecurityDiagnostics();
const health = diag.checkAll();

vril/utils

Zero-dependency utility functions for security operations: constant-time comparison, secure random generation, SHA hashing, Base64 encoding, HTML sanitization, URL validation, deep clone/freeze/merge, debounce/throttle, and exponential backoff retry.

ExportTypeDescription
constantTimeEqual()functionConstant-time string/buffer comparison (prevents timing attacks)
secureRandom()functionCryptographically secure random bytes
secureRandomString()functionSecure random string (configurable charset)
hashData()functionSHA-256/384/512 hashing via Web Crypto
sanitizeHTML()functionBasic HTML sanitizer (strips scripts, event handlers)
validateURL()functionURL validation with protocol allowlisting
ts
import { constantTimeEqual, secureRandomString, hashData } from '@/lib/vril/utils';

// Constant-time comparison (prevents timing attacks)
const match = constantTimeEqual(userToken, expectedToken);

// Secure random string
const apiKey = secureRandomString(32, 'alphanumeric');

// SHA-256 hashing
const hash = await hashData('input-data', 'SHA-256');