codepen-demokit 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/serve.mjs ADDED
@@ -0,0 +1,369 @@
1
+ import http from 'node:http';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { buildDemosJson, watchDemos } from './build-json.mjs';
5
+ import { SHELL_DIR } from './build-site.mjs';
6
+ import { loadSiteConfig, renderShellIndexHtml } from './config.mjs';
7
+
8
+ const HOST = '127.0.0.1';
9
+ const DEFAULT_PORT = 3000;
10
+
11
+ const MIME_TYPES = {
12
+ '.avif': 'image/avif',
13
+ '.css': 'text/css; charset=utf-8',
14
+ '.gif': 'image/gif',
15
+ '.html': 'text/html; charset=utf-8',
16
+ '.ico': 'image/x-icon',
17
+ '.jpeg': 'image/jpeg',
18
+ '.jpg': 'image/jpeg',
19
+ '.js': 'text/javascript; charset=utf-8',
20
+ '.json': 'application/json; charset=utf-8',
21
+ '.md': 'text/markdown; charset=utf-8',
22
+ '.mjs': 'text/javascript; charset=utf-8',
23
+ '.mp3': 'audio/mpeg',
24
+ '.mp4': 'video/mp4',
25
+ '.ogg': 'audio/ogg',
26
+ '.png': 'image/png',
27
+ '.svg': 'image/svg+xml',
28
+ '.txt': 'text/plain; charset=utf-8',
29
+ '.vtt': 'text/vtt; charset=utf-8',
30
+ '.wasm': 'application/wasm',
31
+ '.wav': 'audio/wav',
32
+ '.webm': 'video/webm',
33
+ '.webp': 'image/webp',
34
+ '.woff': 'font/woff',
35
+ '.woff2': 'font/woff2',
36
+ '.xml': 'application/xml; charset=utf-8',
37
+ };
38
+
39
+ const SHELL_FALLBACK_FILES = new Map([
40
+ ['/', 'index.html'],
41
+ ['/index.html', 'index.html'],
42
+ ['/styles.css', 'styles.css'],
43
+ ['/scripts.js', 'scripts.js'],
44
+ ]);
45
+
46
+ // TODO(security): Permissions-Policy and Content-Security-Policy are intentionally
47
+ // omitted on user demo routes served by this localhost-only dev server so users
48
+ // are free to author demos using inline scripts/styles, import maps, third-party
49
+ // CDNs, frameworks, or experimental browser APIs (sensors, media, fullscreen).
50
+ const BASE_SECURITY_HEADERS = {
51
+ 'Cache-Control': 'no-store',
52
+ 'Referrer-Policy': 'no-referrer',
53
+ 'X-Content-Type-Options': 'nosniff',
54
+ 'X-Frame-Options': 'SAMEORIGIN',
55
+ };
56
+
57
+ const SHELL_SECURITY_HEADERS = {
58
+ ...BASE_SECURITY_HEADERS,
59
+ 'Content-Security-Policy':
60
+ "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'",
61
+ };
62
+
63
+ function parsePort(rawPort) {
64
+ if (rawPort === undefined || rawPort === null || rawPort === '') return DEFAULT_PORT;
65
+ const parsed = Number.parseInt(String(rawPort), 10);
66
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
67
+ throw new Error(`Invalid PORT value: ${rawPort}`);
68
+ }
69
+ return parsed;
70
+ }
71
+
72
+ function sendError(res, statusCode, message, extraHeaders = {}) {
73
+ const body = `${statusCode} ${message}\n`;
74
+ res.writeHead(statusCode, {
75
+ ...SHELL_SECURITY_HEADERS,
76
+ ...extraHeaders,
77
+ 'Content-Type': 'text/plain; charset=utf-8',
78
+ 'Content-Length': Buffer.byteLength(body),
79
+ });
80
+ res.end(body);
81
+ }
82
+
83
+ function isWithinRoot(candidatePath, rootPath) {
84
+ return candidatePath === rootPath || candidatePath.startsWith(rootPath + path.sep);
85
+ }
86
+
87
+ async function resolveServeRoot(srcDir, srcRealpath, targetArg) {
88
+ if (!targetArg) {
89
+ return { rootDir: srcDir, rootRealpath: srcRealpath, label: 'src/', isRootServe: true };
90
+ }
91
+
92
+ if (targetArg.includes('\0') || targetArg.includes('\\') || path.isAbsolute(targetArg)) {
93
+ throw new Error(`Invalid target folder "${targetArg}": pass a relative folder path inside src/.`);
94
+ }
95
+
96
+ const trimmed = targetArg.replace(/\/+$/, '');
97
+ if (!trimmed) {
98
+ return { rootDir: srcDir, rootRealpath: srcRealpath, label: 'src/', isRootServe: true };
99
+ }
100
+
101
+ const segments = trimmed.split('/').filter(Boolean);
102
+ for (const segment of segments) {
103
+ if (segment === '.' || segment === '..' || segment.startsWith('.')) {
104
+ throw new Error(`Invalid target folder "${targetArg}": path traversal and hidden folders are not allowed.`);
105
+ }
106
+ }
107
+
108
+ const candidateDir = path.resolve(srcDir, ...segments);
109
+ if (!isWithinRoot(candidateDir, srcDir)) {
110
+ throw new Error(`Invalid target folder "${targetArg}": must resolve within src/.`);
111
+ }
112
+
113
+ let stat;
114
+ try {
115
+ stat = await fs.stat(candidateDir);
116
+ } catch {
117
+ throw new Error(`Folder "src/${segments.join('/')}" does not exist.`);
118
+ }
119
+
120
+ if (!stat.isDirectory()) {
121
+ throw new Error(`"src/${segments.join('/')}" is not a directory.`);
122
+ }
123
+
124
+ const realTargetDir = await fs.realpath(candidateDir);
125
+ if (!isWithinRoot(realTargetDir, srcRealpath)) {
126
+ throw new Error(`Invalid target folder "${targetArg}": resolves outside src/.`);
127
+ }
128
+
129
+ return {
130
+ rootDir: candidateDir,
131
+ rootRealpath: realTargetDir,
132
+ label: `src/${segments.join('/')}/`,
133
+ isRootServe: false,
134
+ };
135
+ }
136
+
137
+ async function resolveSafePath(rawPathname, rootDir, rootRealpath) {
138
+ let decodedPath;
139
+ try {
140
+ decodedPath = decodeURIComponent(rawPathname);
141
+ } catch {
142
+ return { status: 400, message: 'Bad Request' };
143
+ }
144
+
145
+ if (decodedPath.includes('\0') || decodedPath.includes('\\')) {
146
+ return { status: 400, message: 'Bad Request' };
147
+ }
148
+
149
+ const segments = decodedPath.split('/').filter(Boolean);
150
+ for (const segment of segments) {
151
+ if (segment === '.' || segment === '..' || segment.startsWith('.')) {
152
+ return { status: 403, message: 'Forbidden' };
153
+ }
154
+ }
155
+
156
+ const resolvedPath = path.resolve(rootDir, ...segments);
157
+ if (!isWithinRoot(resolvedPath, rootDir)) {
158
+ return { status: 403, message: 'Forbidden' };
159
+ }
160
+
161
+ let stat;
162
+ try {
163
+ stat = await fs.stat(resolvedPath);
164
+ } catch {
165
+ return { status: 404, message: 'Not Found' };
166
+ }
167
+
168
+ if (stat.isDirectory()) {
169
+ if (!decodedPath.endsWith('/')) {
170
+ const normalizedRedirect = `/${segments.map(encodeURIComponent).join('/')}/`;
171
+ return { status: 301, redirect: normalizedRedirect };
172
+ }
173
+
174
+ const indexPath = path.join(resolvedPath, 'index.html');
175
+ try {
176
+ const indexStat = await fs.stat(indexPath);
177
+ if (!indexStat.isFile()) {
178
+ return { status: 404, message: 'Not Found' };
179
+ }
180
+ const realIndexPath = await fs.realpath(indexPath);
181
+ if (!isWithinRoot(realIndexPath, rootRealpath)) {
182
+ return { status: 403, message: 'Forbidden' };
183
+ }
184
+ return { status: 200, filePath: realIndexPath, size: indexStat.size };
185
+ } catch {
186
+ return { status: 404, message: 'Not Found' };
187
+ }
188
+ }
189
+
190
+ if (!stat.isFile()) {
191
+ return { status: 404, message: 'Not Found' };
192
+ }
193
+
194
+ const realFilePath = await fs.realpath(resolvedPath);
195
+ if (!isWithinRoot(realFilePath, rootRealpath)) {
196
+ return { status: 403, message: 'Forbidden' };
197
+ }
198
+
199
+ return { status: 200, filePath: realFilePath, size: stat.size };
200
+ }
201
+
202
+ export async function startServer({
203
+ projectDir = process.cwd(),
204
+ targetFolder = null,
205
+ port: rawPort = process.env.PORT,
206
+ } = {}) {
207
+ const resolvedProjectDir = path.resolve(projectDir);
208
+ const srcDir = path.resolve(resolvedProjectDir, 'src');
209
+ const distDemosJsonPath = path.resolve(resolvedProjectDir, 'dist', 'demos.json');
210
+
211
+ let srcRealpath;
212
+ try {
213
+ srcRealpath = await fs.realpath(srcDir);
214
+ } catch {
215
+ throw new Error(`Directory "src/" not found in ${resolvedProjectDir}.`);
216
+ }
217
+
218
+ const { rootDir, rootRealpath, label, isRootServe } = await resolveServeRoot(
219
+ srcDir,
220
+ srcRealpath,
221
+ targetFolder,
222
+ );
223
+ const port = parsePort(rawPort);
224
+
225
+ const { demoCount } = await buildDemosJson({
226
+ projectDir: resolvedProjectDir,
227
+ outputFile: distDemosJsonPath,
228
+ });
229
+ console.log(`Built dist/demos.json (${demoCount} ${demoCount === 1 ? 'demo' : 'demos'})`);
230
+
231
+ const demoWatcher = watchDemos({
232
+ projectDir: resolvedProjectDir,
233
+ outputFile: distDemosJsonPath,
234
+ onRebuild({ demoCount: updatedCount }) {
235
+ console.log(`Rebuilt dist/demos.json (${updatedCount} ${updatedCount === 1 ? 'demo' : 'demos'})`);
236
+ },
237
+ onError(error) {
238
+ console.error(`Error rebuilding dist/demos.json: ${error.message}`);
239
+ },
240
+ });
241
+ console.log('Watching src/ for demo changes…');
242
+
243
+ const server = http.createServer(async (req, res) => {
244
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
245
+ sendError(res, 405, 'Method Not Allowed', { Allow: 'GET, HEAD' });
246
+ return;
247
+ }
248
+
249
+ let requestUrl;
250
+ try {
251
+ requestUrl = new URL(req.url ?? '/', `http://${HOST}:${port}`);
252
+ } catch {
253
+ sendError(res, 400, 'Bad Request');
254
+ return;
255
+ }
256
+
257
+ // Serve generated dist/demos.json at /demos.json when serving root
258
+ if (isRootServe && requestUrl.pathname === '/demos.json') {
259
+ try {
260
+ const content = await fs.readFile(distDemosJsonPath);
261
+ res.writeHead(200, {
262
+ ...SHELL_SECURITY_HEADERS,
263
+ 'Content-Type': 'application/json; charset=utf-8',
264
+ 'Content-Length': content.byteLength,
265
+ });
266
+ if (req.method === 'HEAD') {
267
+ res.end();
268
+ } else {
269
+ res.end(content);
270
+ }
271
+ } catch {
272
+ sendError(res, 404, 'Not Found');
273
+ }
274
+ return;
275
+ }
276
+
277
+ const result = await resolveSafePath(requestUrl.pathname, rootDir, rootRealpath);
278
+
279
+ if (result.status === 301 && result.redirect) {
280
+ res.writeHead(301, {
281
+ ...BASE_SECURITY_HEADERS,
282
+ Location: result.redirect,
283
+ });
284
+ res.end();
285
+ return;
286
+ }
287
+
288
+ // Fall back to framework shell for root index assets if not overridden in src/
289
+ if (result.status === 404 && isRootServe && SHELL_FALLBACK_FILES.has(requestUrl.pathname)) {
290
+ const shellFile = SHELL_FALLBACK_FILES.get(requestUrl.pathname);
291
+ const shellPath = path.join(SHELL_DIR, shellFile);
292
+ const ext = path.extname(shellPath).toLowerCase();
293
+ const contentType = MIME_TYPES[ext] ?? 'application/octet-stream';
294
+
295
+ try {
296
+ let content;
297
+ if (shellFile === 'index.html') {
298
+ const templateHtml = await fs.readFile(shellPath, 'utf8');
299
+ const siteConfig = loadSiteConfig(resolvedProjectDir);
300
+ content = Buffer.from(renderShellIndexHtml(templateHtml, siteConfig), 'utf8');
301
+ } else {
302
+ content = await fs.readFile(shellPath);
303
+ }
304
+
305
+ res.writeHead(200, {
306
+ ...SHELL_SECURITY_HEADERS,
307
+ 'Content-Type': contentType,
308
+ 'Content-Length': content.byteLength,
309
+ });
310
+ if (req.method === 'HEAD') {
311
+ res.end();
312
+ } else {
313
+ res.end(content);
314
+ }
315
+ } catch {
316
+ sendError(res, 500, 'Internal Server Error');
317
+ }
318
+ return;
319
+ }
320
+
321
+ if (result.status !== 200 || !result.filePath) {
322
+ sendError(res, result.status, result.message ?? 'Error');
323
+ return;
324
+ }
325
+
326
+ const ext = path.extname(result.filePath).toLowerCase();
327
+ const contentType = MIME_TYPES[ext] ?? 'application/octet-stream';
328
+
329
+ try {
330
+ const content = await fs.readFile(result.filePath);
331
+ res.writeHead(200, {
332
+ ...BASE_SECURITY_HEADERS,
333
+ 'Content-Type': contentType,
334
+ 'Content-Length': content.byteLength,
335
+ });
336
+ if (req.method === 'HEAD') {
337
+ res.end();
338
+ } else {
339
+ res.end(content);
340
+ }
341
+ } catch {
342
+ sendError(res, 500, 'Internal Server Error');
343
+ }
344
+ });
345
+
346
+ await new Promise((resolve, reject) => {
347
+ server.once('error', reject);
348
+ server.listen(port, HOST, () => {
349
+ server.off('error', reject);
350
+ resolve();
351
+ });
352
+ });
353
+
354
+ console.log(`Serving ${label} at http://${HOST}:${port}`);
355
+
356
+ let closed = false;
357
+ const close = () => {
358
+ if (closed) return;
359
+ closed = true;
360
+ demoWatcher.close();
361
+ server.closeAllConnections?.();
362
+ server.close(() => process.exit(0));
363
+ };
364
+
365
+ process.on('SIGINT', close);
366
+ process.on('SIGTERM', close);
367
+
368
+ return { server, close };
369
+ }