@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
package/src/server.ts ADDED
@@ -0,0 +1,880 @@
1
+ import {serve} from '@hono/node-server';
2
+ import {getConnInfo} from '@hono/node-server/conninfo';
3
+ import type {ServerType} from '@hono/node-server';
4
+ import {createServer as createHttpsServer} from 'node:https';
5
+ import type {ServerOptions as HttpsServerOptions} from 'node:https';
6
+ import {Hono} from 'hono';
7
+ import type {Context} from 'hono';
8
+ import {secureHeaders} from 'hono/secure-headers';
9
+ import type {WebSocket} from 'ws';
10
+ import {WebSocketServer} from 'ws';
11
+ import {DIGEST_AUTH_USER_HEADER, isLocalAddress, verifyDigestAuth} from './auth/digest.js';
12
+ import type {DigestAuthOptions} from './auth/digest.js';
13
+ import {createCommunityApp} from './community.js';
14
+ import type {CommunityServerOptions} from './community.js';
15
+ import {
16
+ HTTP_BRIDGE_PROTOCOL,
17
+ HTTP_BRIDGE_PROTOCOL_VERSION,
18
+ isBodyForbidden,
19
+ isForbiddenResponseHeader,
20
+ isValidHttpStatus,
21
+ normalizeHeaderName,
22
+ parseBridgeClientMessage,
23
+ validateHeaderName,
24
+ validateHeaderValue
25
+ } from './protocol.js';
26
+ import type {BridgeBody, BridgeRequestMessage, BridgeResponseMessage} from './protocol.js';
27
+
28
+ export interface ServerOptions {
29
+ hostname: string;
30
+ port: number;
31
+ resources?: ResourceCapability;
32
+ maxResourceBodyBytes?: number;
33
+ maxRequestBodyBytes?: number;
34
+ logger?: ResourceLogger;
35
+ authorizeResource?: ResourceAuthorizer;
36
+ digestAuth?: DigestAuthOptions;
37
+ tls?: HttpsServerOptions;
38
+ requestTimeoutMs?: number;
39
+ routes?: readonly string[];
40
+ community?: false | CommunityServerOptions;
41
+ }
42
+
43
+ export interface RunningServer {
44
+ hostname: string;
45
+ port: number;
46
+ close(): Promise<void>;
47
+ }
48
+
49
+ export interface ResourceSnapshot {
50
+ name: string;
51
+ mimeType: string;
52
+ bytes: Uint8Array;
53
+ byteLength?: number;
54
+ etag?: string;
55
+ replacementId?: string;
56
+ lastModified?: Date;
57
+ cacheControl?: string;
58
+ }
59
+
60
+ export interface ResourceMetadata {
61
+ name: string;
62
+ mimeType: string;
63
+ byteLength?: number;
64
+ etag?: string;
65
+ replacementId?: string;
66
+ lastModified?: Date;
67
+ cacheControl?: string;
68
+ }
69
+
70
+ export interface ResourceWriteRequest {
71
+ routeName: string;
72
+ resourceName: string;
73
+ mimeType: string;
74
+ bytes: Uint8Array;
75
+ }
76
+
77
+ export interface ResourceWriteResult {
78
+ created: boolean;
79
+ snapshot?: ResourceSnapshot;
80
+ }
81
+
82
+ export interface ResourceCapability {
83
+ isNamespacePublished?(routeName: string): boolean | Promise<boolean>;
84
+ getResource(routeName: string, resourceName: string): ResourceSnapshot | null | Promise<ResourceSnapshot | null>;
85
+ listResources?(routeName: string): readonly ResourceMetadata[] | Promise<readonly ResourceMetadata[]>;
86
+ putResource?(request: ResourceWriteRequest): ResourceWriteResult | Promise<ResourceWriteResult>;
87
+ deleteResource?(routeName: string, resourceName: string): boolean | Promise<boolean>;
88
+ isSupportedResourceType?(mimeType: string): boolean | Promise<boolean>;
89
+ }
90
+
91
+ export interface ResourceLogEvent {
92
+ event: 'resource.get' | 'resource.head' | 'resource.put' | 'resource.delete' | 'resource.list';
93
+ routeName: string;
94
+ resourceName?: string;
95
+ mimeType?: string;
96
+ byteLength?: number;
97
+ status: number;
98
+ }
99
+
100
+ export interface ResourceLogger {
101
+ info(event: ResourceLogEvent): void;
102
+ }
103
+
104
+ export type ResourceAuthorizer = (
105
+ request: Request,
106
+ operation: 'get' | 'head' | 'put' | 'delete' | 'list',
107
+ routeName: string,
108
+ resourceName?: string
109
+ ) => boolean | Promise<boolean>;
110
+
111
+ export interface ServerAppOptions {
112
+ resources?: ResourceCapability;
113
+ maxResourceBodyBytes?: number;
114
+ maxRequestBodyBytes?: number;
115
+ logger?: ResourceLogger;
116
+ authorizeResource?: ResourceAuthorizer;
117
+ digestAuth?: DigestAuthOptions;
118
+ bridge?: HttpRequestBridge;
119
+ routes?: readonly string[];
120
+ community?: false | CommunityServerOptions;
121
+ }
122
+
123
+ const DEFAULT_MAX_RESOURCE_BODY_BYTES = 10 * 1024 * 1024;
124
+ const DEFAULT_MAX_REQUEST_BODY_BYTES = 1024 * 1024;
125
+ const DEFAULT_REQUEST_TIMEOUT_MS = 5000;
126
+ const TEXT_BODY_TYPES = [
127
+ 'application/json',
128
+ 'application/x-www-form-urlencoded',
129
+ 'application/xml',
130
+ 'text/'
131
+ ];
132
+ const authenticatedUsers = new WeakMap<Request, string>();
133
+
134
+ export interface HttpRequestBridge {
135
+ forward(message: BridgeRequestMessage, method: string): Promise<Response>;
136
+ }
137
+
138
+ export function createApp(options: ServerAppOptions = {}): Hono {
139
+ const app = new Hono();
140
+
141
+ app.use('*', secureHeaders());
142
+
143
+ if (options.digestAuth) {
144
+ app.use('*', async (c, next) => {
145
+ const result = await verifyDigestAuth(c.req.raw, c.req.method, options.digestAuth!);
146
+ if (!result.ok) {
147
+ return c.json(
148
+ {
149
+ error: 'authentication_required',
150
+ message: 'HTTP Digest authentication is required.'
151
+ },
152
+ 401,
153
+ {'WWW-Authenticate': result.challenge ?? ''}
154
+ );
155
+ }
156
+ if (result.username) authenticatedUsers.set(c.req.raw, result.username);
157
+ await next();
158
+ });
159
+ }
160
+
161
+ if (options.community) {
162
+ app.route('/', createCommunityApp(options.community));
163
+ }
164
+
165
+ app.get('/health', (c) =>
166
+ c.json({
167
+ ok: true,
168
+ service: 'turbowarp-http-server'
169
+ })
170
+ );
171
+
172
+ app.get('/ws', (c) =>
173
+ c.json(
174
+ {
175
+ error: 'upgrade_required',
176
+ message: 'Connect to this endpoint with WebSocket.'
177
+ },
178
+ 426
179
+ )
180
+ );
181
+
182
+ app.all('*', async (c) => {
183
+ const resourceResponse = await handleResourceRequest(c, options);
184
+ if (resourceResponse) return resourceResponse;
185
+
186
+ if (options.bridge) {
187
+ const bridgeRequestOptions: BridgeRequestOptions = {
188
+ routes: options.routes ?? [],
189
+ maxBodyBytes: options.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY_BYTES,
190
+ clientAddress: readClientAddress(c)
191
+ };
192
+ const authenticatedUser = authenticatedUsers.get(c.req.raw);
193
+ if (authenticatedUser) bridgeRequestOptions.authenticatedUser = authenticatedUser;
194
+ return options.bridge.forward(
195
+ await createBridgeRequestMessage(c.req.raw, bridgeRequestOptions),
196
+ c.req.method
197
+ );
198
+ }
199
+
200
+ return c.json(
201
+ {
202
+ error: 'not_connected',
203
+ message: 'HTTP-to-TurboWarp request forwarding has not been implemented yet.'
204
+ },
205
+ 503
206
+ );
207
+ });
208
+
209
+ return app;
210
+ }
211
+
212
+ export function startServer(options: ServerOptions): RunningServer {
213
+ const bridge = new WebSocketHttpRequestBridge(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);
214
+ const app = createApp({...options, bridge});
215
+ const wss = new WebSocketServer({noServer: true});
216
+ const sockets = new Set<WebSocket>();
217
+ const server: ServerType = serve({
218
+ fetch: app.fetch,
219
+ hostname: options.hostname,
220
+ port: options.port,
221
+ ...(options.tls ? {createServer: createHttpsServer, serverOptions: options.tls} : {})
222
+ });
223
+
224
+ server.on('upgrade', (request, socket, head) => {
225
+ if (new URL(request.url ?? '/', 'http://127.0.0.1').pathname !== '/ws') {
226
+ socket.destroy();
227
+ return;
228
+ }
229
+ if (!isLocalAddress(socket.remoteAddress)) {
230
+ socket.destroy();
231
+ return;
232
+ }
233
+
234
+ wss.handleUpgrade(request, socket, head, (ws) => {
235
+ sockets.add(ws);
236
+ bridge.attach(ws);
237
+ ws.on('close', () => {
238
+ sockets.delete(ws);
239
+ bridge.detach(ws);
240
+ });
241
+ ws.send(
242
+ JSON.stringify({
243
+ type: 'hello',
244
+ protocol: HTTP_BRIDGE_PROTOCOL,
245
+ version: 1
246
+ })
247
+ );
248
+ ws.on('message', (message) => {
249
+ bridge.receive(ws, String(message));
250
+ });
251
+ });
252
+ });
253
+
254
+ return {
255
+ hostname: options.hostname,
256
+ port: options.port,
257
+ close: async () => {
258
+ const socketClosePromises = Array.from(sockets, (socket) => closeSocket(socket));
259
+ await Promise.all([
260
+ new Promise<void>((resolve, reject) => {
261
+ server.close((error) => {
262
+ if (error) reject(error);
263
+ else resolve();
264
+ });
265
+ }),
266
+ new Promise<void>((resolve, reject) => {
267
+ wss.close((error) => {
268
+ if (error) reject(error);
269
+ else resolve();
270
+ });
271
+ }),
272
+ ...socketClosePromises
273
+ ]);
274
+ sockets.clear();
275
+ }
276
+ };
277
+ }
278
+
279
+ class WebSocketHttpRequestBridge implements HttpRequestBridge {
280
+ private socket: WebSocket | null = null;
281
+ private nextRequestId = 1;
282
+ private readonly pending = new Map<
283
+ string,
284
+ {
285
+ method: string;
286
+ resolve(response: Response): void;
287
+ timeout: ReturnType<typeof setTimeout>;
288
+ }
289
+ >();
290
+
291
+ public constructor(private readonly requestTimeoutMs: number) {}
292
+
293
+ public attach(socket: WebSocket): void {
294
+ const previousSocket = this.socket;
295
+ this.socket = socket;
296
+ if (previousSocket && previousSocket !== socket) {
297
+ this.failPending('bridge_replaced');
298
+ if (previousSocket.readyState === previousSocket.OPEN) previousSocket.close();
299
+ }
300
+ }
301
+
302
+ public detach(socket: WebSocket): void {
303
+ if (this.socket !== socket) return;
304
+ this.socket = null;
305
+ this.failPending('bridge_disconnected');
306
+ }
307
+
308
+ private failPending(error: string): void {
309
+ for (const [id, pending] of this.pending) {
310
+ clearTimeout(pending.timeout);
311
+ pending.resolve(jsonResponse({error}, 502));
312
+ this.pending.delete(id);
313
+ }
314
+ }
315
+
316
+ public async forward(message: BridgeRequestMessage, method: string): Promise<Response> {
317
+ if (!this.socket || this.socket.readyState !== this.socket.OPEN) {
318
+ return jsonResponse({error: 'not_connected'}, 503);
319
+ }
320
+
321
+ const id = `req-${this.nextRequestId}`;
322
+ this.nextRequestId += 1;
323
+ const requestMessage = {...message, id};
324
+
325
+ return new Promise((resolve) => {
326
+ const timeout = setTimeout(() => {
327
+ this.pending.delete(id);
328
+ resolve(jsonResponse({error: 'gateway_timeout'}, 504));
329
+ }, this.requestTimeoutMs);
330
+
331
+ this.pending.set(id, {method, resolve, timeout});
332
+ try {
333
+ this.socket?.send(JSON.stringify(requestMessage));
334
+ } catch {
335
+ clearTimeout(timeout);
336
+ this.pending.delete(id);
337
+ resolve(jsonResponse({error: 'bridge_send_failed'}, 502));
338
+ }
339
+ });
340
+ }
341
+
342
+ public receive(socket: WebSocket, message: string): void {
343
+ if (socket !== this.socket) return;
344
+ const parsed = parseBridgeClientMessage(message);
345
+ if (!parsed) return;
346
+ if (parsed.type === 'error') {
347
+ if (!parsed.id) return;
348
+ const pending = this.pending.get(parsed.id);
349
+ if (!pending) return;
350
+ clearTimeout(pending.timeout);
351
+ this.pending.delete(parsed.id);
352
+ pending.resolve(jsonResponse({error: 'bridge_error', message: parsed.message}, 502));
353
+ return;
354
+ }
355
+
356
+ const pending = this.pending.get(parsed.id);
357
+ if (!pending) return;
358
+ clearTimeout(pending.timeout);
359
+ this.pending.delete(parsed.id);
360
+ pending.resolve(toHttpResponse(parsed, pending.method));
361
+ }
362
+ }
363
+
364
+ function closeSocket(socket: WebSocket): Promise<void> {
365
+ return new Promise((resolve) => {
366
+ if (socket.readyState === socket.CLOSED) {
367
+ resolve();
368
+ return;
369
+ }
370
+ socket.once('close', () => resolve());
371
+ socket.terminate();
372
+ });
373
+ }
374
+
375
+ interface BridgeRequestOptions {
376
+ routes: readonly string[];
377
+ maxBodyBytes: number;
378
+ clientAddress: string;
379
+ authenticatedUser?: string;
380
+ }
381
+
382
+ async function createBridgeRequestMessage(request: Request, options: BridgeRequestOptions): Promise<BridgeRequestMessage> {
383
+ const url = new URL(request.url);
384
+ const routeMatch = matchRoute(url.pathname, options.routes);
385
+ const headers = collectHeaders(request.headers);
386
+ delete headers[DIGEST_AUTH_USER_HEADER];
387
+ if (options.authenticatedUser) headers[DIGEST_AUTH_USER_HEADER] = [options.authenticatedUser];
388
+ const message: BridgeRequestMessage = {
389
+ type: 'request',
390
+ protocol: HTTP_BRIDGE_PROTOCOL,
391
+ version: HTTP_BRIDGE_PROTOCOL_VERSION,
392
+ id: '',
393
+ method: request.method.toUpperCase(),
394
+ url: request.url,
395
+ path: url.pathname,
396
+ route: routeMatch.route,
397
+ pathParams: routeMatch.pathParams,
398
+ query: collectQuery(url.searchParams),
399
+ headers,
400
+ body: await readTextBridgeBody(request, options.maxBodyBytes),
401
+ clientAddress: options.clientAddress
402
+ };
403
+ if (options.authenticatedUser) {
404
+ message.auth = {
405
+ type: 'digest',
406
+ username: options.authenticatedUser
407
+ };
408
+ }
409
+ return message;
410
+ }
411
+
412
+ function toHttpResponse(message: BridgeResponseMessage, method: string): Response {
413
+ const status = isValidHttpStatus(message.status) ? message.status : 502;
414
+ if (!isValidHttpStatus(message.status)) {
415
+ return jsonResponse({error: 'invalid_bridge_status'}, 502);
416
+ }
417
+
418
+ const headers = new Headers();
419
+ for (const [name, values] of Object.entries(message.headers)) {
420
+ const normalized = normalizeHeaderName(name);
421
+ if (
422
+ !validateHeaderName(normalized) ||
423
+ isForbiddenResponseHeader(normalized) ||
424
+ values.some((value) => !validateHeaderValue(value))
425
+ ) {
426
+ return jsonResponse({error: 'invalid_bridge_header'}, 502);
427
+ }
428
+ for (const value of values) {
429
+ headers.append(normalized, value);
430
+ }
431
+ }
432
+
433
+ if (isBodyForbidden(method, status)) {
434
+ return new Response(null, {status, headers});
435
+ }
436
+
437
+ if (message.body.kind === 'text') {
438
+ if (!headers.has('content-type')) headers.set('content-type', 'text/plain; charset=utf-8');
439
+ return new Response(message.body.text, {status, headers});
440
+ }
441
+ return new Response(null, {status, headers});
442
+ }
443
+
444
+ function collectQuery(params: URLSearchParams): Record<string, string[]> {
445
+ const query: Record<string, string[]> = {};
446
+ for (const [name, value] of params) {
447
+ query[name] ??= [];
448
+ query[name].push(value);
449
+ }
450
+ return query;
451
+ }
452
+
453
+ function collectHeaders(headers: Headers): Record<string, string[]> {
454
+ const result: Record<string, string[]> = {};
455
+ headers.forEach((value, name) => {
456
+ const normalized = normalizeHeaderName(name);
457
+ result[normalized] ??= [];
458
+ result[normalized].push(value);
459
+ });
460
+ return result;
461
+ }
462
+
463
+ async function readTextBridgeBody(request: Request, maxBytes: number): Promise<BridgeBody> {
464
+ if (request.method.toUpperCase() === 'GET' || request.method.toUpperCase() === 'HEAD') {
465
+ return {kind: 'empty'};
466
+ }
467
+ const contentLength = parseContentLength(request.headers.get('content-length'));
468
+ if (contentLength !== null && contentLength > maxBytes) {
469
+ return {kind: 'unsupported', reason: 'request_body_too_large'};
470
+ }
471
+ const contentType = request.headers.get('content-type') ?? '';
472
+ const lowerContentType = contentType.toLowerCase();
473
+ if (!TEXT_BODY_TYPES.some((type) => lowerContentType.startsWith(type))) {
474
+ return {kind: 'unsupported', reason: 'non_text_body'};
475
+ }
476
+ const text = await readTextWithLimit(request, maxBytes);
477
+ return text === null ? {kind: 'unsupported', reason: 'request_body_too_large'} : {kind: 'text', text};
478
+ }
479
+
480
+ async function readTextWithLimit(request: Request, maxBytes: number): Promise<string | null> {
481
+ if (!request.body) return '';
482
+ const reader = request.body.getReader();
483
+ const decoder = new TextDecoder();
484
+ let bytesRead = 0;
485
+ let text = '';
486
+
487
+ try {
488
+ for (;;) {
489
+ const result = await reader.read();
490
+ if (result.done) break;
491
+ bytesRead += result.value.byteLength;
492
+ if (bytesRead > maxBytes) {
493
+ await reader.cancel();
494
+ return null;
495
+ }
496
+ text += decoder.decode(result.value, {stream: true});
497
+ }
498
+ text += decoder.decode();
499
+ return text;
500
+ } finally {
501
+ reader.releaseLock();
502
+ }
503
+ }
504
+
505
+ function parseContentLength(value: string | null): number | null {
506
+ if (value === null) return null;
507
+ const length = Number.parseInt(value, 10);
508
+ return Number.isSafeInteger(length) && length >= 0 ? length : null;
509
+ }
510
+
511
+ function readClientAddress(c: Context): string {
512
+ try {
513
+ return getConnInfo(c).remote.address ?? '';
514
+ } catch {
515
+ return '';
516
+ }
517
+ }
518
+
519
+ interface RouteMatch {
520
+ route: string;
521
+ pathParams: Record<string, string>;
522
+ }
523
+
524
+ function matchRoute(pathname: string, routes: readonly string[]): RouteMatch {
525
+ for (const route of routes) {
526
+ const params = matchRoutePattern(pathname, route);
527
+ if (params) return {route, pathParams: params};
528
+ }
529
+ return {route: pathname, pathParams: {}};
530
+ }
531
+
532
+ function matchRoutePattern(pathname: string, route: string): Record<string, string> | null {
533
+ const pathSegments = splitRoute(pathname);
534
+ const routeSegments = splitRoute(route);
535
+ if (pathSegments.length !== routeSegments.length) return null;
536
+
537
+ const params: Record<string, string> = {};
538
+ for (let index = 0; index < routeSegments.length; index += 1) {
539
+ const routeSegment = routeSegments[index];
540
+ const pathSegment = pathSegments[index] ?? '';
541
+ if (routeSegment?.startsWith(':')) {
542
+ params[routeSegment.slice(1)] = pathSegment;
543
+ } else if (routeSegment !== pathSegment) {
544
+ return null;
545
+ }
546
+ }
547
+ return params;
548
+ }
549
+
550
+ function splitRoute(value: string): string[] {
551
+ return value
552
+ .split('/')
553
+ .filter((segment) => segment.length > 0)
554
+ .map(decodePathSegment);
555
+ }
556
+
557
+ async function handleResourceRequest(
558
+ c: Context,
559
+ options: ServerAppOptions
560
+ ): Promise<Response | null> {
561
+ const route = parseResourceRoute(new URL(c.req.url).pathname);
562
+ if (!route) return null;
563
+
564
+ if (route.managementNamespace) {
565
+ return jsonResponse({error: 'not_found'}, 404);
566
+ }
567
+
568
+ const resources = options.resources;
569
+ if (!resources) return null;
570
+
571
+ const published = await resources.isNamespacePublished?.(route.routeName);
572
+ if (published === false) {
573
+ return jsonResponse({error: 'not_found'}, 404);
574
+ }
575
+
576
+ const method = c.req.method.toUpperCase();
577
+ if (route.listing) {
578
+ if (method !== 'GET' && method !== 'HEAD') return methodNotAllowed(['GET', 'HEAD']);
579
+ return handleResourceList(c.req.raw, route.routeName, resources, options, method === 'HEAD');
580
+ }
581
+
582
+ if (method === 'GET' || method === 'HEAD') {
583
+ return handleResourceGet(c.req.raw, route.routeName, route.resourceName, resources, options, method);
584
+ }
585
+ if (method === 'PUT') {
586
+ return handleResourcePut(c.req.raw, route.routeName, route.resourceName, resources, options);
587
+ }
588
+ if (method === 'DELETE') {
589
+ return handleResourceDelete(c.req.raw, route.routeName, route.resourceName, resources, options);
590
+ }
591
+
592
+ return methodNotAllowed(['GET', 'HEAD', 'PUT', 'DELETE']);
593
+ }
594
+
595
+ async function handleResourceGet(
596
+ request: Request,
597
+ routeName: string,
598
+ resourceName: string,
599
+ resources: ResourceCapability,
600
+ options: ServerAppOptions,
601
+ method: 'GET' | 'HEAD'
602
+ ): Promise<Response> {
603
+ if (!(await authorize(options, request, method.toLowerCase() as 'get' | 'head', routeName, resourceName))) {
604
+ return jsonResponse({error: 'forbidden'}, 403);
605
+ }
606
+
607
+ const snapshot = await resources.getResource(routeName, resourceName);
608
+ if (!snapshot) {
609
+ logResource(options, {
610
+ event: method === 'GET' ? 'resource.get' : 'resource.head',
611
+ routeName,
612
+ resourceName,
613
+ status: 404
614
+ });
615
+ return jsonResponse({error: 'not_found'}, 404);
616
+ }
617
+
618
+ const headers = resourceHeaders(snapshot);
619
+ const notModified = isNotModified(request, headers);
620
+ const status = notModified ? 304 : 200;
621
+ logResource(options, {
622
+ event: method === 'GET' ? 'resource.get' : 'resource.head',
623
+ routeName,
624
+ resourceName,
625
+ mimeType: snapshot.mimeType,
626
+ byteLength: getByteLength(snapshot),
627
+ status
628
+ });
629
+
630
+ if (notModified) return new Response(null, {status, headers});
631
+ return new Response(method === 'HEAD' ? null : toArrayBuffer(snapshot.bytes), {status, headers});
632
+ }
633
+
634
+ async function handleResourceList(
635
+ request: Request,
636
+ routeName: string,
637
+ resources: ResourceCapability,
638
+ options: ServerAppOptions,
639
+ headOnly: boolean
640
+ ): Promise<Response> {
641
+ if (!(await authorize(options, request, headOnly ? 'head' : 'list', routeName))) {
642
+ return jsonResponse({error: 'forbidden'}, 403);
643
+ }
644
+ if (!resources.listResources) return jsonResponse({error: 'not_supported'}, 405, {Allow: 'GET, HEAD'});
645
+
646
+ const resourcesList = await resources.listResources(routeName);
647
+ const body = JSON.stringify({
648
+ routeName,
649
+ resources: resourcesList.map((resource) => metadataWithoutBody(resource))
650
+ });
651
+ const headers = new Headers({
652
+ 'Content-Type': 'application/json; charset=utf-8',
653
+ 'Content-Length': String(new TextEncoder().encode(body).byteLength),
654
+ 'Cache-Control': 'no-store'
655
+ });
656
+ logResource(options, {
657
+ event: 'resource.list',
658
+ routeName,
659
+ status: 200
660
+ });
661
+ return new Response(headOnly ? null : body, {status: 200, headers});
662
+ }
663
+
664
+ async function handleResourcePut(
665
+ request: Request,
666
+ routeName: string,
667
+ resourceName: string,
668
+ resources: ResourceCapability,
669
+ options: ServerAppOptions
670
+ ): Promise<Response> {
671
+ if (!resources.putResource) return jsonResponse({error: 'not_supported'}, 405, {Allow: 'GET, HEAD'});
672
+ if (!(await authorize(options, request, 'put', routeName, resourceName))) {
673
+ return jsonResponse({error: 'forbidden'}, 403);
674
+ }
675
+
676
+ const mimeType = request.headers.get('content-type')?.split(';', 1)[0]?.trim() || 'application/octet-stream';
677
+ const supported = await resources.isSupportedResourceType?.(mimeType);
678
+ if (supported === false) return jsonResponse({error: 'unsupported_media_type'}, 415);
679
+
680
+ const maxBytes = options.maxResourceBodyBytes ?? DEFAULT_MAX_RESOURCE_BODY_BYTES;
681
+ const contentLength = request.headers.get('content-length');
682
+ if (contentLength !== null && Number.parseInt(contentLength, 10) > maxBytes) {
683
+ return jsonResponse({error: 'payload_too_large'}, 413);
684
+ }
685
+
686
+ const bytes = await readBodyWithLimit(request, maxBytes);
687
+ if (bytes === null) return jsonResponse({error: 'payload_too_large'}, 413);
688
+
689
+ const result = await resources.putResource({routeName, resourceName, mimeType, bytes});
690
+ logResource(options, {
691
+ event: 'resource.put',
692
+ routeName,
693
+ resourceName,
694
+ mimeType,
695
+ byteLength: bytes.byteLength,
696
+ status: result.created ? 201 : 204
697
+ });
698
+
699
+ if (result.created) {
700
+ return new Response(null, {
701
+ status: 201,
702
+ headers: {Location: resourceLocation(routeName, resourceName)}
703
+ });
704
+ }
705
+ return new Response(null, {status: 204});
706
+ }
707
+
708
+ async function handleResourceDelete(
709
+ request: Request,
710
+ routeName: string,
711
+ resourceName: string,
712
+ resources: ResourceCapability,
713
+ options: ServerAppOptions
714
+ ): Promise<Response> {
715
+ if (!resources.deleteResource) return jsonResponse({error: 'not_supported'}, 405, {Allow: 'GET, HEAD, PUT'});
716
+ if (!(await authorize(options, request, 'delete', routeName, resourceName))) {
717
+ return jsonResponse({error: 'forbidden'}, 403);
718
+ }
719
+
720
+ const removed = await resources.deleteResource(routeName, resourceName);
721
+ logResource(options, {
722
+ event: 'resource.delete',
723
+ routeName,
724
+ resourceName,
725
+ status: removed ? 204 : 404
726
+ });
727
+ return removed ? new Response(null, {status: 204}) : jsonResponse({error: 'not_found'}, 404);
728
+ }
729
+
730
+ interface ParsedResourceRoute {
731
+ routeName: string;
732
+ resourceName: string;
733
+ listing: boolean;
734
+ managementNamespace: boolean;
735
+ }
736
+
737
+ function parseResourceRoute(pathname: string): ParsedResourceRoute | null {
738
+ const rawSegments = pathname.split('/').filter((segment) => segment.length > 0);
739
+ const segments = rawSegments.map(decodePathSegment);
740
+ if (segments[0] === '_tw-http') {
741
+ return {routeName: '', resourceName: '', listing: false, managementNamespace: true};
742
+ }
743
+
744
+ const assetIndex = segments.indexOf('@assets');
745
+ if (assetIndex < 0) return null;
746
+ if (assetIndex !== 0) {
747
+ return {routeName: '', resourceName: '', listing: false, managementNamespace: true};
748
+ }
749
+
750
+ const routeName = '';
751
+ const resourceSegments = segments.slice(1);
752
+ const listing = resourceSegments.length === 0;
753
+ const resourceName = resourceSegments.join('/');
754
+ if (!listing && resourceName.length === 0) return null;
755
+ return {routeName, resourceName, listing, managementNamespace: false};
756
+ }
757
+
758
+ function decodePathSegment(segment: string): string {
759
+ try {
760
+ return decodeURIComponent(segment);
761
+ } catch {
762
+ return segment;
763
+ }
764
+ }
765
+
766
+ function resourceHeaders(snapshot: ResourceSnapshot): Headers {
767
+ const headers = new Headers({
768
+ 'Content-Type': snapshot.mimeType,
769
+ 'Content-Length': String(getByteLength(snapshot)),
770
+ 'Cache-Control': snapshot.cacheControl ?? defaultCacheControl(snapshot)
771
+ });
772
+ const etag = getEtag(snapshot);
773
+ if (etag) headers.set('ETag', etag);
774
+ if (snapshot.lastModified) headers.set('Last-Modified', snapshot.lastModified.toUTCString());
775
+ return headers;
776
+ }
777
+
778
+ function getByteLength(snapshot: ResourceSnapshot): number {
779
+ return snapshot.bytes.byteLength;
780
+ }
781
+
782
+ function getEtag(snapshot: ResourceSnapshot): string | undefined {
783
+ const identity = snapshot.etag ?? snapshot.replacementId;
784
+ if (!identity) return undefined;
785
+ if (/^(W\/)?"[^"]*"$/.test(identity)) return identity;
786
+ return `"${identity.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
787
+ }
788
+
789
+ function defaultCacheControl(snapshot: ResourceSnapshot): string {
790
+ return snapshot.etag || snapshot.replacementId || snapshot.lastModified ? 'no-cache' : 'no-store';
791
+ }
792
+
793
+ function isNotModified(request: Request, headers: Headers): boolean {
794
+ const responseEtag = headers.get('ETag');
795
+ const requestEtags = request.headers.get('if-none-match');
796
+ if (responseEtag && requestEtags) {
797
+ return requestEtags
798
+ .split(',')
799
+ .map((value) => value.trim())
800
+ .some((value) => value === '*' || value === responseEtag);
801
+ }
802
+
803
+ const lastModified = headers.get('Last-Modified');
804
+ const ifModifiedSince = request.headers.get('if-modified-since');
805
+ if (!lastModified || !ifModifiedSince) return false;
806
+ return Date.parse(ifModifiedSince) >= Date.parse(lastModified);
807
+ }
808
+
809
+ async function readBodyWithLimit(request: Request, maxBytes: number): Promise<Uint8Array | null> {
810
+ if (!request.body) return new Uint8Array();
811
+
812
+ const reader = request.body.getReader();
813
+ const chunks: Uint8Array[] = [];
814
+ let total = 0;
815
+
816
+ while (true) {
817
+ const {done, value} = await reader.read();
818
+ if (done) break;
819
+ total += value.byteLength;
820
+ if (total > maxBytes) {
821
+ await reader.cancel();
822
+ return null;
823
+ }
824
+ chunks.push(value);
825
+ }
826
+
827
+ const result = new Uint8Array(total);
828
+ let offset = 0;
829
+ for (const chunk of chunks) {
830
+ result.set(chunk, offset);
831
+ offset += chunk.byteLength;
832
+ }
833
+ return result;
834
+ }
835
+
836
+ async function authorize(
837
+ options: ServerAppOptions,
838
+ request: Request,
839
+ operation: 'get' | 'head' | 'put' | 'delete' | 'list',
840
+ routeName: string,
841
+ resourceName?: string
842
+ ): Promise<boolean> {
843
+ return (await options.authorizeResource?.(request, operation, routeName, resourceName)) !== false;
844
+ }
845
+
846
+ function metadataWithoutBody(resource: ResourceMetadata): ResourceMetadata {
847
+ const metadata: ResourceMetadata = {
848
+ name: resource.name,
849
+ mimeType: resource.mimeType
850
+ };
851
+ if (resource.byteLength !== undefined) metadata.byteLength = resource.byteLength;
852
+ if (resource.etag !== undefined) metadata.etag = resource.etag;
853
+ if (resource.replacementId !== undefined) metadata.replacementId = resource.replacementId;
854
+ if (resource.lastModified !== undefined) metadata.lastModified = resource.lastModified;
855
+ if (resource.cacheControl !== undefined) metadata.cacheControl = resource.cacheControl;
856
+ return metadata;
857
+ }
858
+
859
+ function resourceLocation(routeName: string, resourceName: string): string {
860
+ const encodedName = resourceName.split('/').map(encodeURIComponent).join('/');
861
+ return routeName === '' ? `/@assets/${encodedName}` : `/${encodeURIComponent(routeName)}/${encodedName}`;
862
+ }
863
+
864
+ function methodNotAllowed(methods: readonly string[]): Response {
865
+ return jsonResponse({error: 'method_not_allowed'}, 405, {Allow: methods.join(', ')});
866
+ }
867
+
868
+ function jsonResponse(body: unknown, status: number, headers?: HeadersInit): Response {
869
+ const responseHeaders = new Headers(headers);
870
+ responseHeaders.set('Content-Type', 'application/json; charset=utf-8');
871
+ return new Response(JSON.stringify(body), {status, headers: responseHeaders});
872
+ }
873
+
874
+ function logResource(options: ServerAppOptions, event: ResourceLogEvent): void {
875
+ options.logger?.info(event);
876
+ }
877
+
878
+ function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
879
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
880
+ }