-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathSecureUserProfile.js
More file actions
481 lines (415 loc) · 13.4 KB
/
SecureUserProfile.js
File metadata and controls
481 lines (415 loc) · 13.4 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
const mongoose = require('mongoose');
const { encryptionPlugin } = require('../middleware/fieldEncryption');
/**
* SecureUserProfile Model
* Example implementation of field-level encryption
* Issue #827: End-to-End Encryption for Sensitive Data
*
* This model demonstrates best practices for storing
* PII (Personally Identifiable Information) and
* sensitive financial data with automatic encryption.
*/
const SecureUserProfileSchema = new mongoose.Schema({
// ============================================================================
// Public Fields (Not Encrypted)
// ============================================================================
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
unique: true
},
username: {
type: String,
required: true
},
displayName: {
type: String
},
profilePicture: {
type: String
},
// ============================================================================
// PII Fields (Auto-Encrypted with 'userData' purpose)
// ============================================================================
// These fields are automatically detected and encrypted
email: {
type: String,
required: true
},
phoneNumber: {
type: String
},
dateOfBirth: {
type: Date
},
ssn: {
type: String // Social Security Number - PCI DSS Level 1
},
passport: {
type: String
},
driverLicense: {
type: String
},
nationalId: {
type: String
},
// Address (contains PII)
address: {
street: { type: String },
city: { type: String },
state: { type: String },
zipCode: { type: String },
country: { type: String }
},
// ============================================================================
// Financial Data (Auto-Encrypted with 'financialData' purpose)
// ============================================================================
financialInfo: {
// Primary bank account
bankAccountNumber: {
type: String
},
routingNumber: {
type: String
},
iban: {
type: String
},
swift: {
type: String
},
// Payment cards
paymentCards: [{
cardNumber: { type: String }, // PAN - must be encrypted
cardholderName: { type: String },
expirationDate: { type: String },
cardBrand: { type: String }, // Visa, MasterCard, etc.
lastFourDigits: { type: String }, // For display only
isDefault: { type: Boolean, default: false }
}],
// Income information
annualIncome: {
type: Number
},
salary: {
type: Number
},
// Net worth (sensitive)
netWorth: {
type: Number
}
},
// ============================================================================
// Tax Information (Auto-Encrypted)
// ============================================================================
taxInfo: {
taxId: { type: String }, // TIN/EIN
filingStatus: { type: String },
dependents: { type: Number }
},
// ============================================================================
// Employment Information (Partially Sensitive)
// ============================================================================
employment: {
employer: { type: String }, // Not encrypted
position: { type: String }, // Not encrypted
employeeId: { type: String }, // Encrypted
startDate: { type: Date }, // Not encrypted
workEmail: { type: String } // Encrypted
},
// ============================================================================
// Security & Privacy Settings
// ============================================================================
privacySettings: {
dataRetentionDays: { type: Number, default: 365 },
allowDataExport: { type: Boolean, default: true },
consentToProcess: { type: Boolean, default: true },
consentGivenAt: { type: Date }
},
// ============================================================================
// Encryption Audit Trail
// ============================================================================
encryptionAudit: [{
action: { type: String, enum: ['encrypted', 'decrypted', 'reencrypted'] },
fields: [{ type: String }],
keyId: { type: String },
timestamp: { type: Date, default: Date.now }
}],
// ============================================================================
// Compliance Metadata
// ============================================================================
compliance: {
pciDssCompliant: { type: Boolean, default: true },
gdprCompliant: { type: Boolean, default: true },
dataClassification: {
type: String,
enum: ['public', 'internal', 'confidential', 'restricted'],
default: 'restricted'
},
lastComplianceCheck: { type: Date }
}
}, {
timestamps: true,
toJSON: {
transform: function(doc, ret) {
// Remove encryption metadata from JSON output
delete ret._encrypted;
delete ret._encryptionVersion;
return ret;
}
}
});
// ============================================================================
// Apply Encryption Plugin
// ============================================================================
SecureUserProfileSchema.plugin(encryptionPlugin, {
// Explicitly specify sensitive fields to encrypt
fields: [
// PII
'email',
'phoneNumber',
'ssn',
'passport',
'driverLicense',
'nationalId',
'address',
// Financial
'financialInfo.bankAccountNumber',
'financialInfo.routingNumber',
'financialInfo.iban',
'financialInfo.swift',
'financialInfo.salary',
'financialInfo.annualIncome',
'financialInfo.netWorth',
// Payment cards
'financialInfo.paymentCards',
// Tax info
'taxInfo.taxId',
// Employment
'employment.employeeId',
'employment.workEmail'
],
// Primary purpose for this model
purpose: 'userData',
// Auto-detect additional sensitive fields based on field names
autoDetect: true
});
// ============================================================================
// Indexes
// ============================================================================
SecureUserProfileSchema.index({ userId: 1 }, { unique: true });
SecureUserProfileSchema.index({ username: 1 });
SecureUserProfileSchema.index({ createdAt: -1 });
// ============================================================================
// Instance Methods
// ============================================================================
/**
* Get masked profile for display
* Returns profile with sensitive fields masked
*/
SecureUserProfileSchema.methods.getMaskedProfile = function() {
const encryptionService = require('../services/encryptionService');
const masked = this.toObject();
// Mask sensitive fields
if (masked.ssn) {
masked.ssn = encryptionService.mask(masked.ssn, 'ssn');
}
if (masked.phoneNumber) {
masked.phoneNumber = encryptionService.mask(masked.phoneNumber, 'phone');
}
if (masked.email) {
masked.email = encryptionService.mask(masked.email, 'email');
}
if (masked.financialInfo?.bankAccountNumber) {
masked.financialInfo.bankAccountNumber = encryptionService.mask(
masked.financialInfo.bankAccountNumber,
'bankAccount'
);
}
if (masked.financialInfo?.paymentCards) {
masked.financialInfo.paymentCards = masked.financialInfo.paymentCards.map(card => ({
...card,
cardNumber: encryptionService.mask(card.cardNumber, 'card'),
lastFourDigits: card.cardNumber ? card.cardNumber.slice(-4) : null
}));
}
return masked;
};
/**
* Update encryption audit trail
*/
SecureUserProfileSchema.methods.logEncryptionAudit = function(action, fields, keyId) {
this.encryptionAudit.push({
action,
fields,
keyId,
timestamp: new Date()
});
};
/**
* Check if profile is compliant with regulations
*/
SecureUserProfileSchema.methods.checkCompliance = async function() {
const { getEncryptionStatus } = require('../middleware/fieldEncryption');
const encryptionStatus = getEncryptionStatus(this);
const compliance = {
pciDss: true,
gdpr: true,
issues: []
};
// Check if sensitive financial data is encrypted
if (this.financialInfo?.cardNumber && !encryptionStatus.isEncrypted) {
compliance.pciDss = false;
compliance.issues.push('Payment card data must be encrypted (PCI DSS 3.4)');
}
// Check if PII is encrypted (GDPR Article 32)
if ((this.ssn || this.email) && !encryptionStatus.isEncrypted) {
compliance.gdpr = false;
compliance.issues.push('Personal data must be encrypted (GDPR Article 32)');
}
// Update compliance metadata
this.compliance.pciDssCompliant = compliance.pciDss;
this.compliance.gdprCompliant = compliance.gdpr;
this.compliance.lastComplianceCheck = new Date();
return compliance;
};
/**
* Export user data (GDPR right to data portability)
*/
SecureUserProfileSchema.methods.exportUserData = async function() {
// Decrypt all fields for export
const decrypted = await this.decryptFields([
'email', 'phoneNumber', 'ssn', 'passport', 'driverLicense',
'financialInfo.bankAccountNumber', 'financialInfo.routingNumber'
]);
return {
exportedAt: new Date().toISOString(),
userId: this.userId,
username: this.username,
personalInfo: {
email: decrypted.email,
phoneNumber: decrypted.phoneNumber,
dateOfBirth: this.dateOfBirth,
address: decrypted.address
},
identityDocuments: {
ssn: decrypted.ssn,
passport: decrypted.passport,
driverLicense: decrypted.driverLicense
},
financialInfo: {
bankAccountNumber: decrypted.financialInfo?.bankAccountNumber,
routingNumber: decrypted.financialInfo?.routingNumber,
// Note: Payment card numbers are NOT exported for security
},
metadata: {
accountCreated: this.createdAt,
lastUpdated: this.updatedAt,
dataClassification: this.compliance.dataClassification
}
};
};
// ============================================================================
// Static Methods
// ============================================================================
/**
* Find profile with decrypted sensitive fields
*/
SecureUserProfileSchema.statics.findByUserIdDecrypted = async function(userId, fields = []) {
const profile = await this.findOne({ userId });
if (!profile) {
return null;
}
if (fields.length > 0) {
await profile.decryptFields(fields);
}
return profile;
};
/**
* Batch re-encryption for key rotation
*/
SecureUserProfileSchema.statics.batchReEncrypt = async function(batchSize = 50) {
const fields = [
'email', 'phoneNumber', 'ssn', 'passport', 'driverLicense',
'financialInfo.bankAccountNumber', 'financialInfo.routingNumber',
'taxInfo.taxId'
];
return await this.reEncryptAllDocuments(fields, batchSize);
};
/**
* Get profiles requiring compliance review
*/
SecureUserProfileSchema.statics.getComplianceReviewQueue = async function() {
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
return await this.find({
$or: [
{ 'compliance.lastComplianceCheck': { $lt: thirtyDaysAgo } },
{ 'compliance.lastComplianceCheck': null }
]
}).select('userId username compliance');
};
// ============================================================================
// Hooks
// ============================================================================
/**
* Pre-save hook for additional validation
*/
SecureUserProfileSchema.pre('save', async function(next) {
// Validate SSN format if provided
if (this.isModified('ssn') && this.ssn) {
const ssnRegex = /^\d{3}-?\d{2}-?\d{4}$/;
if (!ssnRegex.test(this.ssn)) {
return next(new Error('Invalid SSN format'));
}
}
// Validate email format
if (this.isModified('email') && this.email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(this.email)) {
return next(new Error('Invalid email format'));
}
}
// Run compliance check on first save
if (this.isNew) {
await this.checkCompliance();
}
next();
});
/**
* Post-save hook for audit logging
*/
SecureUserProfileSchema.post('save', function(doc) {
console.log(`✓ Secure profile saved for user: ${doc.userId}`);
// In production, integrate with your audit logging system
// Example: AuditLog.create({ ... })
});
// ============================================================================
// Virtual Properties
// ============================================================================
/**
* Get user's age from date of birth
*/
SecureUserProfileSchema.virtual('age').get(function() {
if (!this.dateOfBirth) return null;
const today = new Date();
const birthDate = new Date(this.dateOfBirth);
let age = today.getFullYear() - birthDate.getFullYear();
const monthDiff = today.getMonth() - birthDate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
});
/**
* Check if user is an adult (18+)
*/
SecureUserProfileSchema.virtual('isAdult').get(function() {
return this.age >= 18;
});
// ============================================================================
// Model Export
// ============================================================================
module.exports = mongoose.model('SecureUserProfile', SecureUserProfileSchema);