Repository navigation
Expand file tree
/
Copy pathproxy-server.js
More file actions
274 lines (236 loc) · 8.44 KB
/
Copy pathproxy-server.js
File metadata and controls
274 lines (236 loc) · 8.44 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
/**
* CORS Proxy Server for Moodle VLE
*
* Run with: node proxy-server.js
* Provides API endpoints that the web app expects.
*
* Required for web development due to CORS restrictions.
* Not needed for iOS/Android.
*/
const http = require('http');
const https = require('https');
const PORT = 3001;
const TARGET_HOST = 'www.vle.cam.ac.uk';
function makeRequest(options, postData) {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
resolve({
statusCode: res.statusCode,
headers: res.headers,
body: data
});
});
});
req.on('error', reject);
if (postData) req.write(postData);
req.end();
});
}
async function handleAjaxCall(reqBody, res) {
const { sesskey, cookies, methodname, args } = reqBody;
if (!sesskey || !cookies) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing sesskey or cookies' }));
return;
}
const url = `/lib/ajax/service.php?sesskey=${sesskey}&info=${methodname}`;
const postData = JSON.stringify([{
index: 0,
methodname,
args: args || {}
}]);
console.log(`[Proxy] AJAX call: ${methodname}`);
try {
const result = await makeRequest({
hostname: TARGET_HOST,
port: 443,
path: url,
method: 'POST',
headers: {
'Host': TARGET_HOST,
'Cookie': cookies,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
}
}, postData);
console.log(`[Proxy] AJAX response: ${result.statusCode}`);
let moodleData;
try {
moodleData = JSON.parse(result.body);
} catch (e) {
console.error('[Proxy] Invalid JSON from Moodle:', result.body.substring(0, 500));
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON from Moodle', body: result.body.substring(0, 200) }));
return;
}
if (Array.isArray(moodleData) && moodleData[0]) {
const firstResult = moodleData[0];
if (firstResult.error === true) {
console.error('[Proxy] Moodle error:', firstResult.exception);
if (firstResult.exception?.errorcode === 'invalidsesskey' ||
firstResult.exception?.errorcode === 'accessexception' ||
firstResult.exception?.errorcode === 'servicerequireslogin') {
res.writeHead(401, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'session_expired', detail: firstResult.exception.message }));
return;
}
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: firstResult.exception?.message || 'Moodle error', detail: firstResult.exception }));
return;
}
const responseData = firstResult.data !== undefined ? firstResult.data : firstResult;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(responseData));
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(moodleData));
} catch (err) {
console.error('[Proxy] AJAX error:', err.message);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
}
async function handleFetchPage(query, res) {
const { path, cookies } = query;
if (!path) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing path parameter' }));
return;
}
console.log(`[Proxy] Fetch page: ${path}`);
try {
let currentPath = path;
let result;
let redirectCount = 0;
const maxRedirects = 5;
while (redirectCount < maxRedirects) {
result = await makeRequest({
hostname: TARGET_HOST,
port: 443,
path: currentPath,
method: 'GET',
headers: {
'Host': TARGET_HOST,
'Cookie': cookies || '',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
}
});
if (result.statusCode >= 300 && result.statusCode < 400 && result.headers.location) {
const location = result.headers.location;
console.log(`[Proxy] Following redirect to: ${location}`);
// Check if redirecting to login page - this means session expired
if (location.includes('/login/') || location.includes('login.php')) {
console.log('[Proxy] Session expired - redirected to login');
res.writeHead(401, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'session_expired', detail: 'Redirected to login page' }));
return;
}
if (location.startsWith('http')) {
const url = new URL(location);
currentPath = url.pathname + url.search;
} else {
currentPath = location;
}
redirectCount++;
} else {
break;
}
}
// Also check if final page is the login page
if (result.body.includes('id="login"') || result.body.includes('loginform') ||
(result.body.length < 5000 && result.body.includes('login'))) {
console.log('[Proxy] Session expired - received login page');
res.writeHead(401, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'session_expired', detail: 'Received login page' }));
return;
}
console.log(`[Proxy] Final page size: ${result.body.length} bytes`);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(result.body);
} catch (err) {
console.error('[Proxy] Fetch page error:', err.message);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
}
const server = http.createServer(async (req, res) => {
// CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
const url = new URL(req.url, `http://localhost:${PORT}`);
const pathname = url.pathname;
// Health check
if (pathname === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
return;
}
// AJAX endpoint
if (pathname === '/proxy/api/ajax' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', async () => {
try {
const reqBody = JSON.parse(body);
await handleAjaxCall(reqBody, res);
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
}
});
return;
}
// Fetch page endpoint - GET
if (pathname === '/proxy/api/fetch-page' && req.method === 'GET') {
const query = {
path: url.searchParams.get('path'),
cookies: url.searchParams.get('cookies'),
};
await handleFetchPage(query, res);
return;
}
// Fetch page endpoint - POST (for cookies)
if (pathname === '/proxy/api/fetch-page' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', async () => {
try {
const reqBody = JSON.parse(body);
const path = url.searchParams.get('path');
await handleFetchPage({ path, cookies: reqBody.cookies }, res);
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
}
});
return;
}
// 404
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
error: 'Not found',
availableEndpoints: ['/proxy/api/ajax', '/proxy/api/fetch-page', '/health']
}));
});
server.listen(PORT, () => {
console.log(`
🚀 Moodle Proxy Server running at http://localhost:${PORT}
Endpoints:
POST /proxy/api/ajax - Moodle AJAX calls
GET /proxy/api/fetch-page - Fetch HTML pages
GET /health - Health check
For web testing, run the Expo web app and it will use this proxy.
`);
});