generalize presets into mosaic profiles with runtime overlays

This commit is contained in:
Jason Woltje
2026-02-17 11:46:12 -06:00
parent 4eac2c76e6
commit 33bbf60bad
15 changed files with 1868 additions and 0 deletions

View File

@@ -0,0 +1,181 @@
{
"name": "Cryptocurrency & Web3 Security",
"description": "Security patterns for blockchain, cryptocurrency, and Web3 applications",
"domainKeywords": ["crypto", "blockchain", "web3", "defi", "nft", "wallet", "smart contract", "ethereum"],
"compliance": {
"regulations": ["AML", "KYC", "FATF", "BSA", "Regional crypto regulations"],
"scope": "Applications handling cryptocurrencies and digital assets",
"requirements": [
"Secure private key management",
"Anti-money laundering (AML) compliance",
"Know Your Customer (KYC) verification",
"Transaction monitoring and reporting",
"Wallet security and multi-signature",
"Smart contract security audits"
]
},
"securityPatterns": {
"walletSecurity": {
"privateKeys": "Never store private keys in plaintext",
"keyDerivation": "Use BIP32/BIP44 for key derivation",
"storage": "Hardware Security Modules (HSMs) for production",
"backup": "Secure backup and recovery procedures",
"multiSig": "Multi-signature wallets for high-value transactions"
},
"smartContracts": {
"auditing": "Professional security audits required",
"testing": "Comprehensive test coverage including edge cases",
"upgradeability": "Consider proxy patterns for upgradeable contracts",
"accessControl": "Role-based access control in contracts",
"gasOptimization": "Optimize for gas efficiency and DoS protection"
},
"transactionSecurity": {
"validation": "Multi-layer transaction validation",
"monitoring": "Real-time transaction monitoring",
"limits": "Configurable transaction limits",
"timelock": "Time-delayed execution for large transactions",
"approval": "Multi-party approval workflows"
},
"apiSecurity": {
"authentication": "Strong API authentication (JWT + API keys)",
"rateLimit": "Aggressive rate limiting for trading APIs",
"signing": "Request signing for sensitive operations",
"websockets": "Secure WebSocket connections for real-time data"
}
},
"implementationPatterns": {
"backend": {
"walletIntegration": {
"abstraction": "Abstract wallet operations behind service layer",
"keyManagement": "Separate key management from application logic",
"transactions": "Queue and batch transactions for efficiency",
"monitoring": "Monitor blockchain for transaction confirmations"
},
"tradingEngine": {
"orderMatching": "Secure order matching algorithms",
"balanceTracking": "Accurate balance tracking with locks",
"riskManagement": "Position limits and risk controls",
"latency": "Low-latency execution for competitive trading"
},
"compliance": {
"kyc": "Identity verification workflows",
"aml": "Automated AML screening and monitoring",
"reporting": "Suspicious activity reporting (SAR)",
"sanctions": "OFAC and sanctions list screening"
}
},
"frontend": {
"walletConnection": {
"webWallets": "Support for MetaMask, WalletConnect, etc.",
"security": "Validate wallet signatures and addresses",
"persistence": "Secure session management",
"switching": "Handle network and account switching"
},
"trading": {
"realTime": "Real-time price and order book updates",
"charting": "Advanced charting capabilities",
"orderTypes": "Support for various order types",
"riskWarnings": "Clear risk disclosures and warnings"
}
}
},
"blockchainIntegration": {
"ethereum": {
"web3": "Use ethers.js or web3.js for blockchain interaction",
"infura": "Reliable node access via Infura/Alchemy",
"events": "Event listening and log parsing",
"gasManagement": "Dynamic gas price management"
},
"bitcoin": {
"addresses": "Support for multiple address types",
"utxo": "UTXO management and coin selection",
"fees": "Dynamic fee estimation",
"scripting": "Advanced scripting for complex transactions"
},
"multiChain": {
"abstraction": "Chain-agnostic service interfaces",
"bridging": "Cross-chain bridge integrations",
"networks": "Support for testnets and multiple networks",
"consensus": "Handle different consensus mechanisms"
}
},
"testingRequirements": {
"coverage": {
"minimum": "95% for financial logic modules",
"focus": "Security-critical components and edge cases"
},
"security": [
"Smart contract security audits",
"Penetration testing for web interfaces",
"Key management security testing",
"Transaction flow security validation",
"API security testing"
],
"blockchain": [
"Test on multiple networks (mainnet, testnet)",
"Handle network congestion scenarios",
"Test transaction failure and retry logic",
"Validate gas estimation accuracy",
"Test blockchain reorganization handling"
]
},
"context7Libraries": [
"ethers",
"web3",
"@metamask/providers",
"bitcoinjs-lib",
"@walletconnect/client",
"bip32",
"bip39"
],
"codeTemplates": {
"walletService": {
"description": "Secure wallet service interface",
"template": "@Injectable()\nexport class WalletService {\n async signTransaction(transaction: Transaction, keyId: string): Promise<string> {\n const privateKey = await this.keyManager.getKey(keyId);\n return this.signer.sign(transaction, privateKey);\n }\n\n async validateAddress(address: string, network: Network): Promise<boolean> {\n return this.validator.isValid(address, network);\n }\n}"
},
"transactionMonitor": {
"description": "Blockchain transaction monitoring",
"template": "this.web3.eth.subscribe('pendingTransactions', (txHash) => {\n this.web3.eth.getTransaction(txHash).then(tx => {\n if (this.isWatchedAddress(tx.to)) {\n this.processIncomingTransaction(tx);\n }\n });\n});"
},
"smartContractInteraction": {
"description": "Safe smart contract interaction",
"template": "const contract = new ethers.Contract(address, abi, signer);\nconst gasEstimate = await contract.estimateGas.transfer(to, amount);\nconst tx = await contract.transfer(to, amount, {\n gasLimit: gasEstimate.mul(110).div(100), // 10% buffer\n gasPrice: await this.getOptimalGasPrice()\n});"
}
},
"complianceChecklist": [
"Know Your Customer (KYC) procedures implemented",
"Anti-Money Laundering (AML) monitoring in place",
"Suspicious activity reporting (SAR) procedures",
"OFAC and sanctions screening implemented",
"Transaction monitoring and analysis tools",
"Customer due diligence (CDD) procedures",
"Enhanced due diligence (EDD) for high-risk customers",
"Record keeping and data retention policies",
"Compliance training for staff",
"Regular compliance audits and reviews"
],
"securityBestPractices": [
"Never store private keys in application code",
"Use hardware security modules (HSMs) for key storage",
"Implement multi-signature wallets for treasury management",
"Conduct regular security audits of smart contracts",
"Use time-locked transactions for large amounts",
"Implement comprehensive transaction monitoring",
"Use secure random number generation",
"Validate all blockchain data independently",
"Implement proper access controls and authentication",
"Maintain detailed audit logs of all operations"
],
"riskAssessment": [
"Private key compromise and theft",
"Smart contract vulnerabilities and exploits",
"Exchange hacks and loss of user funds",
"Regulatory compliance failures",
"Market manipulation and fraud",
"Technical failures and system outages",
"Insider threats and malicious employees",
"Third-party service provider risks",
"Quantum computing threats to cryptography",
"Cross-chain bridge vulnerabilities"
]
}

View File

@@ -0,0 +1,181 @@
{
"name": "Fintech Security Compliance",
"description": "PCI DSS and financial security requirements for fintech applications",
"domainKeywords": ["payment", "financial", "banking", "credit", "debit", "transaction", "pci", "fintech"],
"compliance": {
"regulations": ["PCI DSS", "PSD2", "SOX", "KYC", "AML"],
"scope": "Applications processing payment card data",
"requirements": [
"Secure cardholder data",
"Encrypt transmission of cardholder data",
"Protect stored cardholder data",
"Maintain vulnerability management program",
"Implement strong access control measures",
"Regularly monitor and test networks",
"Maintain information security policy"
]
},
"dataClassification": {
"pan": {
"definition": "Primary Account Number (Credit/Debit card number)",
"storage": "Never store full PAN unless absolutely necessary",
"masking": "Show only last 4 digits",
"encryption": "AES-256 if storage required",
"transmission": "Always encrypted with TLS 1.2+"
},
"sadData": {
"definition": "Sensitive Authentication Data",
"types": ["CVV2", "PIN", "Track data"],
"storage": "Never store SAD after authorization",
"handling": "Process but do not retain"
},
"cardholderData": {
"definition": "PAN + cardholder name, service code, expiration date",
"minimization": "Store only if business need exists",
"retention": "Purge when no longer needed",
"access": "Restrict access to authorized personnel only"
}
},
"securityPatterns": {
"encryption": {
"algorithm": "AES-256 for data at rest",
"keyManagement": "Hardware Security Modules (HSMs) preferred",
"transmission": "TLS 1.2+ for data in transit",
"tokenization": "Replace PAN with non-sensitive tokens"
},
"authentication": {
"mfa": "Multi-factor authentication mandatory",
"passwordPolicy": "Complex passwords, regular rotation",
"sessionManagement": "Secure session handling with timeout",
"biometric": "Support for biometric authentication"
},
"authorization": {
"rbac": "Role-based access control",
"segregationOfDuties": "Separate roles for sensitive operations",
"leastPrivilege": "Minimum necessary access principle",
"approval": "Multi-person approval for high-value transactions"
},
"fraudPrevention": {
"riskScoring": "Real-time transaction risk assessment",
"monitoring": "Anomaly detection and behavioral analytics",
"alerts": "Immediate alerts for suspicious activities",
"blocking": "Automatic blocking of fraudulent transactions"
}
},
"implementationPatterns": {
"backend": {
"paymentProcessing": {
"tokenization": "Use payment tokens instead of card data",
"validation": "Validate all payment inputs",
"logging": "Log transactions without sensitive data",
"encryption": "Encrypt cardholder data before storage"
},
"apiSecurity": {
"rateLimit": "Implement rate limiting",
"apiKeys": "Secure API key management",
"signing": "Request signing for sensitive operations",
"monitoring": "Monitor API usage patterns"
},
"database": {
"encryption": "Database-level encryption for sensitive fields",
"access": "Database access controls and monitoring",
"backup": "Encrypted backups with secure key management",
"masking": "Data masking for non-production environments"
}
},
"frontend": {
"paymentForms": {
"https": "Always use HTTPS for payment pages",
"validation": "Client-side validation with server confirmation",
"autocomplete": "Disable autocomplete for sensitive fields",
"iframes": "Use secure iframes for payment card input"
},
"dataHandling": {
"noStorage": "Never store payment data in browser",
"masking": "Mask card numbers in UI",
"timeout": "Session timeout for payment pages",
"clearData": "Clear payment data from memory after use"
}
}
},
"testingRequirements": {
"coverage": {
"minimum": "90% for payment processing modules",
"focus": "Security controls and fraud prevention"
},
"security": [
"Penetration testing quarterly",
"Vulnerability scanning monthly",
"Code review for all payment code",
"Test encryption implementation",
"Validate tokenization process"
],
"compliance": [
"PCI DSS compliance validation",
"Test access controls",
"Validate audit logging",
"Test incident response procedures",
"Verify data retention policies"
]
},
"context7Libraries": [
"stripe",
"bcrypt",
"jsonwebtoken",
"helmet",
"express-rate-limit",
"crypto"
],
"codeTemplates": {
"paymentEntity": {
"description": "Payment entity with tokenization",
"template": "@Entity()\nexport class Payment {\n @Tokenized()\n @Column()\n cardToken: string;\n\n @Column()\n lastFourDigits: string;\n\n @Encrypted()\n @Column()\n amount: number;\n}"
},
"transactionLog": {
"description": "Secure transaction logging",
"template": "await this.auditService.logTransaction({\n transactionId: transaction.id,\n userId: user.id,\n amount: transaction.amount,\n currency: transaction.currency,\n status: 'COMPLETED',\n riskScore: riskAssessment.score,\n timestamp: new Date()\n});"
},
"fraudCheck": {
"description": "Fraud prevention check",
"template": "const riskScore = await this.fraudService.assessRisk({\n userId: user.id,\n amount: transaction.amount,\n location: transaction.location,\n deviceFingerprint: request.deviceId\n});\n\nif (riskScore > FRAUD_THRESHOLD) {\n await this.alertService.triggerFraudAlert(transaction);\n}"
}
},
"complianceChecklist": [
"Cardholder data is encrypted at rest and in transit",
"Sensitive authentication data is not stored",
"Access to cardholder data is restricted and monitored",
"Strong cryptography and security protocols are used",
"Antivirus software is maintained",
"Secure systems and applications are developed",
"Access to data is restricted by business need-to-know",
"Unique IDs are assigned to each person with computer access",
"Physical access to cardholder data is restricted",
"All access to network resources is logged and monitored",
"Security systems and processes are regularly tested",
"Information security policy is maintained"
],
"riskAssessment": [
"Unauthorized access to payment data",
"Data breaches and card data theft",
"Fraud and unauthorized transactions",
"System vulnerabilities and exploits",
"Insider threats and malicious employees",
"Third-party payment processor risks",
"Network security vulnerabilities",
"Application security weaknesses",
"Physical security of payment systems",
"Business continuity and disaster recovery"
],
"regulatoryReporting": [
"PCI DSS compliance reports",
"Suspicious activity reports (SARs)",
"Currency transaction reports (CTRs)",
"Know Your Customer (KYC) documentation",
"Anti-Money Laundering (AML) compliance",
"Data breach notification requirements",
"Consumer privacy disclosures",
"Financial audit requirements",
"Incident response documentation",
"Third-party risk assessments"
]
}

View File

@@ -0,0 +1,189 @@
{
"name": "Healthcare HIPAA Compliance",
"description": "HIPAA compliance requirements for healthcare applications handling PHI",
"domainKeywords": ["health", "medical", "patient", "hipaa", "phi", "healthcare"],
"compliance": {
"regulation": "HIPAA (Health Insurance Portability and Accountability Act)",
"scope": "All applications handling Protected Health Information (PHI)",
"requirements": [
"Encrypt PHI at rest and in transit",
"Implement access controls for PHI",
"Audit all access to PHI",
"Ensure data integrity",
"Implement proper user authentication",
"Maintain data minimization practices"
]
},
"dataClassification": {
"phi": {
"definition": "Individually identifiable health information",
"examples": [
"Names, addresses, birth dates",
"Phone numbers, email addresses",
"Social Security numbers",
"Medical record numbers",
"Health plan beneficiary numbers",
"Account numbers",
"Certificate/license numbers",
"Vehicle identifiers and serial numbers",
"Device identifiers and serial numbers",
"Web Universal Resource Locators (URLs)",
"Internet Protocol (IP) address numbers",
"Biometric identifiers",
"Full face photographic images",
"Medical diagnoses and treatment information",
"Lab results and vital signs"
],
"encryption": "AES-256 encryption required",
"storage": "Must be encrypted at rest",
"transmission": "Must be encrypted in transit (TLS 1.2+)"
}
},
"securityPatterns": {
"encryption": {
"algorithm": "AES-256",
"keyManagement": "Use AWS KMS, Azure Key Vault, or similar",
"implementation": "Field-level encryption for PHI columns",
"example": "@Encrypted decorator for entity fields"
},
"authentication": {
"method": "Multi-factor authentication required",
"tokenType": "JWT with refresh tokens",
"sessionTimeout": "Maximum 15 minutes inactive timeout",
"passwordPolicy": "Minimum 8 characters, complexity requirements"
},
"authorization": {
"model": "Role-Based Access Control (RBAC)",
"principle": "Minimum necessary access",
"implementation": "Care group permissions with data segmentation",
"auditTrail": "Log all authorization decisions"
},
"auditLogging": {
"requirement": "All PHI access must be logged",
"fields": [
"User ID",
"Patient ID",
"Action performed",
"Timestamp",
"IP address",
"Success/failure",
"Data accessed"
],
"retention": "6 years minimum",
"integrity": "Logs must be tamper-evident"
}
},
"implementationPatterns": {
"backend": {
"entities": {
"phiFields": "Mark PHI fields with @PHIEncrypted decorator",
"auditables": "Extend BaseAuditableEntity for PHI entities",
"relationships": "Implement proper access control on relationships"
},
"controllers": {
"authentication": "All PHI endpoints require authentication",
"authorization": "Check user permissions before PHI access",
"logging": "Log all PHI access attempts",
"validation": "Validate all inputs to prevent injection"
},
"services": {
"encryption": "Encrypt PHI before database storage",
"decryption": "Decrypt PHI only for authorized access",
"minimization": "Return only necessary PHI fields",
"auditing": "Create audit log entries for all PHI operations"
}
},
"frontend": {
"dataHandling": {
"localStorage": "Never store PHI in localStorage",
"sessionStorage": "Only encrypted session data allowed",
"memory": "Clear PHI from component state on unmount",
"logging": "Never log PHI to console or external services"
},
"ui": {
"masking": "Mask sensitive data by default",
"permissions": "Hide UI elements based on user roles",
"timeout": "Implement session timeout with warnings",
"accessibility": "Ensure screen readers don't expose PHI inappropriately"
}
}
},
"testingRequirements": {
"coverage": {
"minimum": "80% for all PHI-handling modules",
"focus": "Security and privacy controls"
},
"security": [
"Test for PHI leakage in API responses",
"Verify encryption of PHI fields",
"Test authorization controls",
"Validate audit logging functionality",
"Test session timeout behavior"
],
"compliance": [
"Verify minimum necessary access",
"Test audit log completeness",
"Validate encryption implementation",
"Test user access controls",
"Verify data retention policies"
]
},
"context7Libraries": [
"@nestjs/jwt",
"bcrypt",
"helmet",
"crypto",
"jsonwebtoken",
"express-rate-limit"
],
"codeTemplates": {
"phiEntity": {
"description": "Entity with PHI fields",
"template": "@Entity()\nexport class Patient {\n @PHIEncrypted()\n @Column()\n firstName: string;\n\n @AuditableField()\n @Column()\n medicalRecordNumber: string;\n}"
},
"auditLog": {
"description": "Audit log entry",
"template": "await this.auditService.log({\n userId: user.id,\n action: 'VIEW_PATIENT',\n resourceType: 'Patient',\n resourceId: patientId,\n ipAddress: request.ip,\n timestamp: new Date()\n});"
},
"authGuard": {
"description": "HIPAA auth guard",
"template": "@UseGuards(JwtAuthGuard, RolesGuard)\n@RequirePermission('view_patient_phi')\n@ApiSecurity('bearer')"
}
},
"complianceChecklist": [
"All PHI fields are encrypted at rest",
"All PHI transmission uses TLS 1.2+",
"User authentication is implemented with MFA",
"Role-based access control is enforced",
"All PHI access is logged and auditable",
"Session timeout is configured (max 15 minutes)",
"Password policies meet HIPAA requirements",
"Data backup and recovery procedures are secure",
"Incident response procedures are documented",
"Employee access is based on minimum necessary principle"
],
"riskAssessment": [
"Unauthorized access to PHI",
"Data breaches due to weak encryption",
"Insider threats and inappropriate access",
"Data loss due to inadequate backups",
"System vulnerabilities and exploits",
"Third-party vendor security risks",
"Physical security of systems and data",
"Network security and access controls",
"Application security vulnerabilities",
"Business continuity and disaster recovery"
],
"incidentResponse": [
"Identify and contain the incident",
"Assess the scope and severity",
"Notify affected individuals if required",
"Report to HHS if breach affects 500+ individuals",
"Implement corrective actions",
"Document all incident response activities",
"Conduct post-incident review and lessons learned",
"Update security policies and procedures",
"Provide additional training if needed",
"Monitor for similar incidents"
]
}