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);
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');
}
}
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);
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');
}
}
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());
});
Prepared by: Neeta Timsina
Part of: Knowledge Sharing Session
Platform: CareBoarding Technology Platform
Essential Security Practices for AI Development Teams