forked from platanus-hack/platanus-hack-25-arcade
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev-server.ts
More file actions
261 lines (225 loc) · 7.49 KB
/
Copy pathdev-server.ts
File metadata and controls
261 lines (225 loc) · 7.49 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
import { createServer, IncomingMessage, ServerResponse } from 'http';
import { readFileSync, watch } from 'fs';
import { execSync } from 'child_process';
import { createHash } from 'crypto';
import { checkRestrictions, CheckResults } from './check-restrictions.js';
const DEFAULT_COVER_SHA256 = 'b97a843d173c8fe4bfccbb7645d54d174a19f69dcd02b10af3111df07744a642';
// Check PNG dimensions by reading PNG header
function checkPNGDimensions(buffer: Buffer): { width: number; height: number; isPNG: boolean } {
// Check PNG signature
const pngSignature = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
if (!buffer.subarray(0, 8).equals(pngSignature)) {
return { width: 0, height: 0, isPNG: false };
}
// Read IHDR chunk (width at bytes 16-19, height at bytes 20-23)
const width = buffer.readUInt32BE(16);
const height = buffer.readUInt32BE(20);
return { width, height, isPNG: true };
}
const PORT = 3000;
let cachedChecks: CheckResults | null = null;
// Store SSE clients for broadcasting reload events
const sseClients: Set<ServerResponse> = new Set();
// Get Git repository information
function getGitInfo() {
try {
const remoteUrl = execSync('git config --get remote.origin.url', { encoding: 'utf-8' }).trim();
const username = execSync('git config user.name', { encoding: 'utf-8' }).trim();
const email = execSync('git config user.email', { encoding: 'utf-8' }).trim();
// Parse GitHub repo from remote URL
let repoUrl = remoteUrl;
if (remoteUrl.includes('github.com')) {
// Handle both SSH and HTTPS URLs
const match = remoteUrl.match(/github\.com[:/](.+?)(?:\.git)?$/);
if (match) {
repoUrl = `https://github.com/${match[1]}`;
}
}
return {
username,
email,
remoteUrl: repoUrl,
isGitRepo: true
};
} catch (error) {
return {
username: null,
email: null,
remoteUrl: null,
isGitRepo: false,
error: 'Not a git repository or git not configured'
};
}
}
// Run checks initially
async function updateChecks() {
try {
cachedChecks = await checkRestrictions('./game.js');
console.log(`\n🔄 Checks updated at ${new Date().toLocaleTimeString()}`);
console.log(` Size: ${cachedChecks.sizeKB.toFixed(2)} KB`);
console.log(` Status: ${cachedChecks.passed ? '✅ Passing' : '❌ Failing'}`);
// Notify all connected clients to reload
broadcastReload();
} catch (error) {
console.error('Error running checks:', error);
}
}
// Broadcast reload event to all SSE clients
function broadcastReload() {
sseClients.forEach((client) => {
try {
client.write('data: reload\n\n');
} catch (error) {
sseClients.delete(client);
}
});
}
// Watch game.js for changes
console.log('👀 Watching game.js for changes...');
watch('./game.js', (eventType) => {
if (eventType === 'change') {
updateChecks();
}
});
// Initial check
updateChecks();
const server = createServer(async (req, res) => {
const url = req.url || '/';
// CORS headers for development
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
try {
// Serve index.html
if (url === '/' || url === '/index.html') {
const html = readFileSync('./index.html', 'utf-8');
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
return;
}
// Serve game.js
if (url === '/game.js') {
const gameJs = readFileSync('./game.js', 'utf-8');
res.writeHead(200, { 'Content-Type': 'application/javascript' });
res.end(gameJs);
return;
}
// Serve metadata.json
if (url === '/metadata.json') {
const metadata = readFileSync('./metadata.json', 'utf-8');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(metadata);
return;
}
// API endpoint for restriction checks
if (url === '/api/checks') {
if (!cachedChecks) {
cachedChecks = await checkRestrictions('./game.js');
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(cachedChecks));
return;
}
// API endpoint for Git information
if (url === '/api/git-info') {
const gitInfo = getGitInfo();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(gitInfo));
return;
}
// API endpoint for cover check
if (url === '/api/cover-check') {
try {
const coverPath = './cover.png';
const coverBuffer = readFileSync(coverPath);
const coverHash = createHash('sha256').update(coverBuffer).digest('hex');
const isChanged = coverHash !== DEFAULT_COVER_SHA256;
// Check PNG dimensions
const { width, height, isPNG } = checkPNGDimensions(coverBuffer);
const isValidSize = width === 800 && height === 600;
let message = '';
let isValid = false;
if (!isPNG) {
message = 'cover.png is not a valid PNG file';
} else if (!isChanged) {
message = 'Default cover detected';
} else if (!isValidSize) {
message = `Cover is ${width}x${height}, must be 800x600`;
} else {
message = 'Custom cover provided';
isValid = true;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
exists: true,
isChanged: isChanged,
isPNG: isPNG,
width: width,
height: height,
isValidSize: isValidSize,
isValid: isValid,
message: message
}));
} catch (error) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
exists: false,
isChanged: false,
isPNG: false,
width: 0,
height: 0,
isValidSize: false,
isValid: false,
message: 'cover.png not found'
}));
}
return;
}
// SSE endpoint for live reload
if (url === '/sse') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
// Send initial connection message
res.write('data: connected\n\n');
// Add client to the set
sseClients.add(res);
// Remove client when connection closes
req.on('close', () => {
sseClients.delete(res);
});
return;
}
// 404 for everything else
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
} catch (error) {
console.error('Error handling request:', error);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
}
});
server.listen(PORT, () => {
console.log('\n🎮 Platanus Hack 25: Arcade Challenge Dev Server');
console.log('================================================');
console.log(`🚀 Server running at http://localhost:${PORT}`);
console.log(`📝 Edit game.js to see live updates`);
console.log(`🔍 Restrictions are checked automatically\n`);
console.log('Press Ctrl+C to stop\n');
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\n\n👋 Shutting down dev server...');
server.close(() => {
console.log('✅ Server stopped');
process.exit(0);
});
});