TypeScript SDK

Installation

Install the Asguard TypeScript SDK via npm:

npm install @org-cyber/asguard

Requirements

  • Node.js: >= 14
  • Axios: >= 1.0
  • TypeScript: >= 4.0 (optional, for type checking)

Setup & Configuration

Configure API clients for both Fraud Detection and Face Verification services:

import {
  Configuration,
  FraudDetectionApi,
  FaceVerificationApi
} from "@org-cyber/asguard";

// Fraud Detection Client
const fraudConfig = new Configuration({
  basePath: "http://localhost:8081",
  baseOptions: {
    headers: { "X-API-Key": "your-api-key" }
  }
});
const fraudApi = new FraudDetectionApi(fraudConfig);

// Face Verification Client
const faceConfig = new Configuration({
  basePath: "http://localhost:8082",
  baseOptions: {
    headers: { Authorization: "Bearer your-token" }
  }
});
const faceApi = new FaceVerificationApi(faceConfig);
Replace base paths with your actual service endpoints. Note that Axios response data is in the .data attribute.

Fraud Detection API

Analyzing Transactions

Analyze transactions for fraud using async/await:

import { FraudCheckRequest } from "@org-cyber/asguard";

async function checkTransaction() {
  const payload: FraudCheckRequest = {
    user_id: "user_123",
    transaction_id: "txn_456",
    amount: 250000,
    currency: "USD",
    ip_address: "192.168.1.5",
    device_id: "device_789",
    location: "Lagos, Nigeria"
  };

  try {
    const response = await fraudApi.checkFraud(payload);
    const result = response.data;

    console.log(`Risk Score: ${result.risk_score}`);
    console.log(`Risk Level: ${result.risk_level}`);
    console.log(`AI Recommendation: ${result.ai_recommendation}`);
    console.log(`Reasons:`, result.reasons);

    return result;
  } catch (error: any) {
    console.error("Error:", error.response?.data || error.message);
    throw error;
  }
}

// Call the function
checkTransaction();

Request Fields

Field Type Required Description
user_id string Yes Unique user identifier
transaction_id string Yes Unique transaction identifier
amount number Yes Transaction amount
currency string Yes ISO 4217 currency code
ip_address string No Source IP address
device_id string No Device fingerprint
location string No Geographic location

Response Fields

Field Type Description
risk_score number Risk score 0-100
risk_level string LOW, MEDIUM, HIGH, CRITICAL
reasons string[] List of reasons
ai_triggered boolean Whether AI was triggered
ai_confidence number Confidence score 0-1
ai_recommendation string APPROVE, REVIEW, BLOCK, CHALLENGE
ai_fraud_probability number Fraud probability 0-1
ai_summary string AI analysis summary

Fraud Detection API Reference

POST /analyze

Analyze a transaction for fraudulent activity.

Example Request

POST http://localhost:8081/analyze
X-API-Key: your-api-key
Content-Type: application/json

{
  "user_id": "user_123",
  "transaction_id": "txn_456",
  "amount": 250000,
  "currency": "USD",
  "ip_address": "192.168.1.5",
  "device_id": "device_789",
  "location": "Lagos, Nigeria"
}

Example Response (200 OK)

{
  "transaction_id": "txn_456",
  "risk_score": 41,
  "risk_level": "MEDIUM",
  "reasons": [
    "High transaction amount (>100k)",
    "Foreign currency transaction (USD)"
  ],
  "ai_triggered": true,
  "ai_confidence": 0.85,
  "ai_recommendation": "REVIEW",
  "ai_fraud_probability": 0.45,
  "ai_summary": "Large USD transaction from Lagos warrants manual review",
  "message": "Transaction analyzed successfully"
}

GET /health

Check service health.

const health = await fraudApi.health();
// Returns: { status: "asguard health running" }

Face Verification API

Analyzing Faces

Extract facial embeddings and quality metrics:

import * as fs from "fs";
import { AnalyzeFaceRequest } from "@org-cyber/asguard";

async function analyzeFace() {
  // Load and encode image
  const imageBytes = fs.readFileSync("selfie.jpg");
  const base64Image = imageBytes.toString("base64");
  const dataURI = `data:image/jpeg;base64,${base64Image}`;

  const request: AnalyzeFaceRequest = {
    image: dataURI,
    quality_checks: true
  };

  try {
    const response = await faceApi.analyzeFace(request);
    const result = response.data;

    if (result.success) {
      console.log(`Embedding: ${result.embedding.length}D vector`);
      console.log(`Quality: ${result.quality_score}`);
      console.log(`Sharpness: ${result.sharpness}`);
      console.log(`Brightness: ${result.brightness}`);
      return result;
    }
  } catch (error: any) {
    console.error("Error:", error.response?.data || error.message);
  }
}

analyzeFace();

Request Fields

Field Type Required Description
image string Yes Base64-encoded image (data URI)
quality_checks boolean No Enable quality metrics

Response Fields

Field Type Description
success boolean Whether analysis succeeded
face_detected boolean Whether a face was detected
embedding number[] 128-dimensional embedding
quality_score number Overall quality (0-1)
sharpness number Image sharpness metric
brightness number Average brightness
face_size_ratio number Face to image size ratio
processing_time_ms number Processing time

Comparing Faces

Compare two faces for identity verification:

import * as fs from "fs";
import { CompareFacesRequest } from "@org-cyber/asguard";

async function compareFaces(
  probeImagePath: string,
  referenceEmbedding: number[]
) {
  // Load probe image
  const probeBytes = fs.readFileSync(probeImagePath);
  const probeBase64 = probeBytes.toString("base64");
  const probeURI = `data:image/jpeg;base64,${probeBase64}`;

  const request: CompareFacesRequest = {
    probe_image: probeURI,
    reference_embedding: referenceEmbedding,
    threshold: 0.6
  };

  try {
    const response = await faceApi.compareFaces(request);
    const result = response.data;

    if (result.success) {
      if (result.match) {
        console.log(`Match! Confidence: ${result.confidence}`);
      } else {
        console.log(`No match. Distance: ${result.distance}`);
      }
      return result;
    }
  } catch (error: any) {
    console.error("Error:", error.response?.data || error.message);
  }
}

// Usage (with embedding from analyze)
// compareFaces("verification.jpg", storedEmbedding);

Request Fields

Field Type Required Description
probe_image string Yes Base64-encoded image
reference_embedding number[] Yes 128D reference embedding
threshold number No Confidence threshold

Response Fields

Field Type Description
success boolean Whether comparison succeeded
match boolean Whether faces match
confidence number Confidence score (0-1)
distance number Euclidean distance
threshold_used number Applied threshold
probe_quality number Probe image quality
processing_time_ms number Processing time

Face Verification API Reference

POST /v1/analyze

Extract facial embeddings and quality metrics.

Example Request

POST http://localhost:8082/v1/analyze
Authorization: Bearer your-token
Content-Type: application/json

{
  "image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
  "quality_checks": true
}

Example Response (200 OK)

{
  "success": true,
  "face_detected": true,
  "embedding": [0.023, -0.14, 0.082, ...],
  "quality_score": 1.0,
  "sharpness": 0.82,
  "brightness": 142.5,
  "face_size_ratio": 0.34,
  "warnings": [],
  "processing_time_ms": 312
}

POST /v1/compare

Compare a probe image against a reference embedding.

Example Request

POST http://localhost:8082/v1/compare
Authorization: Bearer your-token
Content-Type: application/json

{
  "probe_image": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
  "reference_embedding": [0.023, -0.14, 0.082, ...],
  "threshold": 0.6
}

Example Response (200 OK)

{
  "success": true,
  "match": true,
  "confidence": 0.78,
  "distance": 0.131,
  "threshold_used": 0.6,
  "probe_quality": 1.0,
  "processing_time_ms": 287
}

GET /health

Check service health and version.

GET http://localhost:8082/health

Response: { "status": "healthy", "service": "asguard-face", "version": "1.0.0" }

Error Handling

Handle errors with try-catch and check status codes:

try {
  const response = await fraudApi.checkFraud(payload);
  const result = response.data;
  // Process result
} catch (error: any) {
  const status = error.response?.status;
  const data = error.response?.data;

  if (status === 400) {
    console.error("Bad request:", data);
  } else if (status === 401) {
    console.error("Unauthorized - check credentials");
  } else if (status === 429) {
    console.error("Rate limited");
  } else if (status === 500) {
    console.error("Server error - retry");
  } else {
    console.error("Unknown error:", error.message);
  }
}

HTTP Status Codes

Code Meaning Action
200 Success Process response normally
400 Bad Request Check input parameters
401 Unauthorized Verify credentials
429 Rate Limited Implement backoff
500 Server Error Retry with backoff

Best Practices

Image Encoding

Properly encode images as base64 data URIs:

import * as fs from "fs";

function encodeImage(filePath: string, mimeType: string): string {
  const data = fs.readFileSync(filePath);
  const base64 = data.toString("base64");
  return `data:${mimeType};base64,${base64}`;
}

// Usage
const jpegUri = encodeImage("photo.jpg", "image/jpeg");
const pngUri = encodeImage("photo.png", "image/png");

Async/Await Error Handling

Wrap operations in proper error handling:

async function processTransaction(fraudRequest: FraudCheckRequest) {
  try {
    const response = await fraudApi.checkFraud(fraudRequest);
    return response.data;
  } catch (error: any) {
    if (error.response?.status === 429) {
      // Handle rate limiting
      await new Promise(r => setTimeout(r, 1000));
      return processTransaction(fraudRequest);
    }
    throw error;
  }
}

Quality Checks

Always enable quality checks for face verification:

const request: AnalyzeFaceRequest = {
  image: dataURI,
  quality_checks: true
};

const response = await faceApi.analyzeFace(request);
const result = response.data;

if (result.quality_score < 0.7) {
  console.warn("Low image quality", {
    sharpness: result.sharpness,
    brightness: result.brightness,
    faceSize: result.face_size_ratio
  });
}

Threshold Configuration

Select appropriate thresholds for your use case:

// High security (KYC, access control)
const strictThreshold = 0.75;

// Standard verification (user login)
const standardThreshold = 0.65;

// Lenient (lower false negatives)
const lenientThreshold = 0.55;

const compareRequest: CompareFacesRequest = {
  probe_image: probeURI,
  reference_embedding: embedding,
  threshold: standardThreshold
};