-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcors_test.html
492 lines (448 loc) · 19.8 KB
/
cors_test.html
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
482
483
484
485
486
487
488
489
490
491
492
<!DOCTYPE html>
<html>
<head>
<title>CORS Test</title>
<link rel="icon" href="data:,"> <!-- Empty favicon to prevent 404 errors -->
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f0f0f0;
}
.container {
max-width: 800px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.status {
margin-top: 20px;
padding: 10px;
border-radius: 4px;
}
.error {
background-color: #ffebee;
color: #c62828;
}
.success {
background-color: #e8f5e9;
color: #2e7d32;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 10px 0;
}
button:hover {
background-color: #45a049;
}
pre {
background-color: #f5f5f5;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
.debug-info {
margin-top: 20px;
font-size: 0.9em;
color: #666;
}
.cookie-info {
margin-top: 10px;
padding: 10px;
background-color: #f8f9fa;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container">
<h1>CORS Test Page</h1>
<p>This page tests CORS access to the task_timings endpoint.</p>
<div class="important-notice" style="background-color: #ffebee; color: #c62828; padding: 15px; margin: 15px 0; border-radius: 4px;">
<strong>Important:</strong> You must first log in through the main application at:
<a href="" id="loginLink" target="_blank">Loading...</a>
<br>
<small>Default credentials: username <strong>admin</strong>, password <strong>admin</strong></small>
</div>
<p class="debug-info">Testing against server: <span id="serverUrl"></span></p>
<div class="cookie-info">
<strong>Cookie Status:</strong>
<pre id="cookieInfo">Checking...</pre>
<div class="note" style="margin-top: 10px; font-size: 0.9em; color: #666;">
Note: Due to browser security, JavaScript might not be able to see the cookies directly,
but they are still being sent with requests. Check the server logs to confirm.
</div>
</div>
<button onclick="checkLoginStatus()">1. Check Login Status</button>
<button onclick="testTaskTimings()">2. Test Task Timings Access</button>
<button onclick="testTaskTimingsAPI()">3. Test Task Timings API</button>
<button onclick="checkServerCookies()">4. Check Server-Side Cookies</button>
<button onclick="testPreflightRequest()">5. Test Preflight Request</button>
<button onclick="testPostRequest()">6. Test POST Request</button>
<button onclick="testAllServers()">7. Test All Server Combinations</button>
<div id="status" class="status"></div>
<pre id="response"></pre>
</div>
<script>
// Get the target server URL from the current location
function getTargetServer() {
const hostname = window.location.hostname;
const protocol = window.location.protocol;
// Handle localhost
if (hostname === 'localhost' || hostname.match(/^(\d{1,3}\.){3}\d{1,3}$/)) {
return 'http://localhost:5000';
}
// Define known test servers
const knownServers = [
'cli-debrid.godver3.xyz',
'cli-test.godver3.xyz'
];
// Create URLs for both HTTP and HTTPS
const servers = knownServers.map(server => ({
http: `http://${server}`,
https: `https://${server}`
}));
// Store all servers for testing
window.allTestServers = servers;
// Default to the first server's HTTPS URL
return servers[0].https;
}
const targetServer = getTargetServer();
document.getElementById('serverUrl').textContent = targetServer;
document.getElementById('loginLink').href = `${targetServer}/auth/login`;
document.getElementById('loginLink').textContent = `${targetServer}/auth/login`;
function updateCookieInfo() {
const cookieInfo = document.getElementById('cookieInfo');
const cookies = document.cookie;
let info = '';
info += 'Client-Side Cookie Info:\n';
if (cookies) {
const cookieList = cookies.split(';').map(cookie => {
const [name, value] = cookie.trim().split('=');
return `${name} = ${value.substring(0, 20)}${value.length > 20 ? '...' : ''}`;
});
info += cookieList.join('\n');
} else {
info += 'No cookies visible to JavaScript\n';
info += '(This is normal due to security settings)\n';
}
info += '\nDebug Info:\n';
info += `Location hostname: ${window.location.hostname}\n`;
info += `Target server: ${targetServer}\n`;
info += `Protocol: ${window.location.protocol}\n`;
info += `Port: ${window.location.port}\n`;
info += `Available test servers:\n`;
if (window.allTestServers) {
window.allTestServers.forEach(server => {
info += ` HTTPS: ${server.https}\n`;
info += ` HTTP: ${server.http}\n`;
});
}
info += '\nNote: Cookies may still be sent with requests even if not visible here.\n';
info += 'Check server logs or network tab for confirmation.';
cookieInfo.innerHTML = info;
}
async function checkServerCookies() {
try {
showStatus('Checking server-side cookies...');
const response = await fetch(`${window.location.origin}/cookie-check`, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
});
const data = await response.text();
showResponse({
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries([...response.headers.entries()]),
cookies: data
});
showStatus('Successfully checked server-side cookies');
} catch (error) {
showStatus('Error checking server-side cookies: ' + error.message, true);
console.error('Error:', error);
}
}
// Update cookie info every 2 seconds
updateCookieInfo();
setInterval(updateCookieInfo, 2000);
function showStatus(message, isError = false) {
const statusDiv = document.getElementById('status');
statusDiv.textContent = message;
statusDiv.className = 'status ' + (isError ? 'error' : 'success');
}
function showResponse(data) {
const responseDiv = document.getElementById('response');
if (typeof data === 'object') {
responseDiv.textContent = JSON.stringify(data, null, 2);
} else {
responseDiv.textContent = String(data).substring(0, 1000) +
(String(data).length > 1000 ? '...' : '');
}
}
async function checkLoginStatus() {
try {
showStatus('Checking login status...');
const response = await fetch(`${targetServer}/auth/login`, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'text/html',
'X-Requested-With': 'XMLHttpRequest'
},
mode: 'cors'
});
showResponse({
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries([...response.headers.entries()]),
url: response.url
});
// Check if we're redirected to root (which means we're logged in)
if (response.redirected && response.url === `${targetServer}/`) {
showStatus('Successfully logged in - redirected to root');
return true;
}
// Check if we have session cookie
const hasCookie = document.cookie.includes('session=') ||
response.headers.get('cookie')?.includes('session=');
if (hasCookie) {
showStatus('Session cookie present - likely logged in');
return true;
} else {
showStatus('Warning: No session cookie found. This could be due to:\n' +
'1. Not being logged in\n' +
'2. Cookies being blocked by browser settings\n' +
'3. SameSite cookie restrictions\n' +
'4. Different domains/subdomains\n' +
'Try accessing this page using the same hostname as your main application.', true);
return false;
}
} catch (error) {
showStatus(`Error checking login status: ${error.message}\n\n` +
'This could be due to CORS restrictions or the server being unavailable.', true);
console.error('Error:', error);
return false;
}
}
async function testTaskTimings() {
if (!(await checkLoginStatus())) {
return;
}
try {
const response = await fetch(`${targetServer}/program_operation/task_timings`, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'text/html',
'X-Requested-With': 'XMLHttpRequest'
}
});
const text = await response.text();
showStatus('Successfully accessed task_timings page');
showResponse(text);
} catch (error) {
showStatus(`Error accessing task_timings: ${error.message}`, true);
console.error('Error:', error);
}
}
async function testTaskTimingsAPI() {
if (!(await checkLoginStatus())) {
return;
}
try {
const response = await fetch(`${targetServer}/program_operation/api/task_timings`, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
});
const data = await response.json();
showStatus('Successfully accessed task_timings API');
showResponse(data);
} catch (error) {
showStatus(`Error accessing task_timings API: ${error.message}`, true);
console.error('Error:', error);
}
}
async function testPreflightRequest() {
try {
showStatus('Testing preflight request...');
const response = await fetch(`${targetServer}/auth/login`, {
method: 'OPTIONS',
credentials: 'include',
headers: {
'Accept': 'text/html',
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Request-Method': 'POST',
'Access-Control-Request-Headers': 'Content-Type'
},
mode: 'cors'
});
showResponse({
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries([...response.headers.entries()]),
message: 'Preflight request successful'
});
showStatus('Successfully tested preflight request');
} catch (error) {
showStatus('Error testing preflight request: ' + error.message, true);
console.error('Error:', error);
}
}
async function testPostRequest() {
try {
showStatus('Testing POST request...');
// First try a simple POST to the login endpoint
const response = await fetch(`${targetServer}/auth/login`, {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
},
body: 'test=true', // Simple form data
mode: 'cors'
});
const data = await response.text();
const result = {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries([...response.headers.entries()]),
response: data
};
// Even if we get a redirect or error, that's OK - we're testing CORS
if (response.status === 405) {
result.note = "The endpoint doesn't accept POST, but CORS is working (request went through)";
} else if (response.status === 302) {
result.note = "Got a redirect, which is normal. CORS is working correctly.";
}
showResponse(result);
showStatus('Successfully tested POST request - CORS is working even if endpoint returned an error');
} catch (error) {
showStatus('Error testing POST request: ' + error.message, true);
console.error('Error:', error);
}
}
// Add new function to test all server combinations
async function testAllServers() {
showStatus('Testing all server combinations...');
const results = {
tests: []
};
for (const server of window.allTestServers) {
// Test HTTPS to HTTPS
try {
showStatus(`Testing HTTPS -> HTTPS: ${server.https}`);
const response = await fetch(`${server.https}/auth/login`, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'text/html',
'X-Requested-With': 'XMLHttpRequest'
}
});
results.tests.push({
type: 'HTTPS -> HTTPS',
server: server.https,
status: response.status,
success: response.status === 200 || response.status === 302
});
} catch (error) {
results.tests.push({
type: 'HTTPS -> HTTPS',
server: server.https,
error: error.message,
success: false
});
}
// Test HTTP to HTTP
try {
showStatus(`Testing HTTP -> HTTP: ${server.http}`);
const response = await fetch(`${server.http}/auth/login`, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'text/html',
'X-Requested-With': 'XMLHttpRequest'
}
});
results.tests.push({
type: 'HTTP -> HTTP',
server: server.http,
status: response.status,
success: response.status === 200 || response.status === 302
});
} catch (error) {
results.tests.push({
type: 'HTTP -> HTTP',
server: server.http,
error: error.message,
success: false
});
}
// Test mixed protocol (if current page is HTTPS)
if (window.location.protocol === 'https:') {
try {
showStatus(`Testing HTTPS -> HTTP: ${server.http}`);
const response = await fetch(`${server.http}/auth/login`, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'text/html',
'X-Requested-With': 'XMLHttpRequest'
}
});
results.tests.push({
type: 'HTTPS -> HTTP',
server: server.http,
status: response.status,
success: response.status === 200 || response.status === 302
});
} catch (error) {
results.tests.push({
type: 'HTTPS -> HTTP',
server: server.http,
error: error.message,
success: false
});
}
}
}
showResponse(results);
const successCount = results.tests.filter(t => t.success).length;
showStatus(`Completed all server tests. ${successCount}/${results.tests.length} tests passed.`);
}
// Add button for testing all servers
document.addEventListener('DOMContentLoaded', function() {
const container = document.querySelector('.container');
const newButton = document.createElement('button');
newButton.textContent = '7. Test All Server Combinations';
newButton.onclick = testAllServers;
newButton.style.backgroundColor = '#2196F3';
container.insertBefore(newButton, document.getElementById('status'));
// Add protocol info
const protocolInfo = document.createElement('div');
protocolInfo.className = 'debug-info';
protocolInfo.innerHTML = `Current page protocol: <strong>${window.location.protocol}</strong>`;
container.insertBefore(protocolInfo, document.getElementById('status'));
});
</script>
</body>
</html>