v1.0.0
Stable

@glyphlock/sdk

The official Node.js SDK for GlyphLock. Steganographic security, covenant enforcement, and AI chain orchestration.

Installation

Install the GlyphLock SDK using npm, yarn, or pnpm:

npm install @glyphlock/sdk

Note: Always use environment variables for your API key. Never commit secrets to version control.

Quick Start

Initialize the GlyphLock client with your API key and start making requests:

lib/glyphlock.ts
import { GlyphLock } from "@glyphlock/sdk";

const gl = new GlyphLock({
  apiKey: process.env.GLYPHLOCK_API_KEY!,
  chainMode: "openai-first",     // Primary: OpenAI, Fallback: Claude/Gemini
  environment: "production",
  timeoutMs: 30000
});

// AI Chain Example
const result = await gl.chainRun({
  input: "Draft an ability card for Alfred, the Glyph Architect.",
  model: "openai:gpt-4.1",
  fallback: ["anthropic:opus-3.5", "gemini:pro"],
  temperature: 0.4
});

console.log(result.output);
console.log("Model used:", result.modelUsed);
console.log("Latency:", result.latencyMs, "ms");

AI Chain

Orchestrate across OpenAI, Anthropic, Gemini with automatic fallback

Stego QR

Generate and decode steganographic QR codes

Covenant

Verify access decisions with policy enforcement

AI Chain Orchestration

The chain module provides unified access to multiple AI providers with automatic fallback, health monitoring, and dynamic routing based on real-time performance metrics.

Chain Configuration with Health Monitoring
import { GlyphLock } from "@glyphlock/sdk";

const gl = new GlyphLock({
  apiKey: process.env.GLYPHLOCK_API_KEY!,
  chainMode: "gemini-first",        // Primary: Gemini (FREE), Fallback: OpenAI → Claude
  enableHealthRouting: true,        // Enable dynamic routing based on provider health
  maxRetries: 3,
  timeoutMs: 30000
});

// Run with health-aware fallback
const result = await gl.chainRun({
  input: "Analyze this smart contract for vulnerabilities...",
  persona: "SECURITY",              // Available: GENERAL, SECURITY, AUDIT, BLOCKCHAIN, DEBUGGER
  jsonMode: true,                   // Force JSON output (if provider supports it)
  temperature: 0.3,
  maxTokens: 2000,
  chainMode: "audit-optimized"      // Override chain mode for this call
});

// Response includes health metadata
console.log(result.output);
console.log("Provider:", result.provider);
console.log("Health Score:", result.meta.healthScore);
console.log("Latency:", result.latencyMs, "ms");
console.log("Attempts:", result.attemptCount);
Audit Mode with Structured Output
// Run security audit with structured JSON output
const audit = await gl.runAudit({
  target: "https://example.com/api/users",
  type: "api",
  context: {
    method: "POST",
    headers: { "Content-Type": "application/json" }
  }
});

// Audit returns structured data
console.log("Risk Score:", audit.audit.risk_score);       // 0-100
console.log("Severity:", audit.audit.severity);           // low/moderate/high/critical
console.log("Issues:", audit.audit.issues);               // Array of findings
console.log("Recommendations:", audit.audit.recommendations);
Provider Health Monitoring
// Get real-time health report
const health = gl.getHealthReport();

console.log("Providers:", health.providers);
// Each provider shows: successRate, avgLatencyMs, status, score

// Get recommended chain based on current health
const chain = gl.getRecommendedChain({
  requireJsonMode: true,   // Filter to JSON-capable providers
  requireAudit: true       // Filter to audit-capable providers
});

// Reset health metrics if needed
gl.resetHealth();

// Switch chain mode dynamically
gl.setChainMode("claude-first");

Chain Modes

  • gemini-first — Gemini (FREE) → OpenAI → Claude
  • openai-first — GPT-4o → Gemini → Claude
  • claude-first — Claude → OpenAI → Gemini
  • audit-optimized — OpenAI → Claude → Gemini
  • free-only — Gemini → OpenRouter only
  • balanced — Load-balanced by health

Available Personas

  • GENERAL — Default assistant mode
  • SECURITY — Threat & vulnerability focus
  • AUDIT — Structured security analysis
  • BLOCKCHAIN — Smart contracts & DeFi
  • DEBUGGER — Bug identification & fixes
  • ANALYTICS — Data pattern analysis

JSON Mode per Provider

JSON mode is automatically enabled based on provider capabilities:

  • • OpenAI — Full JSON schema support with strict mode
  • • Gemini — JSON object mode via responseMimeType
  • • Claude — JSON mode via system prompt
  • • OpenRouter — Depends on underlying model

Steganographic QR Codes

Generate and decode QR codes with hidden steganographic payloads. Perfect for secure access tokens, covenant bindings, and tamper-evident markers.

Encode & Decode
import { GlyphLock } from "@glyphlock/sdk";
import fs from "fs";

const gl = new GlyphLock({ apiKey: process.env.GLYPHLOCK_API_KEY! });

// Encode data into a steganographic QR code
const encoded = await gl.qrEncode({
  data: "GLYPHLOCK::ACCESS::ALFRED",
  mode: "stego",           // "stego" for hidden payload, "raw" for plain QR
  level: "high",           // Error correction: low/medium/high/ultra
  format: "png",           // Output format: png/svg
  metadata: {
    role: "architect",
    tier: "S",
    expires: "2025-12-31"
  }
});

// Save to file
fs.writeFileSync("alfred-qr.png", encoded.imageBuffer);
console.log("Checksum:", encoded.checksum);

// Decode a QR code
const imageBuffer = fs.readFileSync("alfred-qr.png");
const decoded = await gl.qrDecode(imageBuffer);

console.log("Data:", decoded.data);
console.log("Mode:", decoded.mode);
console.log("Metadata:", decoded.metadata);

Security Levels

  • low — 7% error correction, max data
  • medium — 15% error correction
  • high — 25% error correction
  • ultra — 30% + steganographic hardening

Use Cases

  • • Secure access tokens & passes
  • • Covenant binding proofs
  • • Tamper-evident product labels
  • • Hidden audit trails

Covenant Verification

Verify access decisions against your covenant policies. Returns allow/deny decisions with reasoning and policy traces.

Verify Access
import { GlyphLock } from "@glyphlock/sdk";

const gl = new GlyphLock({ apiKey: process.env.GLYPHLOCK_API_KEY! });

// Verify if an action is allowed
const decision = await gl.covenantVerify({
  token: "user-session-or-signed-jwt",
  action: "read",
  resource: "/dream-team/alfred",
  context: {
    ip: "192.168.1.1",
    userAgent: "Mozilla/5.0...",
    timestamp: Date.now()
  }
});

if (!decision.allowed) {
  console.error("Access denied:", decision.reason);
  console.log("Policy ID:", decision.policyId);
  throw new Error(`Forbidden: ${decision.reason}`);
}

console.log("Access granted, trace:", decision.traceId);

// Response structure
interface CovenantVerifyResult {
  allowed: boolean;         // Whether the action is permitted
  reason?: string;          // Human-readable reason if denied
  policyId?: string;        // Which policy matched
  traceId?: string;         // Unique trace for audit logging
}

Webhooks & Events

Receive real-time notifications when security events occur. Webhooks are signed with HMAC for verification.

Webhook Handler
// Express.js webhook handler
import { GlyphLock } from "@glyphlock/sdk";
import express from "express";

const app = express();
const gl = new GlyphLock({ apiKey: process.env.GLYPHLOCK_API_KEY! });

app.post("/webhooks/glyphlock", express.raw({ type: "application/json" }), (req, res) => {
  const signature = req.headers["x-glyphlock-signature"];
  const timestamp = req.headers["x-glyphlock-timestamp"];
  
  // Verify webhook signature
  const isValid = gl.webhooks.verify({
    payload: req.body,
    signature,
    timestamp,
    secret: process.env.WEBHOOK_SECRET!
  });

  if (!isValid) {
    return res.status(401).json({ error: "Invalid signature" });
  }

  const event = JSON.parse(req.body);
  
  switch (event.type) {
    // Chain Events
    case "chain.completed":
      console.log("Chain completed:", event.data.trace_id, "via", event.data.provider);
      break;
    case "chain.failed":
      console.log("Chain FAILED:", event.data.error_message);
      console.log("Providers attempted:", event.data.providers_attempted);
      break;
    
    // QR Events  
    case "qr.encoded":
      console.log("QR encoded:", event.data.code_id);
      console.log("Payload size:", event.data.payload_size_bytes, "bytes");
      break;
    case "qr.decoded":
      console.log("QR decoded:", event.data.code_id);
      console.log("Integrity verified:", event.data.integrity_verified);
      break;
    
    // Covenant Events
    case "covenant.verified":
      console.log("Covenant verified:", event.data.covenant_id);
      break;
    case "covenant.denied":
      console.log("Covenant DENIED:", event.data.denial_reason);
      console.log("Denial code:", event.data.denial_code);
      break;
  }

  res.json({ received: true });
});

Chain Events

chain.completed — AI chain finished successfully
chain.failed — All providers failed
chain.fallback — Fallback provider used
chain.provider_degraded — Provider health degraded

QR Code Events

qr.generated — QR code created
qr.encoded — Data encoded with steganography
qr.decoded — QR decoded and extracted
qr.scanned — QR code scanned by user
qr.threat_detected — Malicious content found
qr.tamper_detected — Integrity check failed

Covenant Events

covenant.verified — Verification passed
covenant.denied — Verification failed, access denied
covenant.expired — Covenant has expired
covenant.revoked — Covenant was revoked

Security Events

security.threat_blocked — Threat blocked
security.rate_limit — Rate limit exceeded
security.audit_completed — Audit finished
Event Payload Structure
// Example: chain.failed event payload
{
  "id": "evt_7a3f9c2e1b4d6a8f0e2c4b6d",
  "type": "chain.failed",
  "category": "chain",
  "severity": "error",
  "timestamp": "2025-01-15T14:30:00Z",
  "api_version": "2.0",
  "data": {
    "trace_id": "trace_abc123",
    "error_code": "CHAIN_EXHAUSTED",
    "error_message": "All providers failed after 3 attempts",
    "providers_attempted": ["GEMINI", "OPENAI", "CLAUDE"],
    "total_attempts": 3,
    "total_latency_ms": 45200,
    "last_provider": "CLAUDE",
    "last_error": "Rate limit exceeded",
    "fallback_exhausted": true
  },
  "metadata": {
    "user_id": "user_123",
    "request_id": "req_xyz789"
  }
}

// Example: covenant.denied event payload
{
  "id": "evt_8b4f0d3e2c5a7b9f",
  "type": "covenant.denied",
  "category": "covenant", 
  "severity": "error",
  "data": {
    "covenant_id": "cov_abc123",
    "asset_id": "asset_xyz",
    "asset_type": "ai_model",
    "denial_reason": "Signature mismatch detected",
    "denial_code": "SIG_MISMATCH",
    "signature_mismatch": true,
    "attempted_action": "model.inference",
    "requester_id": "unauthorized_client"
  }
}

Error Handling

All SDK methods throw GlyphLockError on failure. Catch and handle appropriately.

Error Handling
import { GlyphLock, GlyphLockError } from "@glyphlock/sdk";

const gl = new GlyphLock({ apiKey: process.env.GLYPHLOCK_API_KEY! });

try {
  const result = await gl.chainRun({
    input: "Generate security report...",
    model: "openai:gpt-4.1"
  });
  console.log(result.output);
} catch (error) {
  if (error instanceof GlyphLockError) {
    console.error("GlyphLock Error:", error.message);
    console.error("Code:", error.code);           // e.g. "RATE_LIMITED"
    console.error("Status:", error.status);       // e.g. 429
    console.error("Details:", error.details);     // Additional context
    
    // Handle specific errors
    if (error.code === "RATE_LIMITED") {
      // Implement backoff
    } else if (error.code === "INVALID_API_KEY") {
      // Check configuration
    }
  } else {
    throw error;
  }
}

// Common error codes
// INVALID_API_KEY    — API key missing or invalid
// RATE_LIMITED       — Too many requests
// QUOTA_EXCEEDED     — Monthly quota reached
// PROVIDER_ERROR     — Upstream AI provider failed
// INVALID_INPUT      — Request validation failed
// NETWORK_ERROR      — Connection failed

Ready to Build?

Get your API key from the GlyphLock Console and start integrating secure AI orchestration into your applications.