-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript-insecure.js
More file actions
347 lines (288 loc) · 10.4 KB
/
Copy pathscript-insecure.js
File metadata and controls
347 lines (288 loc) · 10.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
/**
* AI Chat Application - INSECURE VERSION (Educational Purpose Only)
*
* ⚠️ WARNING: This file demonstrates BAD SECURITY PRACTICES
*
* This version shows what NOT to do:
* - Hardcoded API keys (SECURITY RISK!)
* - No user input validation
* - Keys visible in source code
* - Keys stored in version control
*
* Use this ONLY for educational comparison with script.js
* NEVER use this approach in production!
*/
class InsecureAIChatApp {
constructor() {
// ❌ BAD PRACTICE: Hardcoded API keys
// This is what you should NEVER do in real applications
this.config = {
apiKey: 'YOUR_GROQ_API_KEY_HERE', // ❌ EXPOSED! (Replace with actual key for demo)
apiProvider: 'groq',
model: 'llama-3.1-8b-instant',
systemPrompt: 'You are a helpful AI assistant. Provide clear, concise, and accurate responses.'
};
// Chat history
this.chatHistory = [];
// API endpoints
this.apiEndpoints = {
groq: 'https://api.groq.com/openai/v1/chat/completions',
openrouter: 'https://openrouter.ai/api/v1/chat/completions',
huggingface: 'https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-chat-hf'
};
// Get DOM elements
this.elements = {
messagesContainer: document.getElementById('messagesContainer'),
messageInput: document.getElementById('messageInput'),
sendBtn: document.getElementById('sendBtn'),
clearBtn: document.getElementById('clearBtn'),
welcomeMessage: document.getElementById('welcomeMessage'),
statusIndicator: document.getElementById('statusIndicator')
};
// Initialize
this.init();
}
/**
* Initialize the insecure app
*/
init() {
this.setupEventListeners();
this.updateStatus();
this.setupTextareaResize();
// Show warning message
this.showSecurityWarning();
console.log('⚠️ INSECURE AI Chat App initialized - FOR EDUCATIONAL PURPOSES ONLY!');
}
/**
* Show security warning to users
*/
showSecurityWarning() {
const warningDiv = document.createElement('div');
warningDiv.className = 'security-warning';
warningDiv.innerHTML = `
<div class="warning-content">
<h3>♨️ API's Keys in JavaScript Function</h3>
</div>
`;
// Add warning styles
warningDiv.style.cssText = `
background:rgb(44, 123, 49);
color: white;
padding: 20px;
margin: 10px;
border-radius: 8px;
border-left: 5px solid #48c5ff;
font-family: Arial, sans-serif;
`;
// Insert warning at the top
const container = document.querySelector('.chat-container') || document.body;
container.insertBefore(warningDiv, container.firstChild);
}
/**
* Set up event listeners
*/
setupEventListeners() {
this.elements.sendBtn.addEventListener('click', () => this.sendMessage());
this.elements.messageInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.sendMessage();
}
});
this.elements.clearBtn.addEventListener('click', () => this.clearChat());
}
/**
* Auto-resize textarea
*/
setupTextareaResize() {
this.elements.messageInput.addEventListener('input', () => {
this.elements.messageInput.style.height = 'auto';
this.elements.messageInput.style.height = this.elements.messageInput.scrollHeight + 'px';
});
}
/**
* Update status (always shows as connected since key is hardcoded)
*/
updateStatus() {
this.elements.statusIndicator.classList.add('connected');
this.elements.statusIndicator.innerHTML = `
<span class="status-dot"></span>
Connected (${this.config.apiProvider}) - INSECURE VERSION
`;
}
/**
* Send message (simplified - no validation needed)
*/
async sendMessage() {
const message = this.elements.messageInput.value.trim();
if (!message) return;
// Hide welcome message
if (this.elements.welcomeMessage) {
this.elements.welcomeMessage.style.display = 'none';
}
// Clear input
this.elements.messageInput.value = '';
this.elements.messageInput.style.height = 'auto';
// Disable send button
this.elements.sendBtn.disabled = true;
// Add user message
this.addMessage('user', message);
// Add to chat history
this.chatHistory.push({
role: 'user',
content: message
});
// Show loading
const loadingId = this.addLoadingMessage();
try {
// Call API (using hardcoded key)
const response = await this.callAPI();
// Remove loading
this.removeMessage(loadingId);
// Add AI response
this.addMessage('assistant', response);
// Add to history
this.chatHistory.push({
role: 'assistant',
content: response
});
} catch (error) {
this.removeMessage(loadingId);
this.addMessage('assistant', `Error: ${error.message}`);
console.error('API Error:', error);
}
// Re-enable send button
this.elements.sendBtn.disabled = false;
this.elements.messageInput.focus();
}
/**
* Call API with hardcoded key
*/
async callAPI() {
const endpoint = this.apiEndpoints[this.config.apiProvider];
const messages = [
{ role: 'system', content: this.config.systemPrompt },
...this.chatHistory
];
const requestBody = {
model: this.config.model,
messages: messages,
temperature: 0.7,
max_tokens: 1024
};
// Make request with hardcoded API key
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.config.apiKey}`, // ❌ Hardcoded key!
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error?.message || `API request failed: ${response.status}`);
}
const data = await response.json();
const messageContent = data.choices[0]?.message?.content;
if (!messageContent) {
throw new Error('No response from API');
}
return messageContent;
}
/**
* Add message to chat
*/
addMessage(role, content) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${role}`;
const avatar = role === 'user' ? '👤' : '🤖';
const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
messageDiv.innerHTML = `
<div class="message-avatar">${avatar}</div>
<div class="message-content">
<div class="message-text">${this.formatMessage(content)}</div>
<div class="message-time">${time}</div>
</div>
`;
this.elements.messagesContainer.appendChild(messageDiv);
this.scrollToBottom();
return messageDiv.id = `msg-${Date.now()}`;
}
/**
* Format message content
*/
formatMessage(content) {
content = content.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
content = content.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
return `<pre><code>${code.trim()}</code></pre>`;
});
content = content.replace(/`([^`]+)`/g, '<code>$1</code>');
content = content.replace(/\n/g, '<br>');
return content;
}
/**
* Add loading message
*/
addLoadingMessage() {
const messageDiv = document.createElement('div');
const id = `loading-${Date.now()}`;
messageDiv.id = id;
messageDiv.className = 'message assistant';
messageDiv.innerHTML = `
<div class="message-avatar">🤖</div>
<div class="message-content">
<div class="loading-dots">
<span></span>
<span></span>
<span></span>
</div>
</div>
`;
this.elements.messagesContainer.appendChild(messageDiv);
this.scrollToBottom();
return id;
}
/**
* Remove message
*/
removeMessage(id) {
const message = document.getElementById(id);
if (message) {
message.remove();
}
}
/**
* Clear chat
*/
clearChat() {
if (this.chatHistory.length > 0) {
if (!confirm('Are you sure you want to clear the chat history?')) {
return;
}
}
this.chatHistory = [];
this.elements.messagesContainer.innerHTML = '';
if (this.elements.welcomeMessage) {
this.elements.welcomeMessage.style.display = 'flex';
}
console.log('Chat cleared');
}
/**
* Scroll to bottom
*/
scrollToBottom() {
setTimeout(() => {
this.elements.messagesContainer.scrollTop = this.elements.messagesContainer.scrollHeight;
}, 100);
}
}
// Initialize the insecure app
document.addEventListener('DOMContentLoaded', () => {
// Create global app instance
window.insecureChatApp = new InsecureAIChatApp();
console.log('⚠️ INSECURE AI Chat Application loaded - FOR EDUCATIONAL PURPOSES ONLY!');
console.log('🔒 Compare this with script.js to learn security best practices');
});