Spaces:
Sleeping
Sleeping
| const mongoose = require('mongoose'); | |
| const crypto = require('crypto'); | |
| // Atlas MongoDB connection string | |
| const MONGODB_URI = 'mongodb+srv://nothingyu:wSg3lbO1PkHiRMq9@sandbox.ecysggv.mongodb.net/test?retryWrites=true&w=majority&appName=sandbox'; | |
| // Connect to MongoDB Atlas | |
| const connectDB = async () => { | |
| try { | |
| await mongoose.connect(MONGODB_URI); | |
| console.log('β Connected to MongoDB Atlas'); | |
| } catch (error) { | |
| console.error('β MongoDB connection error:', error); | |
| process.exit(1); | |
| } | |
| }; | |
| // Enhanced Subtitle Schema with security features | |
| const subtitleSchema = new mongoose.Schema({ | |
| segmentId: { type: Number, required: true, unique: true }, | |
| startTime: { type: String, required: true }, | |
| endTime: { type: String, required: true }, | |
| duration: { type: String, required: true }, | |
| englishText: { type: String, required: true }, | |
| chineseTranslation: { type: String, default: '' }, | |
| isProtected: { type: Boolean, default: false }, | |
| protectedReason: { type: String, default: '' }, | |
| lastModified: { type: Date, default: Date.now }, | |
| modificationHistory: [{ | |
| timestamp: { type: Date, default: Date.now }, | |
| action: String, | |
| previousValue: String, | |
| newValue: String, | |
| modifiedBy: String | |
| }], | |
| // New security fields | |
| contentChecksum: { type: String, required: true }, | |
| lastVerified: { type: Date, default: Date.now }, | |
| verificationHistory: [{ | |
| timestamp: Date, | |
| checksum: String, | |
| verifiedBy: String, | |
| status: String | |
| }], | |
| watermark: { type: String, default: '' }, | |
| accessLog: [{ | |
| timestamp: Date, | |
| userId: String, | |
| action: String, | |
| ip: String, | |
| userAgent: String | |
| }] | |
| }); | |
| const Subtitle = mongoose.model('Subtitle', subtitleSchema); | |
| // Security utilities | |
| const securityUtils = { | |
| generateChecksum: (content) => { | |
| return crypto.createHash('sha256').update(content).digest('hex'); | |
| }, | |
| addWatermark: (text, userId) => { | |
| const watermark = Buffer.from(userId || 'system').toString('base64').slice(0, 8); | |
| return text + '\u200B' + watermark; // Zero-width space + watermark | |
| }, | |
| extractWatermark: (text) => { | |
| const parts = text.split('\u200B'); | |
| return parts.length > 1 ? parts[1] : null; | |
| }, | |
| validateTimeFormat: (timeString) => { | |
| const timePattern = /^\d{2}:\d{2}:\d{2},\d{3}$/; | |
| return timePattern.test(timeString); | |
| }, | |
| sanitizeInput: (text) => { | |
| // Basic XSS prevention | |
| return text | |
| .replace(/</g, '<') | |
| .replace(/>/g, '>') | |
| .replace(/"/g, '"') | |
| .replace(/'/g, ''') | |
| .replace(/\//g, '/'); | |
| } | |
| }; | |
| // Enhanced protection system | |
| const enhancedProtection = { | |
| async addSecurityFeatures() { | |
| try { | |
| console.log('π Adding security features to existing subtitles...'); | |
| const subtitles = await Subtitle.find({}); | |
| console.log(`π Found ${subtitles.length} subtitle segments`); | |
| let updatedCount = 0; | |
| for (const subtitle of subtitles) { | |
| const updates = {}; | |
| // Generate checksum if not exists | |
| if (!subtitle.contentChecksum) { | |
| const content = subtitle.englishText + subtitle.startTime + subtitle.endTime; | |
| updates.contentChecksum = securityUtils.generateChecksum(content); | |
| } | |
| // Add watermark if not exists | |
| if (!subtitle.watermark) { | |
| updates.watermark = securityUtils.addWatermark(subtitle.englishText, 'system'); | |
| } | |
| // Add verification history if empty | |
| if (!subtitle.verificationHistory || subtitle.verificationHistory.length === 0) { | |
| updates.verificationHistory = [{ | |
| timestamp: new Date(), | |
| checksum: subtitle.contentChecksum || securityUtils.generateChecksum(subtitle.englishText + subtitle.startTime + subtitle.endTime), | |
| verifiedBy: 'system', | |
| status: 'verified' | |
| }]; | |
| } | |
| // Update if any changes needed | |
| if (Object.keys(updates).length > 0) { | |
| await Subtitle.findByIdAndUpdate(subtitle._id, { | |
| ...updates, | |
| lastModified: new Date(), | |
| $push: { | |
| modificationHistory: { | |
| timestamp: new Date(), | |
| action: 'SECURITY_ENHANCEMENT', | |
| previousValue: 'none', | |
| newValue: 'security_features_added', | |
| modifiedBy: 'system' | |
| } | |
| } | |
| }); | |
| updatedCount++; | |
| } | |
| } | |
| console.log(`β Enhanced ${updatedCount} subtitle segments with security features`); | |
| // Verify integrity | |
| await this.verifyAllIntegrity(); | |
| } catch (error) { | |
| console.error('β Error adding security features:', error); | |
| } | |
| }, | |
| async verifyAllIntegrity() { | |
| try { | |
| console.log('π Verifying integrity of all subtitle segments...'); | |
| const subtitles = await Subtitle.find({}); | |
| let verifiedCount = 0; | |
| let failedCount = 0; | |
| for (const subtitle of subtitles) { | |
| const currentChecksum = securityUtils.generateChecksum( | |
| subtitle.englishText + subtitle.startTime + subtitle.endTime | |
| ); | |
| if (currentChecksum === subtitle.contentChecksum) { | |
| verifiedCount++; | |
| } else { | |
| failedCount++; | |
| console.warn(`β οΈ Integrity check failed for segment ${subtitle.segmentId}`); | |
| } | |
| } | |
| console.log(`β Integrity verification complete:`); | |
| console.log(` - Verified: ${verifiedCount} segments`); | |
| console.log(` - Failed: ${failedCount} segments`); | |
| if (failedCount > 0) { | |
| console.log('β οΈ Some segments failed integrity checks. Consider investigation.'); | |
| } | |
| } catch (error) { | |
| console.error('β Error during integrity verification:', error); | |
| } | |
| }, | |
| async createSecurityLogsCollection() { | |
| try { | |
| console.log('π Creating security logs collection...'); | |
| const securityLogSchema = new mongoose.Schema({ | |
| timestamp: { type: Date, default: Date.now }, | |
| event: { type: String, required: true }, | |
| details: mongoose.Schema.Types.Mixed, | |
| ip: String, | |
| userAgent: String, | |
| userId: String, | |
| severity: { type: String, enum: ['low', 'medium', 'high', 'critical'], default: 'medium' } | |
| }); | |
| const SecurityLog = mongoose.model('SecurityLog', securityLogSchema); | |
| // Create index for efficient querying | |
| await SecurityLog.createIndexes(); | |
| console.log('β Security logs collection created'); | |
| // Log initial security enhancement | |
| await SecurityLog.create({ | |
| event: 'SECURITY_ENHANCEMENT_IMPLEMENTED', | |
| details: { | |
| action: 'Enhanced subtitle protection system', | |
| features: ['checksums', 'watermarks', 'integrity_verification'], | |
| timestamp: new Date() | |
| }, | |
| severity: 'high' | |
| }); | |
| } catch (error) { | |
| console.error('β Error creating security logs:', error); | |
| } | |
| }, | |
| async createBackupVerification() { | |
| try { | |
| console.log('πΎ Creating backup verification system...'); | |
| const backupSchema = new mongoose.Schema({ | |
| backupName: { type: String, required: true, unique: true }, | |
| timestamp: { type: Date, default: Date.now }, | |
| collections: [String], | |
| totalRecords: Number, | |
| checksum: String, | |
| status: { type: String, enum: ['created', 'verified', 'restored'], default: 'created' }, | |
| createdBy: String | |
| }); | |
| const Backup = mongoose.model('Backup', backupSchema); | |
| // Create initial backup record | |
| const collections = ['subtitles', 'sourcetexts', 'submissions', 'users']; | |
| let totalRecords = 0; | |
| for (const collection of collections) { | |
| const count = await mongoose.connection.db.collection(collection).countDocuments(); | |
| totalRecords += count; | |
| } | |
| const backupData = { | |
| collections, | |
| totalRecords, | |
| checksum: securityUtils.generateChecksum(`backup-${Date.now()}`) | |
| }; | |
| await Backup.create({ | |
| backupName: `security-enhanced-backup-${new Date().toISOString()}`, | |
| collections, | |
| totalRecords, | |
| checksum: backupData.checksum, | |
| createdBy: 'system' | |
| }); | |
| console.log('β Backup verification system created'); | |
| console.log(`π Backup created with ${totalRecords} total records`); | |
| } catch (error) { | |
| console.error('β Error creating backup verification:', error); | |
| } | |
| } | |
| }; | |
| // Main implementation function | |
| const implementSecurityEnhancements = async () => { | |
| try { | |
| console.log('π Starting security enhancement implementation...'); | |
| // Step 1: Add security features to existing subtitles | |
| await enhancedProtection.addSecurityFeatures(); | |
| // Step 2: Verify integrity | |
| await enhancedProtection.verifyAllIntegrity(); | |
| // Step 3: Create security logs collection | |
| await enhancedProtection.createSecurityLogsCollection(); | |
| // Step 4: Create backup verification system | |
| await enhancedProtection.createBackupVerification(); | |
| console.log('\nπ Security enhancements implemented successfully!'); | |
| console.log('\nπ Implemented features:'); | |
| console.log(' β Content checksums for integrity verification'); | |
| console.log(' β Invisible watermarks for content tracking'); | |
| console.log(' β Security logging system'); | |
| console.log(' β Backup verification system'); | |
| console.log(' β Input sanitization utilities'); | |
| console.log(' β Time format validation'); | |
| console.log('\nπ Next steps:'); | |
| console.log(' 1. Implement JWT authentication'); | |
| console.log(' 2. Add rate limiting per user'); | |
| console.log(' 3. Set up monitoring and alerting'); | |
| console.log(' 4. Configure automated security testing'); | |
| } catch (error) { | |
| console.error('β Error implementing security enhancements:', error); | |
| } finally { | |
| await mongoose.disconnect(); | |
| console.log('π Disconnected from MongoDB'); | |
| } | |
| }; | |
| // Run the implementation | |
| connectDB().then(() => { | |
| implementSecurityEnhancements(); | |
| }); |