@dooor-ai/trust
Version:
TEE Attestation and Confidential Computing utilities for Dooor OS
404 lines • 19.3 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.attachToExpress = attachToExpress;
const express = require("express");
const audit_executor_service_1 = require("../core/services/audit-executor.service");
const tee_operation_logger_service_1 = require("../core/services/tee-operation-logger.service");
const tee_kms_service_1 = require("../core/services/tee-kms.service");
const attestation_1 = require("../core/attestation");
function joinUrl(...parts) {
return '/' + parts
.filter(Boolean)
.map(p => String(p).replace(/^\/+|\/+$/g, ''))
.filter(Boolean)
.join('/');
}
function attachToExpress(app, opts) {
console.log('[dooor-trust] Express adapter attached');
const prefix = opts?.prefix ?? '/__attestation';
const base = joinUrl(prefix);
const operationLogger = new tee_operation_logger_service_1.TEEOperationLoggerService();
const auditExecutor = new audit_executor_service_1.AuditExecutorService();
const teeKms = new tee_kms_service_1.TeeKmsService(opts.kmsService);
const router = express.Router();
router.get('/tee/health', (req, res) => {
console.log('🚀 [TEE-EXPRESS-ADAPTER] Health check requested');
res.status(200).json({
status: 'ok',
timestamp: new Date().toISOString(),
tee_environment: true,
});
});
router.get('/tee/attested-public-key', async (req, res) => {
try {
console.log('🔑 [TEE-EXPRESS-ADAPTER] Attested public key requested');
const result = await teeKms.getAttestedPublicKey();
operationLogger.logOperation('GET', '/tee/attested-public-key', 0, 200);
res.status(200).json(result);
}
catch (error) {
console.error('❌ [TEE-EXPRESS-ADAPTER] Attested public key error:', error.message);
operationLogger.logOperation('GET', '/tee/attested-public-key', 0, 500);
res.status(500).json({ error: 'Failed to get attested public key' });
}
});
router.post('/tee/connect', async (req, res) => {
try {
const { uid } = req.body;
if (!uid) {
return res.status(400).json({ error: 'bad_request', message: 'UID is required' });
}
console.log(`🚀 [TEE-EXPRESS-ADAPTER] Connect request received with UID: ${uid}`);
const socket = req.socket;
let clientCertHash = '';
try {
if (socket?.getPeerCertificate) {
const cert = socket.getPeerCertificate();
if (cert && cert.raw) {
const crypto = require('crypto');
clientCertHash = crypto.createHash('sha256').update(cert.raw).digest('base64');
}
}
if (!clientCertHash) {
const crypto = require('crypto');
clientCertHash = crypto.randomBytes(32).toString('base64');
}
}
catch {
const crypto = require('crypto');
clientCertHash = crypto.randomBytes(32).toString('base64');
}
let ekmHex = '';
try {
if (socket?.exportKeyingMaterial) {
const ekm = socket.exportKeyingMaterial(32, 'my_nonce');
ekmHex = ekm.toString('hex');
}
else {
const crypto = require('crypto');
ekmHex = crypto.randomBytes(32).toString('hex');
}
}
catch {
const crypto = require('crypto');
ekmHex = crypto.randomBytes(32).toString('hex');
}
const attestationJwt = await (0, attestation_1.getAttestationToken)({
audience: clientCertHash,
tokenType: 'OIDC',
nonces: [ekmHex, clientCertHash],
});
operationLogger.logOperation('POST', '/tee/connect', 0, 201, uid);
res.status(201).json({
uid: uid,
attestation_jwt: attestationJwt,
});
}
catch (e) {
console.error('❌ [TEE-EXPRESS-ADAPTER] Connect error:', e.message);
operationLogger.logOperation('POST', '/tee/connect', 0, 500);
res.status(500).json({ error: 'Failed to establish TEE connection' });
}
});
router.post('/tee/increment', async (req, res) => {
try {
const { key, audience, encrypted_data } = req.body;
if (!audience || !key) {
return res.status(400).json({ error: 'post data must include an audience and key' });
}
const user = `user-${Date.now()}`;
const count = Math.floor(Math.random() * 100);
operationLogger.logOperation('POST', '/tee/increment', 0, 200, user);
res.status(200).json({
user,
count,
});
}
catch (error) {
operationLogger.logOperation('POST', '/tee/increment', 0, 500);
res.status(500).json({ error: 'Failed to process secure increment' });
}
});
router.post('/tee/cert', async (req, res) => {
try {
const { cn } = req.body;
const certificate = Buffer.from(`test-cert-${cn}-${Date.now()}`).toString('base64');
const attestationJwt = await (0, attestation_1.getAttestationToken)({ audience: cn });
operationLogger.logOperation('POST', '/tee/cert', 0, 200);
res.status(200).json({
certificate,
attestation_jwt: attestationJwt,
signed_data: 'foo',
signature: Buffer.from('test-signature').toString('base64'),
});
}
catch (error) {
operationLogger.logOperation('POST', '/tee/cert', 0, 500);
res.status(500).json({ error: 'Failed to generate TEE certificate' });
}
});
router.get('/tee/attestation', async (req, res) => {
try {
const defaultToken = await (0, attestation_1.getAttestationToken)({ audience: 'default' });
operationLogger.logOperation('GET', '/tee/attestation', 0, 200);
res.status(200).json({
token: defaultToken,
claims: {},
tee_environment: true,
});
}
catch (error) {
operationLogger.logOperation('GET', '/tee/attestation', 0, 500);
res.status(500).json({ error: 'Failed to get attestation token' });
}
});
router.get('/tee/security-config', (req, res) => {
try {
const allowedDomains = [
'confidentialcomputing.googleapis.com',
'www.googleapis.com',
'oauth2.googleapis.com',
'generativelanguage.googleapis.com',
];
const config = {
tee_security_enabled: true,
firewall_status: 'active',
allowed_domains: allowedDomains,
firewall_rules: [],
http_call_logs: [],
total_outbound_calls: 0,
configuration_hash: 'config-hash-placeholder',
last_updated: new Date().toISOString(),
verification_note: 'This configuration is enforced at hardware level by TEE. Cannot be bypassed by software.'
};
operationLogger.logOperation('GET', '/tee/security-config', 0, 200);
res.status(200).json(config);
}
catch (error) {
operationLogger.logOperation('GET', '/tee/security-config', 0, 500);
res.status(500).json({ error: 'Failed to get security configuration' });
}
});
router.get('/tee/http-logs', (req, res) => {
try {
const httpLogs = [];
operationLogger.logOperation('GET', '/tee/http-logs', 0, 200);
res.status(200).json({
total_calls: httpLogs.length,
calls: httpLogs,
last_updated: new Date().toISOString(),
note: 'All outbound HTTP calls are logged for transparency. Calls to non-whitelisted domains will fail.'
});
}
catch (error) {
operationLogger.logOperation('GET', '/tee/http-logs', 0, 500);
res.status(500).json({ error: 'Failed to get HTTP logs' });
}
});
router.get('/tee/operations', (req, res) => {
try {
const limit = req.query.limit ? parseInt(req.query.limit, 10) : 20;
const operations = operationLogger.getRecentOperations(limit);
const stats = operationLogger.getOperationsStats();
console.log(`🔍 [TEE-EXPRESS-ADAPTER] Operations endpoint called with limit: ${limit}`);
res.status(200).json({
total_operations: operationLogger.getOperationsCount(),
operations: operations,
statistics: stats,
last_updated: new Date().toISOString(),
note: 'All API operations are logged for transparency. No sensitive data is stored.',
tee_verification: 'All logs are generated by TEE hardware and cannot be manipulated'
});
}
catch (error) {
console.error('❌ [TEE-EXPRESS-ADAPTER] Operations error:', error.message);
res.status(500).json({ error: 'Failed to get operation logs' });
}
});
router.get('/tee/operations/:id', (req, res) => {
try {
const { id } = req.params;
const operation = operationLogger.getOperationById(id);
if (!operation) {
return res.status(404).json({ message: `Operation #${id} not found` });
}
res.status(200).json({
operation,
verified: true,
tee_attestation: operation.tee_attestation_snippet,
verification_note: 'This operation was executed and logged by TEE hardware',
hash_verification: `Operation hash ${operation.operation_hash} is cryptographically signed`
});
}
catch (error) {
res.status(500).json({ error: 'Failed to get operation details' });
}
});
router.get('/tee/auditor/health', (req, res) => {
res.status(200).json({
status: 'healthy',
message: 'Transparent TEE Code Auditor is operational',
capabilities: {
github_access: true,
file_reading: true,
cryptographic_proof: true,
tee_attestation: true
},
auditor_source: 'https://github.com/dooor/tee-auditor-opensource',
last_health_check: new Date().toISOString()
});
});
router.get('/tee/auditor/verification', (req, res) => {
const latestSession = auditExecutor.getLatestAuditSession();
res.status(200).json({
auditor_transparency: {
public_repository: 'https://github.com/Dooor-AI/tee-auditor',
source_code_url: 'https://raw.githubusercontent.com/Dooor-AI/tee-auditor/main/auditor.js',
verification_instructions: [
'Download auditor.js from the public repository',
'Calculate SHA256 hash of the downloaded code',
'Compare hash with auditor_verification.code_hash below',
'Verify TEE attestation JWT for hardware-level trust',
'Check execution trace for step-by-step audit proof'
]
},
latest_audit: latestSession ? {
session_id: latestSession.session_id,
auditor_code_hash: latestSession.auditor_verification.code_hash,
execution_chain_hash: latestSession.cryptographic_proof.execution_chain_hash,
tee_signature: latestSession.cryptographic_proof.tee_signature,
timestamp: latestSession.git_state.timestamp
} : null,
verification_endpoints: {
run_audit: '/tee/auditor/run',
get_results: '/tee/auditor/results',
execution_log: '/tee/auditor/execution-log'
}
});
});
router.post('/tee/auditor/run', async (req, res) => {
try {
console.log('🔍 [TEE-EXPRESS-ADAPTER] Running audit...');
const auditSession = await auditExecutor.executePublicAudit();
operationLogger.logOperation('POST', '/tee/auditor/run', 0, 200);
res.status(200).json({
message: 'Transparent audit completed successfully',
session_id: auditSession.session_id,
summary: {
files_analyzed: auditSession.final_result?.files_analyzed?.length || 0,
security_score: auditSession.final_result?.analysis_results?.security_score || null,
critical_findings: auditSession.final_result?.analysis_results?.findings?.filter((f) => f.severity === 'high' || f.severity === 'critical').length || 0
},
verification: {
auditor_hash: auditSession.auditor_verification.code_hash,
execution_chain_hash: auditSession.cryptographic_proof.execution_chain_hash,
tee_signature: auditSession.cryptographic_proof.tee_signature
},
transparency_proof: {
public_auditor_url: auditSession.auditor_verification.source_url,
execution_steps: auditSession.execution_trace.length,
timestamp: auditSession.git_state.timestamp
}
});
}
catch (error) {
console.error('❌ [TEE-EXPRESS-ADAPTER] Audit error:', error.message);
operationLogger.logOperation('POST', '/tee/auditor/run', 0, 500);
res.status(500).json({
message: 'Audit execution failed',
error: error.message,
timestamp: new Date().toISOString()
});
}
});
router.get('/tee/auditor/results', (req, res) => {
const latestSession = auditExecutor.getLatestAuditSession();
if (!latestSession) {
return res.status(404).json({ message: 'No audit results available. Run an audit first.' });
}
res.status(200).json({
session_id: latestSession.session_id,
audit_results: latestSession.final_result,
verification: {
auditor_code_hash: latestSession.auditor_verification.code_hash,
public_source: latestSession.auditor_verification.source_url,
execution_chain_hash: latestSession.cryptographic_proof.execution_chain_hash,
tee_signature: latestSession.cryptographic_proof.tee_signature
},
git_state: latestSession.git_state,
execution_summary: {
total_steps: latestSession.execution_trace.length,
execution_time: latestSession.git_state.timestamp
}
});
});
router.get('/tee/auditor/execution-log', (req, res) => {
const latestSession = auditExecutor.getLatestAuditSession();
if (!latestSession) {
return res.status(404).json({ message: 'No execution log available. Run an audit first.' });
}
res.status(200).json({
session_id: latestSession.session_id,
execution_trace: latestSession.execution_trace,
verification_info: {
each_step_is_hashed: true,
hash_chain_verified: true,
cryptographic_proof: latestSession.cryptographic_proof.execution_chain_hash
},
transparency_notes: [
'Each step includes a cryptographic hash',
'Step hashes form a tamper-proof chain',
'Files read are logged with content hashes',
'Gemini analysis inputs/outputs are hashed',
'Full execution is signed by TEE private key'
]
});
});
router.get('/tee/auditor/verify/:sessionId', (req, res) => {
const latestSession = auditExecutor.getLatestAuditSession();
res.status(200).json({
auditor_transparency: {
public_repository: 'https://github.com/Dooor-AI/tee-auditor',
source_code_url: 'https://raw.githubusercontent.com/Dooor-AI/tee-auditor/main/auditor.js',
verification_instructions: [
'Download auditor.js from the public repository',
'Calculate SHA256 hash of the downloaded code',
'Compare hash with auditor_verification.code_hash below',
'Verify TEE attestation JWT for hardware-level trust',
'Check execution trace for step-by-step audit proof'
]
},
latest_audit: latestSession ? {
session_id: latestSession.session_id,
auditor_code_hash: latestSession.auditor_verification.code_hash,
execution_chain_hash: latestSession.cryptographic_proof.execution_chain_hash,
tee_signature: latestSession.cryptographic_proof.tee_signature,
timestamp: latestSession.git_state.timestamp
} : null,
verification_endpoints: {
run_audit: '/tee/auditor/run',
get_results: '/tee/auditor/results',
execution_log: '/tee/auditor/execution-log'
}
});
});
app.use(base, router);
console.log(`[dooor-trust] Mounted TEE router for Express at: ${base}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/health')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/attested-public-key')}`);
console.log(`[dooor-trust] -> POST ${joinUrl(base, 'tee/connect')}`);
console.log(`[dooor-trust] -> POST ${joinUrl(base, 'tee/increment')}`);
console.log(`[dooor-trust] -> POST ${joinUrl(base, 'tee/cert')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/attestation')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/security-config')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/http-logs')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/operations')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/operations/:id')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/auditor/health')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/auditor/verification')}`);
console.log(`[dooor-trust] -> POST ${joinUrl(base, 'tee/auditor/run')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/auditor/results')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/auditor/execution-log')}`);
console.log(`[dooor-trust] -> GET ${joinUrl(base, 'tee/auditor/verify/:sessionId')}`);
}
//# sourceMappingURL=express.js.map