Spaces:
Sleeping
Sleeping
File size: 10,289 Bytes
da819ac | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | 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();
}); |