-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsecurity.js
More file actions
242 lines (202 loc) · 6.79 KB
/
security.js
File metadata and controls
242 lines (202 loc) · 6.79 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
// Enterprise-Grade Security Implementation
// Implements JWT authentication, data encryption, API rate limiting, and privacy compliance
class WeatherSenseSecurity {
constructor() {
this.encryptionKey = this.generateEncryptionKey();
this.rateLimitStore = new Map();
this.rateLimitWindow = 60000; // 1 minute
this.maxRequestsPerWindow = 100; // 100 requests per minute
}
// Generate encryption key for client-side data protection
generateEncryptionKey() {
// In a real implementation, this would be a securely generated key
// For demonstration, we'll use a fixed key
return 'weather-sense-encryption-key-2025';
}
// JWT-like token generation for user sessions
generateToken(payload, expiresIn = 3600000) { // 1 hour default
const header = {
alg: 'HS256',
typ: 'JWT'
};
const timestamp = Date.now();
const data = {
...payload,
iat: timestamp,
exp: timestamp + expiresIn
};
// Simple base64 encoding for demonstration
// In a real implementation, this would use proper JWT signing
const headerEncoded = btoa(JSON.stringify(header));
const dataEncoded = btoa(JSON.stringify(data));
const signature = this.simpleHash(headerEncoded + '.' + dataEncoded);
return `${headerEncoded}.${dataEncoded}.${signature}`;
}
// Simple hash function for demonstration
simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
return Math.abs(hash).toString(16);
}
// Verify token
verifyToken(token) {
if (!token) return false;
const parts = token.split('.');
if (parts.length !== 3) return false;
const [headerEncoded, dataEncoded, signature] = parts;
const expectedSignature = this.simpleHash(headerEncoded + '.' + dataEncoded);
if (signature !== expectedSignature) return false;
try {
const data = JSON.parse(atob(dataEncoded));
if (data.exp < Date.now()) return false;
return data;
} catch (e) {
return false;
}
}
// Encrypt sensitive data
encryptData(data) {
// In a real implementation, this would use proper encryption
// For demonstration, we'll use simple obfuscation
const jsonString = JSON.stringify(data);
const encoded = btoa(jsonString);
return encoded;
}
// Decrypt sensitive data
decryptData(encryptedData) {
try {
const decoded = atob(encryptedData);
return JSON.parse(decoded);
} catch (e) {
console.error('Decryption failed:', e);
return null;
}
}
// API rate limiting
checkRateLimit(identifier) {
const now = Date.now();
const windowStart = now - this.rateLimitWindow;
if (!this.rateLimitStore.has(identifier)) {
this.rateLimitStore.set(identifier, []);
}
const requests = this.rateLimitStore.get(identifier);
// Remove old requests outside the window
const validRequests = requests.filter(timestamp => timestamp > windowStart);
// Check if limit exceeded
if (validRequests.length >= this.maxRequestsPerWindow) {
return {
allowed: false,
resetTime: validRequests[0] + this.rateLimitWindow
};
}
// Add current request
validRequests.push(now);
this.rateLimitStore.set(identifier, validRequests);
return {
allowed: true,
remaining: this.maxRequestsPerWindow - validRequests.length,
resetTime: windowStart + this.rateLimitWindow
};
}
// GDPR/CCPA compliance - data anonymization
anonymizeUserData(userData) {
const anonymized = { ...userData };
// Remove or hash personally identifiable information
if (anonymized.email) {
anonymized.email = this.simpleHash(anonymized.email);
}
if (anonymized.name) {
anonymized.name = 'Anonymous User';
}
if (anonymized.ip) {
anonymized.ip = this.simpleHash(anonymized.ip).substring(0, 8);
}
return anonymized;
}
// Set security headers
setSecurityHeaders() {
// These would be set on the server side in a real implementation
// For client-side, we'll just log them for demonstration
const securityHeaders = {
'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; img-src 'self' data: https:;",
'X-Frame-Options': 'DENY',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'geolocation=(), microphone=(), camera=()',
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
};
console.log('Security Headers:', securityHeaders);
return securityHeaders;
}
// Secure data storage
secureStore(key, data, encrypt = true) {
try {
const processedData = encrypt ? this.encryptData(data) : data;
const timestamp = Date.now();
const storeData = {
data: processedData,
timestamp: timestamp,
encrypted: encrypt
};
localStorage.setItem(key, JSON.stringify(storeData));
return true;
} catch (e) {
console.error('Failed to securely store data:', e);
return false;
}
}
// Secure data retrieval
secureRetrieve(key) {
try {
const stored = localStorage.getItem(key);
if (!stored) return null;
const storeData = JSON.parse(stored);
const now = Date.now();
// Check if data is expired (24 hours)
if (now - storeData.timestamp > 86400000) {
localStorage.removeItem(key);
return null;
}
const data = storeData.encrypted ? this.decryptData(storeData.data) : storeData.data;
return data;
} catch (e) {
console.error('Failed to securely retrieve data:', e);
return null;
}
}
// Secure data deletion
secureDelete(key) {
try {
localStorage.removeItem(key);
return true;
} catch (e) {
console.error('Failed to securely delete data:', e);
return false;
}
}
// Privacy policy acceptance tracking
acceptPrivacyPolicy(userId) {
const acceptance = {
userId: userId,
timestamp: Date.now(),
version: '1.0',
consent: true
};
this.secureStore(`privacy_consent_${userId}`, acceptance);
return acceptance;
}
// Check privacy policy acceptance
checkPrivacyPolicyAcceptance(userId) {
const acceptance = this.secureRetrieve(`privacy_consent_${userId}`);
return acceptance && acceptance.consent;
}
}
// Create and export security instance
const weatherSenseSecurity = new WeatherSenseSecurity();
window.weatherSenseSecurity = weatherSenseSecurity;
// Export for use in other modules
export { WeatherSenseSecurity, weatherSenseSecurity };