@kubohiroya/turbowarp-http-server 0.1.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.
Files changed (63) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +346 -0
  3. package/README.md +874 -0
  4. package/dist/auth/digest-file.d.ts +17 -0
  5. package/dist/auth/digest-file.js +90 -0
  6. package/dist/auth/digest-file.js.map +1 -0
  7. package/dist/auth/digest.d.ts +23 -0
  8. package/dist/auth/digest.js +139 -0
  9. package/dist/auth/digest.js.map +1 -0
  10. package/dist/cli.d.ts +1 -0
  11. package/dist/cli.js +156 -0
  12. package/dist/cli.js.map +1 -0
  13. package/dist/community.d.ts +81 -0
  14. package/dist/community.js +689 -0
  15. package/dist/community.js.map +1 -0
  16. package/dist/digest-cli.d.ts +1 -0
  17. package/dist/digest-cli.js +159 -0
  18. package/dist/digest-cli.js.map +1 -0
  19. package/dist/extension-manifest.json +441 -0
  20. package/dist/protocol.d.ts +59 -0
  21. package/dist/protocol.js +71 -0
  22. package/dist/protocol.js.map +1 -0
  23. package/dist/server.d.ts +89 -0
  24. package/dist/server.js +650 -0
  25. package/dist/server.js.map +1 -0
  26. package/dist/turbowarp-http-server.js +1110 -0
  27. package/docs/deployment-targets.ja.md +274 -0
  28. package/docs/turbowarp-http-server.architecture.html +15149 -0
  29. package/docs/turbowarp-http-server.architecture.json +1014 -0
  30. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.dark.png +0 -0
  31. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.light.png +0 -0
  32. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.dark.png +0 -0
  33. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.light.png +0 -0
  34. package/docs/turbowarp-http-server.architecture.visual-check.html +32 -0
  35. package/docs/turbowarp-http-server.architecture.visual-check.json +547 -0
  36. package/examples/01-hello-form/README.ja.md +46 -0
  37. package/examples/01-hello-form/server.mjs +59 -0
  38. package/examples/02-visitor-counter/README.ja.md +39 -0
  39. package/examples/02-visitor-counter/server.mjs +44 -0
  40. package/examples/03-message-board/README.ja.md +47 -0
  41. package/examples/03-message-board/server.mjs +72 -0
  42. package/examples/04-image-upload/README.ja.md +46 -0
  43. package/examples/04-image-upload/server.mjs +149 -0
  44. package/examples/05-live-camera/README.ja.md +47 -0
  45. package/examples/05-live-camera/server.mjs +147 -0
  46. package/examples/06-scratch-like-community/README.ja.md +82 -0
  47. package/examples/06-scratch-like-community/server.mjs +17 -0
  48. package/examples/README.ja.md +20 -0
  49. package/package.json +75 -0
  50. package/schemas/extension-manifest.schema.json +49 -0
  51. package/src/auth/digest-file.ts +115 -0
  52. package/src/auth/digest.ts +170 -0
  53. package/src/block-definitions.json +417 -0
  54. package/src/cli.ts +172 -0
  55. package/src/community.ts +815 -0
  56. package/src/config.ts +12 -0
  57. package/src/digest-cli.ts +178 -0
  58. package/src/extension-manifest.ts +149 -0
  59. package/src/extension.ts +713 -0
  60. package/src/globals.d.ts +30 -0
  61. package/src/index.ts +8 -0
  62. package/src/protocol.ts +132 -0
  63. package/src/server.ts +880 -0
@@ -0,0 +1,689 @@
1
+ import { randomBytes, scrypt as scryptCallback, timingSafeEqual } from 'node:crypto';
2
+ import { promisify } from 'node:util';
3
+ import { Hono } from 'hono';
4
+ const scrypt = promisify(scryptCallback);
5
+ const SESSION_COOKIE = 'tw_community_session';
6
+ const DEFAULT_SESSION_MAX_AGE_SECONDS = 60 * 60 * 8;
7
+ const DEFAULT_MAX_SB3_BYTES = 10 * 1024 * 1024;
8
+ const DEFAULT_MAX_IMAGE_BYTES = 2 * 1024 * 1024;
9
+ const DEFAULT_MAX_UPLOAD_FORM_OVERHEAD_BYTES = 64 * 1024;
10
+ const PASSWORD_HASH_PREFIX = 'scrypt';
11
+ const SB3_MIME_TYPES = new Set([
12
+ 'application/octet-stream',
13
+ 'application/x.scratch.sb3',
14
+ 'application/zip',
15
+ 'application/x-zip-compressed'
16
+ ]);
17
+ const IMAGE_MIME_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
18
+ export function createCommunityApp(options = {}) {
19
+ const storage = options.storage ?? new InMemoryCommunityStorage();
20
+ const maxSb3Bytes = options.maxSb3Bytes ?? DEFAULT_MAX_SB3_BYTES;
21
+ const maxImageBytes = options.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES;
22
+ const oauthProviders = options.oauthProviders ?? readOAuthProvidersFromEnv(process.env);
23
+ const app = new Hono();
24
+ app.get('/', async (c) => {
25
+ const session = await ensureSession(c, storage);
26
+ const user = await readCurrentUser(storage, session);
27
+ const projects = await storage.listProjects();
28
+ return html(c, renderLayout('Community Projects', renderProjectList(projects, user, session.csrfToken)));
29
+ });
30
+ app.get('/signup', async (c) => {
31
+ const session = await ensureSession(c, storage);
32
+ return html(c, renderLayout('Sign up', renderSignupForm(session.csrfToken)));
33
+ });
34
+ app.post('/signup', async (c) => {
35
+ const session = await ensureSession(c, storage);
36
+ const form = await c.req.parseBody();
37
+ if (!verifyCsrf(form, session))
38
+ return forbidden(c, 'CSRF token mismatch.');
39
+ const username = readTextField(form, 'username').trim();
40
+ const password = readTextField(form, 'password');
41
+ if (!isValidUsername(username) || password.length < 8) {
42
+ return html(c, renderLayout('Sign up', renderSignupForm(session.csrfToken, 'Use a username and an 8+ character password.')), 400);
43
+ }
44
+ if (await storage.findUserByUsername(username)) {
45
+ return html(c, renderLayout('Sign up', renderSignupForm(session.csrfToken, 'That username is already taken.')), 409);
46
+ }
47
+ const user = await storage.createUser({
48
+ username,
49
+ passwordHash: await hashPassword(password)
50
+ });
51
+ await setSessionUser(storage, session, user.id);
52
+ return redirect(c, '/');
53
+ });
54
+ app.get('/login', async (c) => {
55
+ const session = await ensureSession(c, storage);
56
+ return html(c, renderLayout('Log in', renderLoginForm(session.csrfToken)));
57
+ });
58
+ app.post('/login', async (c) => {
59
+ const session = await ensureSession(c, storage);
60
+ const form = await c.req.parseBody();
61
+ if (!verifyCsrf(form, session))
62
+ return forbidden(c, 'CSRF token mismatch.');
63
+ const username = readTextField(form, 'username').trim();
64
+ const password = readTextField(form, 'password');
65
+ const user = await storage.findUserByUsername(username);
66
+ if (!user?.passwordHash || !(await verifyPassword(password, user.passwordHash))) {
67
+ return html(c, renderLayout('Log in', renderLoginForm(session.csrfToken, 'Invalid username or password.')), 401);
68
+ }
69
+ await setSessionUser(storage, session, user.id);
70
+ return redirect(c, '/');
71
+ });
72
+ app.post('/logout', async (c) => {
73
+ const session = await ensureSession(c, storage);
74
+ const form = await c.req.parseBody();
75
+ if (!verifyCsrf(form, session))
76
+ return forbidden(c, 'CSRF token mismatch.');
77
+ await storage.deleteSession(session.id);
78
+ clearSessionCookie(c);
79
+ return redirect(c, '/login');
80
+ });
81
+ app.get('/auth/:provider/start', async (c) => {
82
+ const providerName = c.req.param('provider');
83
+ const provider = oauthProviders[providerName];
84
+ if (!provider)
85
+ return c.json({ error: 'oauth_provider_disabled' }, 404);
86
+ const session = await ensureSession(c, storage);
87
+ const state = randomToken();
88
+ session.oauthState = state;
89
+ session.oauthProvider = providerName;
90
+ await storage.saveSession(session);
91
+ const authorizationUrl = new URL(provider.authorizationUrl);
92
+ authorizationUrl.searchParams.set('response_type', 'code');
93
+ authorizationUrl.searchParams.set('client_id', provider.clientId);
94
+ authorizationUrl.searchParams.set('state', state);
95
+ authorizationUrl.searchParams.set('redirect_uri', provider.redirectUri ?? new URL(`/auth/${providerName}/callback`, c.req.url).toString());
96
+ if (provider.scope)
97
+ authorizationUrl.searchParams.set('scope', provider.scope);
98
+ return redirect(c, authorizationUrl.toString());
99
+ });
100
+ app.get('/auth/:provider/callback', async (c) => {
101
+ const providerName = c.req.param('provider');
102
+ const provider = oauthProviders[providerName];
103
+ if (!provider)
104
+ return c.json({ error: 'oauth_provider_disabled' }, 404);
105
+ const session = await ensureSession(c, storage);
106
+ if (session.oauthProvider !== providerName || c.req.query('state') !== session.oauthState) {
107
+ return forbidden(c, 'OAuth state mismatch.');
108
+ }
109
+ const subject = c.req.query('subject') ?? c.req.query('user') ?? c.req.query('code');
110
+ if (!subject)
111
+ return c.json({ error: 'oauth_subject_required' }, 400);
112
+ const existing = await storage.findUserByOAuth(providerName, subject);
113
+ const user = existing ??
114
+ (await storage.createUser({
115
+ username: uniqueOAuthUsername(providerName, subject),
116
+ oauthProvider: providerName,
117
+ oauthSubject: subject
118
+ }));
119
+ session.oauthProvider = undefined;
120
+ session.oauthState = undefined;
121
+ await setSessionUser(storage, session, user.id);
122
+ return redirect(c, '/');
123
+ });
124
+ app.post('/projects', async (c) => {
125
+ const session = await ensureSession(c, storage);
126
+ const user = await requireUser(c, storage, session);
127
+ if (!user)
128
+ return c.json({ error: 'login_required' }, 401);
129
+ const form = await readMultipartFormWithLimit(c.req.raw, maxSb3Bytes + maxImageBytes + DEFAULT_MAX_UPLOAD_FORM_OVERHEAD_BYTES);
130
+ if (!form.ok)
131
+ return c.json({ error: form.error }, form.status);
132
+ if (!verifyCsrf(form.fields, session))
133
+ return forbidden(c, 'CSRF token mismatch.');
134
+ const sb3File = readFileField(form.fields, 'sb3');
135
+ const sb3Validation = await validateSb3File(sb3File, maxSb3Bytes);
136
+ if (!sb3Validation.ok)
137
+ return c.json({ error: sb3Validation.error }, sb3Validation.status);
138
+ const thumbnailFile = readFileField(form.fields, 'thumbnail');
139
+ const thumbnailValidation = await validateOptionalImageFile(thumbnailFile, maxImageBytes);
140
+ if (!thumbnailValidation.ok)
141
+ return c.json({ error: thumbnailValidation.error }, thumbnailValidation.status);
142
+ const project = await storage.createProject({
143
+ ownerId: user.id,
144
+ title: sanitizeTitle(readTextField(form.fields, 'title')),
145
+ description: readTextField(form.fields, 'description').slice(0, 2000),
146
+ sb3Bytes: sb3Validation.bytes,
147
+ sb3FileName: sb3Validation.fileName,
148
+ sb3MimeType: sb3Validation.mimeType,
149
+ ...thumbnailValidation.thumbnail
150
+ });
151
+ return redirect(c, `/projects/${project.id}`, 303);
152
+ });
153
+ app.get('/projects/:downloadId{[A-Za-z0-9_-]+\\.sb3}', async (c) => {
154
+ const projectId = c.req.param('downloadId').slice(0, -'.sb3'.length);
155
+ const project = await storage.findProjectById(projectId);
156
+ if (!project)
157
+ return c.json({ error: 'not_found' }, 404);
158
+ return new Response(toArrayBuffer(project.sb3Bytes), {
159
+ status: 200,
160
+ headers: {
161
+ 'Content-Type': project.sb3MimeType,
162
+ 'Content-Length': String(project.sb3Bytes.byteLength),
163
+ 'Content-Disposition': `attachment; filename="${escapeHeaderFileName(project.sb3FileName)}"`,
164
+ 'Cache-Control': 'no-store'
165
+ }
166
+ });
167
+ });
168
+ app.get('/projects/:id', async (c) => {
169
+ const session = await ensureSession(c, storage);
170
+ const user = await readCurrentUser(storage, session);
171
+ const project = await storage.findProjectById(c.req.param('id'));
172
+ if (!project)
173
+ return c.json({ error: 'not_found' }, 404);
174
+ return html(c, renderLayout(project.title, renderProjectDetail(project, user, session.csrfToken)));
175
+ });
176
+ app.post('/projects/:id/remix', async (c) => {
177
+ const session = await ensureSession(c, storage);
178
+ const user = await requireUser(c, storage, session);
179
+ if (!user)
180
+ return c.json({ error: 'login_required' }, 401);
181
+ const form = await c.req.parseBody();
182
+ if (!verifyCsrf(form, session))
183
+ return forbidden(c, 'CSRF token mismatch.');
184
+ const original = await storage.findProjectById(c.req.param('id'));
185
+ if (!original)
186
+ return c.json({ error: 'not_found' }, 404);
187
+ const remixInput = {
188
+ ownerId: user.id,
189
+ title: sanitizeTitle(readTextField(form, 'title') || `${original.title} remix`),
190
+ description: readTextField(form, 'description') || `Remix of ${original.title}`,
191
+ sb3Bytes: original.sb3Bytes.slice(),
192
+ sb3FileName: original.sb3FileName,
193
+ sb3MimeType: original.sb3MimeType,
194
+ remixOfProjectId: original.id
195
+ };
196
+ if (original.thumbnailBytes)
197
+ remixInput.thumbnailBytes = original.thumbnailBytes.slice();
198
+ if (original.thumbnailFileName)
199
+ remixInput.thumbnailFileName = original.thumbnailFileName;
200
+ if (original.thumbnailMimeType)
201
+ remixInput.thumbnailMimeType = original.thumbnailMimeType;
202
+ const project = await storage.createProject(remixInput);
203
+ return redirect(c, `/projects/${project.id}`, 303);
204
+ });
205
+ app.post('/projects/:id/update', async (c) => {
206
+ const session = await ensureSession(c, storage);
207
+ const user = await requireUser(c, storage, session);
208
+ if (!user)
209
+ return c.json({ error: 'login_required' }, 401);
210
+ const form = await c.req.parseBody();
211
+ if (!verifyCsrf(form, session))
212
+ return forbidden(c, 'CSRF token mismatch.');
213
+ const project = await storage.findProjectById(c.req.param('id'));
214
+ if (!project)
215
+ return c.json({ error: 'not_found' }, 404);
216
+ if (project.ownerId !== user.id)
217
+ return forbidden(c, 'Only the project owner can edit this project.');
218
+ project.title = sanitizeTitle(readTextField(form, 'title'));
219
+ project.description = readTextField(form, 'description').slice(0, 2000);
220
+ await storage.saveProject(project);
221
+ return redirect(c, `/projects/${project.id}`, 303);
222
+ });
223
+ app.post('/projects/:id/replace', async (c) => {
224
+ const session = await ensureSession(c, storage);
225
+ const user = await requireUser(c, storage, session);
226
+ if (!user)
227
+ return c.json({ error: 'login_required' }, 401);
228
+ const form = await readMultipartFormWithLimit(c.req.raw, maxSb3Bytes + maxImageBytes + DEFAULT_MAX_UPLOAD_FORM_OVERHEAD_BYTES);
229
+ if (!form.ok)
230
+ return c.json({ error: form.error }, form.status);
231
+ if (!verifyCsrf(form.fields, session))
232
+ return forbidden(c, 'CSRF token mismatch.');
233
+ const project = await storage.findProjectById(c.req.param('id'));
234
+ if (!project)
235
+ return c.json({ error: 'not_found' }, 404);
236
+ if (project.ownerId !== user.id)
237
+ return forbidden(c, 'Only the project owner can replace this project.');
238
+ const sb3File = readFileField(form.fields, 'sb3');
239
+ const sb3Validation = await validateSb3File(sb3File, maxSb3Bytes);
240
+ if (!sb3Validation.ok)
241
+ return c.json({ error: sb3Validation.error }, sb3Validation.status);
242
+ const thumbnailFile = readFileField(form.fields, 'thumbnail');
243
+ const thumbnailValidation = await validateOptionalImageFile(thumbnailFile, maxImageBytes);
244
+ if (!thumbnailValidation.ok)
245
+ return c.json({ error: thumbnailValidation.error }, thumbnailValidation.status);
246
+ project.sb3Bytes = sb3Validation.bytes;
247
+ project.sb3FileName = sb3Validation.fileName;
248
+ project.sb3MimeType = sb3Validation.mimeType;
249
+ const thumbnail = thumbnailValidation.thumbnail;
250
+ if (thumbnail.thumbnailBytes && thumbnail.thumbnailFileName && thumbnail.thumbnailMimeType) {
251
+ project.thumbnailBytes = thumbnail.thumbnailBytes;
252
+ project.thumbnailFileName = thumbnail.thumbnailFileName;
253
+ project.thumbnailMimeType = thumbnail.thumbnailMimeType;
254
+ }
255
+ await storage.saveProject(project);
256
+ return redirect(c, `/projects/${project.id}`, 303);
257
+ });
258
+ app.post('/projects/:id/delete', async (c) => {
259
+ const session = await ensureSession(c, storage);
260
+ const user = await requireUser(c, storage, session);
261
+ if (!user)
262
+ return c.json({ error: 'login_required' }, 401);
263
+ const form = await c.req.parseBody();
264
+ if (!verifyCsrf(form, session))
265
+ return forbidden(c, 'CSRF token mismatch.');
266
+ const project = await storage.findProjectById(c.req.param('id'));
267
+ if (!project)
268
+ return c.json({ error: 'not_found' }, 404);
269
+ if (project.ownerId !== user.id)
270
+ return forbidden(c, 'Only the project owner can delete this project.');
271
+ await storage.deleteProject(project.id);
272
+ return redirect(c, '/', 303);
273
+ });
274
+ return app;
275
+ }
276
+ export class InMemoryCommunityStorage {
277
+ constructor() {
278
+ this.userSequence = 1;
279
+ this.projectSequence = 1;
280
+ this.users = new Map();
281
+ this.sessions = new Map();
282
+ this.projects = new Map();
283
+ }
284
+ async createUser(input) {
285
+ const user = {
286
+ ...input,
287
+ id: `user-${this.userSequence}`,
288
+ createdAt: new Date().toISOString()
289
+ };
290
+ this.userSequence += 1;
291
+ this.users.set(user.id, user);
292
+ return user;
293
+ }
294
+ async findUserByUsername(username) {
295
+ return Array.from(this.users.values()).find((user) => user.username === username) ?? null;
296
+ }
297
+ async findUserById(id) {
298
+ return this.users.get(id) ?? null;
299
+ }
300
+ async findUserByOAuth(provider, subject) {
301
+ return (Array.from(this.users.values()).find((user) => user.oauthProvider === provider && user.oauthSubject === subject) ?? null);
302
+ }
303
+ async createSession(input) {
304
+ const session = {
305
+ ...input,
306
+ id: randomToken()
307
+ };
308
+ this.sessions.set(session.id, session);
309
+ return session;
310
+ }
311
+ async getSession(id) {
312
+ const session = this.sessions.get(id);
313
+ if (!session)
314
+ return null;
315
+ if (session.expiresAt <= Date.now()) {
316
+ this.sessions.delete(id);
317
+ return null;
318
+ }
319
+ return session;
320
+ }
321
+ async saveSession(session) {
322
+ this.sessions.set(session.id, session);
323
+ }
324
+ async deleteSession(id) {
325
+ this.sessions.delete(id);
326
+ }
327
+ async createProject(input) {
328
+ const now = new Date().toISOString();
329
+ const project = {
330
+ ...input,
331
+ id: `project-${this.projectSequence}`,
332
+ createdAt: now,
333
+ updatedAt: now
334
+ };
335
+ this.projectSequence += 1;
336
+ this.projects.set(project.id, project);
337
+ return project;
338
+ }
339
+ async findProjectById(id) {
340
+ return this.projects.get(id) ?? null;
341
+ }
342
+ async listProjects() {
343
+ return Array.from(this.projects.values()).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
344
+ }
345
+ async saveProject(project) {
346
+ this.projects.set(project.id, { ...project, updatedAt: new Date().toISOString() });
347
+ }
348
+ async deleteProject(id) {
349
+ return this.projects.delete(id);
350
+ }
351
+ }
352
+ export function readOAuthProvidersFromEnv(env) {
353
+ const providers = {};
354
+ for (const [name, value] of Object.entries(env)) {
355
+ const match = /^COMMUNITY_OAUTH_([A-Z0-9_]+)_CLIENT_ID$/.exec(name);
356
+ if (!match || !value)
357
+ continue;
358
+ const providerKey = match[1]?.toLowerCase().replace(/_/g, '-');
359
+ if (!providerKey)
360
+ continue;
361
+ const envPrefix = `COMMUNITY_OAUTH_${match[1]}`;
362
+ const authorizationUrl = env[`${envPrefix}_AUTHORIZATION_URL`];
363
+ if (!authorizationUrl)
364
+ continue;
365
+ const config = {
366
+ clientId: value,
367
+ authorizationUrl
368
+ };
369
+ const redirectUri = env[`${envPrefix}_REDIRECT_URI`];
370
+ const scope = env[`${envPrefix}_SCOPE`];
371
+ if (redirectUri)
372
+ config.redirectUri = redirectUri;
373
+ if (scope)
374
+ config.scope = scope;
375
+ providers[providerKey] = config;
376
+ }
377
+ return providers;
378
+ }
379
+ async function ensureSession(c, storage) {
380
+ const sessionId = readCookie(c.req.header('Cookie') ?? '', SESSION_COOKIE);
381
+ const existing = sessionId ? await storage.getSession(sessionId) : null;
382
+ if (existing)
383
+ return existing;
384
+ const session = await storage.createSession({
385
+ csrfToken: randomToken(),
386
+ expiresAt: Date.now() + DEFAULT_SESSION_MAX_AGE_SECONDS * 1000
387
+ });
388
+ setSessionCookie(c, session.id);
389
+ return session;
390
+ }
391
+ async function setSessionUser(storage, session, userId) {
392
+ session.userId = userId;
393
+ session.csrfToken = randomToken();
394
+ session.expiresAt = Date.now() + DEFAULT_SESSION_MAX_AGE_SECONDS * 1000;
395
+ await storage.saveSession(session);
396
+ }
397
+ async function readCurrentUser(storage, session) {
398
+ return session.userId ? storage.findUserById(session.userId) : null;
399
+ }
400
+ async function requireUser(c, storage, session) {
401
+ const user = await readCurrentUser(storage, session);
402
+ if (!user)
403
+ clearSessionCookie(c);
404
+ return user;
405
+ }
406
+ async function hashPassword(password) {
407
+ const salt = randomToken();
408
+ const derived = (await scrypt(password, salt, 64));
409
+ return `${PASSWORD_HASH_PREFIX}:${salt}:${derived.toString('base64url')}`;
410
+ }
411
+ async function verifyPassword(password, storedHash) {
412
+ const [prefix, salt, expected] = storedHash.split(':');
413
+ if (prefix !== PASSWORD_HASH_PREFIX || !salt || !expected)
414
+ return false;
415
+ const actual = (await scrypt(password, salt, 64));
416
+ const expectedBuffer = Buffer.from(expected, 'base64url');
417
+ return actual.byteLength === expectedBuffer.byteLength && timingSafeEqual(actual, expectedBuffer);
418
+ }
419
+ function verifyCsrf(form, session) {
420
+ return readTextField(form, 'csrf') === session.csrfToken;
421
+ }
422
+ function readTextField(form, name) {
423
+ const value = form[name];
424
+ return typeof value === 'string' ? value : '';
425
+ }
426
+ function readFileField(form, name) {
427
+ const value = form[name];
428
+ return typeof value === 'object' && value instanceof File ? value : null;
429
+ }
430
+ async function readMultipartFormWithLimit(request, maxBytes) {
431
+ const contentType = request.headers.get('content-type') ?? '';
432
+ if (!contentType.toLowerCase().startsWith('multipart/form-data')) {
433
+ return { ok: false, error: 'multipart_required', status: 415 };
434
+ }
435
+ const contentLength = parseContentLength(request.headers.get('content-length'));
436
+ if (contentLength !== null && contentLength > maxBytes) {
437
+ return { ok: false, error: 'upload_body_too_large', status: 413 };
438
+ }
439
+ const body = await readBodyWithLimit(request, maxBytes);
440
+ if (!body)
441
+ return { ok: false, error: 'upload_body_too_large', status: 413 };
442
+ let formData;
443
+ try {
444
+ formData = await new Response(body, {
445
+ headers: { 'Content-Type': contentType }
446
+ }).formData();
447
+ }
448
+ catch {
449
+ return { ok: false, error: 'multipart_invalid', status: 400 };
450
+ }
451
+ return { ok: true, fields: Object.fromEntries(formData.entries()) };
452
+ }
453
+ async function readBodyWithLimit(request, maxBytes) {
454
+ if (!request.body)
455
+ return new ArrayBuffer(0);
456
+ const reader = request.body.getReader();
457
+ const chunks = [];
458
+ let byteLength = 0;
459
+ try {
460
+ for (;;) {
461
+ const result = await reader.read();
462
+ if (result.done)
463
+ break;
464
+ byteLength += result.value.byteLength;
465
+ if (byteLength > maxBytes) {
466
+ await reader.cancel();
467
+ return null;
468
+ }
469
+ chunks.push(result.value);
470
+ }
471
+ }
472
+ finally {
473
+ reader.releaseLock();
474
+ }
475
+ const body = new Uint8Array(byteLength);
476
+ let offset = 0;
477
+ for (const chunk of chunks) {
478
+ body.set(chunk, offset);
479
+ offset += chunk.byteLength;
480
+ }
481
+ return toArrayBuffer(body);
482
+ }
483
+ function parseContentLength(value) {
484
+ if (value === null)
485
+ return null;
486
+ const length = Number.parseInt(value, 10);
487
+ return Number.isSafeInteger(length) && length >= 0 ? length : null;
488
+ }
489
+ async function validateSb3File(file, maxBytes) {
490
+ if (!file)
491
+ return { ok: false, error: 'sb3_required', status: 400 };
492
+ if (file.size > maxBytes)
493
+ return { ok: false, error: 'sb3_too_large', status: 413 };
494
+ if (!file.name.toLowerCase().endsWith('.sb3'))
495
+ return { ok: false, error: 'sb3_extension_required', status: 415 };
496
+ if (!SB3_MIME_TYPES.has(normalizeMimeType(file.type)))
497
+ return { ok: false, error: 'sb3_mime_type_rejected', status: 415 };
498
+ const bytes = new Uint8Array(await file.arrayBuffer());
499
+ if (!hasZipSignature(bytes))
500
+ return { ok: false, error: 'sb3_zip_signature_required', status: 415 };
501
+ return { ok: true, bytes, fileName: file.name, mimeType: normalizeMimeType(file.type) };
502
+ }
503
+ async function validateOptionalImageFile(file, maxBytes) {
504
+ if (!file || file.size === 0)
505
+ return { ok: true, thumbnail: {} };
506
+ if (file.size > maxBytes)
507
+ return { ok: false, error: 'thumbnail_too_large', status: 413 };
508
+ const mimeType = normalizeMimeType(file.type);
509
+ if (!IMAGE_MIME_TYPES.has(mimeType))
510
+ return { ok: false, error: 'thumbnail_mime_type_rejected', status: 415 };
511
+ const bytes = new Uint8Array(await file.arrayBuffer());
512
+ if (!matchesImageSignature(bytes, mimeType))
513
+ return { ok: false, error: 'thumbnail_signature_rejected', status: 415 };
514
+ return {
515
+ ok: true,
516
+ thumbnail: {
517
+ thumbnailBytes: bytes,
518
+ thumbnailFileName: file.name,
519
+ thumbnailMimeType: mimeType
520
+ }
521
+ };
522
+ }
523
+ function hasZipSignature(bytes) {
524
+ return bytes[0] === 0x50 && bytes[1] === 0x4b && [0x03, 0x05, 0x07].includes(bytes[2] ?? -1) && bytes[3] !== undefined;
525
+ }
526
+ function matchesImageSignature(bytes, mimeType) {
527
+ if (mimeType === 'image/png') {
528
+ return bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47;
529
+ }
530
+ if (mimeType === 'image/jpeg')
531
+ return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
532
+ if (mimeType === 'image/gif') {
533
+ return bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46;
534
+ }
535
+ if (mimeType === 'image/webp') {
536
+ return bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46;
537
+ }
538
+ return false;
539
+ }
540
+ function normalizeMimeType(value) {
541
+ return value.split(';', 1)[0]?.trim().toLowerCase() || 'application/octet-stream';
542
+ }
543
+ function sanitizeTitle(value) {
544
+ const trimmed = value.trim();
545
+ return trimmed ? trimmed.slice(0, 120) : 'Untitled project';
546
+ }
547
+ function isValidUsername(value) {
548
+ return /^[A-Za-z0-9_-]{3,32}$/.test(value);
549
+ }
550
+ function uniqueOAuthUsername(provider, subject) {
551
+ return `${provider}-${subject}`.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 32) || `${provider}-user`;
552
+ }
553
+ function html(c, body, status = 200) {
554
+ return c.html(body, status);
555
+ }
556
+ function forbidden(c, message) {
557
+ return c.json({ error: 'forbidden', message }, 403);
558
+ }
559
+ function redirect(c, location, status = 302) {
560
+ return c.redirect(location, status);
561
+ }
562
+ function setSessionCookie(c, sessionId) {
563
+ c.header('Set-Cookie', `${SESSION_COOKIE}=${encodeURIComponent(sessionId)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${DEFAULT_SESSION_MAX_AGE_SECONDS}`);
564
+ }
565
+ function clearSessionCookie(c) {
566
+ c.header('Set-Cookie', `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
567
+ }
568
+ function readCookie(cookieHeader, name) {
569
+ for (const part of cookieHeader.split(';')) {
570
+ const [rawName, ...rawValue] = part.trim().split('=');
571
+ if (rawName === name)
572
+ return decodeURIComponent(rawValue.join('='));
573
+ }
574
+ return null;
575
+ }
576
+ function randomToken() {
577
+ return randomBytes(32).toString('base64url');
578
+ }
579
+ function toArrayBuffer(bytes) {
580
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
581
+ }
582
+ function escapeHtml(value) {
583
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
584
+ }
585
+ function escapeHeaderFileName(value) {
586
+ return value.replace(/\\/g, '_').replace(/"/g, '_').replace(/\r/g, '_').replace(/\n/g, '_');
587
+ }
588
+ function renderLayout(title, body) {
589
+ return `<!doctype html>
590
+ <html lang="en">
591
+ <head>
592
+ <meta charset="utf-8">
593
+ <meta name="viewport" content="width=device-width, initial-scale=1">
594
+ <title>${escapeHtml(title)}</title>
595
+ <style>
596
+ body { font-family: system-ui, sans-serif; line-height: 1.5; margin: 2rem auto; max-width: 880px; padding: 0 1rem; }
597
+ header, article, form { margin-bottom: 1.5rem; }
598
+ label { display: block; margin: 0.75rem 0; }
599
+ input, textarea { box-sizing: border-box; display: block; max-width: 32rem; padding: 0.45rem; width: 100%; }
600
+ button, a.button { display: inline-block; margin-right: 0.5rem; padding: 0.45rem 0.75rem; }
601
+ article { border: 1px solid #ddd; border-radius: 6px; padding: 1rem; }
602
+ .error { color: #9f1239; }
603
+ </style>
604
+ </head>
605
+ <body>
606
+ <header><h1>${escapeHtml(title)}</h1><nav><a href="/">Projects</a> <a href="/signup">Sign up</a> <a href="/login">Log in</a></nav></header>
607
+ ${body}
608
+ </body>
609
+ </html>`;
610
+ }
611
+ function renderProjectList(projects, user, csrfToken) {
612
+ const form = user
613
+ ? `<section>
614
+ <h2>Share a project</h2>
615
+ <form action="/projects" method="post" enctype="multipart/form-data">
616
+ <input type="hidden" name="csrf" value="${escapeHtml(csrfToken)}">
617
+ <label>Title <input name="title" required></label>
618
+ <label>Description <textarea name="description"></textarea></label>
619
+ <label>SB3 file <input name="sb3" type="file" accept=".sb3,application/x.scratch.sb3,application/zip" required></label>
620
+ <label>Thumbnail <input name="thumbnail" type="file" accept="image/png,image/jpeg,image/gif,image/webp"></label>
621
+ <button type="submit">Publish</button>
622
+ </form>
623
+ </section>`
624
+ : '<p><a href="/login">Log in</a> to share a project.</p>';
625
+ const items = projects.length === 0
626
+ ? '<p>No projects yet.</p>'
627
+ : projects
628
+ .map((project) => `<article>
629
+ <h2><a href="/projects/${escapeHtml(project.id)}">${escapeHtml(project.title)}</a></h2>
630
+ <p>${escapeHtml(project.description)}</p>
631
+ ${project.remixOfProjectId ? `<p>Remix of <a href="/projects/${escapeHtml(project.remixOfProjectId)}">${escapeHtml(project.remixOfProjectId)}</a></p>` : ''}
632
+ </article>`)
633
+ .join('');
634
+ return `${form}<section>${items}</section>`;
635
+ }
636
+ function renderSignupForm(csrfToken, error = '') {
637
+ return `<form action="/signup" method="post">
638
+ ${error ? `<p class="error">${escapeHtml(error)}</p>` : ''}
639
+ <input type="hidden" name="csrf" value="${escapeHtml(csrfToken)}">
640
+ <label>Username <input name="username" autocomplete="username" required></label>
641
+ <label>Password <input name="password" type="password" autocomplete="new-password" required></label>
642
+ <button type="submit">Create account</button>
643
+ </form>`;
644
+ }
645
+ function renderLoginForm(csrfToken, error = '') {
646
+ return `<form action="/login" method="post">
647
+ ${error ? `<p class="error">${escapeHtml(error)}</p>` : ''}
648
+ <input type="hidden" name="csrf" value="${escapeHtml(csrfToken)}">
649
+ <label>Username <input name="username" autocomplete="username" required></label>
650
+ <label>Password <input name="password" type="password" autocomplete="current-password" required></label>
651
+ <button type="submit">Log in</button>
652
+ </form>
653
+ <p><a href="/auth/demo/start">Try configured OAuth demo provider</a></p>`;
654
+ }
655
+ function renderProjectDetail(project, user, csrfToken) {
656
+ const ownerControls = user?.id === project.ownerId
657
+ ? `<form action="/projects/${escapeHtml(project.id)}/update" method="post">
658
+ <input type="hidden" name="csrf" value="${escapeHtml(csrfToken)}">
659
+ <label>Title <input name="title" value="${escapeHtml(project.title)}" required></label>
660
+ <label>Description <textarea name="description">${escapeHtml(project.description)}</textarea></label>
661
+ <button type="submit">Save</button>
662
+ </form>
663
+ <form action="/projects/${escapeHtml(project.id)}/replace" method="post" enctype="multipart/form-data">
664
+ <input type="hidden" name="csrf" value="${escapeHtml(csrfToken)}">
665
+ <label>SB3 file <input name="sb3" type="file" accept=".sb3,application/x.scratch.sb3,application/zip" required></label>
666
+ <label>Thumbnail <input name="thumbnail" type="file" accept="image/png,image/jpeg,image/gif,image/webp"></label>
667
+ <button type="submit">Replace SB3</button>
668
+ </form>
669
+ <form action="/projects/${escapeHtml(project.id)}/delete" method="post">
670
+ <input type="hidden" name="csrf" value="${escapeHtml(csrfToken)}">
671
+ <button type="submit">Delete</button>
672
+ </form>`
673
+ : '';
674
+ const remixForm = user
675
+ ? `<form action="/projects/${escapeHtml(project.id)}/remix" method="post">
676
+ <input type="hidden" name="csrf" value="${escapeHtml(csrfToken)}">
677
+ <label>Remix title <input name="title" value="${escapeHtml(`${project.title} remix`)}"></label>
678
+ <button type="submit">Create remix</button>
679
+ </form>`
680
+ : '<p>Log in to remix this project.</p>';
681
+ return `<article>
682
+ <p>${escapeHtml(project.description)}</p>
683
+ ${project.remixOfProjectId ? `<p>Remix of <a href="/projects/${escapeHtml(project.remixOfProjectId)}">${escapeHtml(project.remixOfProjectId)}</a></p>` : ''}
684
+ <p><a href="/projects/${escapeHtml(project.id)}.sb3">Download SB3</a></p>
685
+ </article>
686
+ ${remixForm}
687
+ ${ownerControls}`;
688
+ }
689
+ //# sourceMappingURL=community.js.map