๐Ÿ“ JavaScript Code Examples

๐Ÿ”’ PII Detection with Presidio

const { PresidioAnalyzer, PresidioAnonymizer } = require('@microsoft/presidio');

const analyzer = new PresidioAnalyzer();
const anonymizer = new PresidioAnonymizer();

// Analyze text for PII
const results = await analyzer.analyze({
  text: "John Doe's SSN is 123-45-6789",
  language: "en"
});

// Anonymize detected PII
const anonymized = await anonymizer.anonymize({
  text: "John Doe's SSN is 123-45-6789",
  analyzerResults: results
});

console.log('Anonymized text:', anonymized.text);

๐Ÿ” JWT Token Validation

const jwt = require('jsonwebtoken');

// Create JWT token
const payload = {
  user_id: 123,
  exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour
};
const token = jwt.sign(payload, 'secret_key', { algorithm: 'HS256' });

// Verify JWT token
try {
  const decoded = jwt.verify(token, 'secret_key', { algorithms: ['HS256'] });
  console.log(`Valid token for user: ${decoded.user_id}`);
} catch (error) {
  if (error.name === 'TokenExpiredError') {
    console.log('Token has expired');
  } else {
    console.log('Invalid token');
  }
}

๐Ÿ›ก๏ธ HIPAA Safe Harbor Implementation

function deidentifyPHI(text) {
  // Remove SSNs
  text = text.replace(/\d{3}-\d{2}-\d{4}/g, '[SSN]');
  
  // Remove dates (keep year only)
  text = text.replace(/\b\d{1,2}\/\d{1,2}\/\d{4}\b/g, 
    (match) => match.split('/')[2]);
  
  // Remove phone numbers
  text = text.replace(/\b\d{3}-\d{3}-\d{4}\b/g, '[PHONE]');
  
  // Remove email addresses
  text = text.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, 
    '[EMAIL]');
  
  return text;
}

// Usage
const phiText = "Patient John Doe (SSN: 123-45-6789) was seen on 12/15/2023";
const deidentified = deidentifyPHI(phiText);
console.log(deidentified);

๐Ÿงช ML Model Testing

const { DataValidation } = require('data-validation-js');

// Test model input validation
function testModelInputValidation(testData) {
  const validator = new DataValidation();
  
  // Define expectations
  validator.expectColumnToExist('user_id');
  validator.expectColumnValuesToBeBetween('age', 0, 120);
  validator.expectColumnValuesToNotBeNull('email');
  
  // Validate dataset
  const results = validator.validate(testData);
  
  if (!results.success) {
    throw new Error('Data validation failed: ' + results.errors);
  }
  
  return results;
}

// Test model output validation
function testModelOutputValidation(predictions, actuals) {
  // Validate prediction format
  if (predictions.length !== actuals.length) {
    throw new Error('Prediction count mismatch');
  }
  
  // Check prediction range
  const validPredictions = predictions.every(p => p >= 0 && p <= 1);
  if (!validPredictions) {
    throw new Error('Invalid prediction values');
  }
  
  // Calculate bias score
  const biasScore = calculateBiasScore(predictions, actuals);
  if (biasScore > 0.1) {
    throw new Error('Model shows significant bias');
  }
}

๐Ÿ“Š Monitoring Setup

const prometheus = require('prom-client');

// Define metrics
const REQUEST_COUNT = new prometheus.Counter({
  name: 'ai_requests_total',
  help: 'Total AI requests'
});

const REQUEST_LATENCY = new prometheus.Histogram({
  name: 'ai_request_duration_seconds',
  help: 'AI request latency',
  labelNames: ['model_name']
});

// Middleware to monitor AI requests
function monitorAIRequest(modelName) {
  return (req, res, next) => {
    const start = Date.now();
    
    res.on('finish', () => {
      const duration = (Date.now() - start) / 1000;
      REQUEST_COUNT.inc();
      REQUEST_LATENCY.labels(modelName).observe(duration);
    });
    
    next();
  };
}

// Usage in Express app
app.use('/api/ai', monitorAIRequest('gpt-4'));
app.get('/metrics', async (req, res) => {
  res.set('Content-Type', prometheus.register.contentType);
  res.end(await prometheus.register.metrics());
});

Secure AI Development Guide

Prepared by: Neeta Timsina

Part of: Knowledge Sharing Session

Platform: CareBoarding Technology Platform

Essential Security Practices for AI Development Teams

1 / 23
Loading...
Loading content...
Loading answer...
Click the card to validate your guess

๐Ÿ“š Appendix

๐Ÿ”ค Abbreviations & Definitions

PHI - Protected Health Information Personal health data protected under HIPAA regulations
PII - Personally Identifiable Information Data that can identify an individual
ePHI - Electronic Protected Health Information PHI stored or transmitted electronically
HIPAA - Health Insurance Portability and Accountability Act Federal law protecting patient health information
NIST - National Institute of Standards and Technology Federal agency providing cybersecurity frameworks
RBAC - Role-Based Access Control Access control based on user roles and permissions
IAM - Identity and Access Management Framework for managing user identities and permissions
OAuth2 - Open Authorization 2.0 Authorization protocol for secure API access
OIDC - OpenID Connect Identity layer built on top of OAuth 2.0
JWT - JSON Web Token Compact, URL-safe token for secure information exchange
API - Application Programming Interface Set of rules for software applications to communicate
CI/CD - Continuous Integration/Continuous Deployment Automated software delivery pipeline
GAN - Generative Adversarial Network AI model architecture with generator and discriminator
NER - Named Entity Recognition NLP technique to identify and classify named entities
SSN - Social Security Number Nine-digit identifier issued to US citizens
DLP - Data Loss Prevention Security technology to prevent data breaches
SBOM - Software Bill of Materials Inventory of software components and dependencies
ONNX - Open Neural Network Exchange Open format for machine learning models
VPC - Virtual Private Cloud Isolated cloud computing environment
WAF - Web Application Firewall Security system protecting web applications
SIEM - Security Information and Event Management Security system for threat detection and response
BAA - Business Associate Agreement HIPAA contract between covered entities and business associates
SLA - Service Level Agreement Contract defining service quality and performance metrics
SOC 2 - System and Organization Controls 2 Security compliance framework for service organizations
QPS - Queries Per Second Measure of system throughput and performance
SLI - Service Level Indicator Measurable characteristic of a service
SLO - Service Level Objective Target value for a service level indicator