@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.
- package/LICENSE +373 -0
- package/README.ja.md +346 -0
- package/README.md +874 -0
- package/dist/auth/digest-file.d.ts +17 -0
- package/dist/auth/digest-file.js +90 -0
- package/dist/auth/digest-file.js.map +1 -0
- package/dist/auth/digest.d.ts +23 -0
- package/dist/auth/digest.js +139 -0
- package/dist/auth/digest.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +156 -0
- package/dist/cli.js.map +1 -0
- package/dist/community.d.ts +81 -0
- package/dist/community.js +689 -0
- package/dist/community.js.map +1 -0
- package/dist/digest-cli.d.ts +1 -0
- package/dist/digest-cli.js +159 -0
- package/dist/digest-cli.js.map +1 -0
- package/dist/extension-manifest.json +441 -0
- package/dist/protocol.d.ts +59 -0
- package/dist/protocol.js +71 -0
- package/dist/protocol.js.map +1 -0
- package/dist/server.d.ts +89 -0
- package/dist/server.js +650 -0
- package/dist/server.js.map +1 -0
- package/dist/turbowarp-http-server.js +1110 -0
- package/docs/deployment-targets.ja.md +274 -0
- package/docs/turbowarp-http-server.architecture.html +15149 -0
- package/docs/turbowarp-http-server.architecture.json +1014 -0
- package/docs/turbowarp-http-server.architecture.visual-check.1440x900.dark.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.1440x900.light.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.dark.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.light.png +0 -0
- package/docs/turbowarp-http-server.architecture.visual-check.html +32 -0
- package/docs/turbowarp-http-server.architecture.visual-check.json +547 -0
- package/examples/01-hello-form/README.ja.md +46 -0
- package/examples/01-hello-form/server.mjs +59 -0
- package/examples/02-visitor-counter/README.ja.md +39 -0
- package/examples/02-visitor-counter/server.mjs +44 -0
- package/examples/03-message-board/README.ja.md +47 -0
- package/examples/03-message-board/server.mjs +72 -0
- package/examples/04-image-upload/README.ja.md +46 -0
- package/examples/04-image-upload/server.mjs +149 -0
- package/examples/05-live-camera/README.ja.md +47 -0
- package/examples/05-live-camera/server.mjs +147 -0
- package/examples/06-scratch-like-community/README.ja.md +82 -0
- package/examples/06-scratch-like-community/server.mjs +17 -0
- package/examples/README.ja.md +20 -0
- package/package.json +75 -0
- package/schemas/extension-manifest.schema.json +49 -0
- package/src/auth/digest-file.ts +115 -0
- package/src/auth/digest.ts +170 -0
- package/src/block-definitions.json +417 -0
- package/src/cli.ts +172 -0
- package/src/community.ts +815 -0
- package/src/config.ts +12 -0
- package/src/digest-cli.ts +178 -0
- package/src/extension-manifest.ts +149 -0
- package/src/extension.ts +713 -0
- package/src/globals.d.ts +30 -0
- package/src/index.ts +8 -0
- package/src/protocol.ts +132 -0
- package/src/server.ts +880 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,650 @@
|
|
|
1
|
+
import { serve } from '@hono/node-server';
|
|
2
|
+
import { getConnInfo } from '@hono/node-server/conninfo';
|
|
3
|
+
import { createServer as createHttpsServer } from 'node:https';
|
|
4
|
+
import { Hono } from 'hono';
|
|
5
|
+
import { secureHeaders } from 'hono/secure-headers';
|
|
6
|
+
import { WebSocketServer } from 'ws';
|
|
7
|
+
import { DIGEST_AUTH_USER_HEADER, isLocalAddress, verifyDigestAuth } from './auth/digest.js';
|
|
8
|
+
import { createCommunityApp } from './community.js';
|
|
9
|
+
import { HTTP_BRIDGE_PROTOCOL, HTTP_BRIDGE_PROTOCOL_VERSION, isBodyForbidden, isForbiddenResponseHeader, isValidHttpStatus, normalizeHeaderName, parseBridgeClientMessage, validateHeaderName, validateHeaderValue } from './protocol.js';
|
|
10
|
+
const DEFAULT_MAX_RESOURCE_BODY_BYTES = 10 * 1024 * 1024;
|
|
11
|
+
const DEFAULT_MAX_REQUEST_BODY_BYTES = 1024 * 1024;
|
|
12
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 5000;
|
|
13
|
+
const TEXT_BODY_TYPES = [
|
|
14
|
+
'application/json',
|
|
15
|
+
'application/x-www-form-urlencoded',
|
|
16
|
+
'application/xml',
|
|
17
|
+
'text/'
|
|
18
|
+
];
|
|
19
|
+
const authenticatedUsers = new WeakMap();
|
|
20
|
+
export function createApp(options = {}) {
|
|
21
|
+
const app = new Hono();
|
|
22
|
+
app.use('*', secureHeaders());
|
|
23
|
+
if (options.digestAuth) {
|
|
24
|
+
app.use('*', async (c, next) => {
|
|
25
|
+
const result = await verifyDigestAuth(c.req.raw, c.req.method, options.digestAuth);
|
|
26
|
+
if (!result.ok) {
|
|
27
|
+
return c.json({
|
|
28
|
+
error: 'authentication_required',
|
|
29
|
+
message: 'HTTP Digest authentication is required.'
|
|
30
|
+
}, 401, { 'WWW-Authenticate': result.challenge ?? '' });
|
|
31
|
+
}
|
|
32
|
+
if (result.username)
|
|
33
|
+
authenticatedUsers.set(c.req.raw, result.username);
|
|
34
|
+
await next();
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
if (options.community) {
|
|
38
|
+
app.route('/', createCommunityApp(options.community));
|
|
39
|
+
}
|
|
40
|
+
app.get('/health', (c) => c.json({
|
|
41
|
+
ok: true,
|
|
42
|
+
service: 'turbowarp-http-server'
|
|
43
|
+
}));
|
|
44
|
+
app.get('/ws', (c) => c.json({
|
|
45
|
+
error: 'upgrade_required',
|
|
46
|
+
message: 'Connect to this endpoint with WebSocket.'
|
|
47
|
+
}, 426));
|
|
48
|
+
app.all('*', async (c) => {
|
|
49
|
+
const resourceResponse = await handleResourceRequest(c, options);
|
|
50
|
+
if (resourceResponse)
|
|
51
|
+
return resourceResponse;
|
|
52
|
+
if (options.bridge) {
|
|
53
|
+
const bridgeRequestOptions = {
|
|
54
|
+
routes: options.routes ?? [],
|
|
55
|
+
maxBodyBytes: options.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY_BYTES,
|
|
56
|
+
clientAddress: readClientAddress(c)
|
|
57
|
+
};
|
|
58
|
+
const authenticatedUser = authenticatedUsers.get(c.req.raw);
|
|
59
|
+
if (authenticatedUser)
|
|
60
|
+
bridgeRequestOptions.authenticatedUser = authenticatedUser;
|
|
61
|
+
return options.bridge.forward(await createBridgeRequestMessage(c.req.raw, bridgeRequestOptions), c.req.method);
|
|
62
|
+
}
|
|
63
|
+
return c.json({
|
|
64
|
+
error: 'not_connected',
|
|
65
|
+
message: 'HTTP-to-TurboWarp request forwarding has not been implemented yet.'
|
|
66
|
+
}, 503);
|
|
67
|
+
});
|
|
68
|
+
return app;
|
|
69
|
+
}
|
|
70
|
+
export function startServer(options) {
|
|
71
|
+
const bridge = new WebSocketHttpRequestBridge(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);
|
|
72
|
+
const app = createApp({ ...options, bridge });
|
|
73
|
+
const wss = new WebSocketServer({ noServer: true });
|
|
74
|
+
const sockets = new Set();
|
|
75
|
+
const server = serve({
|
|
76
|
+
fetch: app.fetch,
|
|
77
|
+
hostname: options.hostname,
|
|
78
|
+
port: options.port,
|
|
79
|
+
...(options.tls ? { createServer: createHttpsServer, serverOptions: options.tls } : {})
|
|
80
|
+
});
|
|
81
|
+
server.on('upgrade', (request, socket, head) => {
|
|
82
|
+
if (new URL(request.url ?? '/', 'http://127.0.0.1').pathname !== '/ws') {
|
|
83
|
+
socket.destroy();
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (!isLocalAddress(socket.remoteAddress)) {
|
|
87
|
+
socket.destroy();
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
91
|
+
sockets.add(ws);
|
|
92
|
+
bridge.attach(ws);
|
|
93
|
+
ws.on('close', () => {
|
|
94
|
+
sockets.delete(ws);
|
|
95
|
+
bridge.detach(ws);
|
|
96
|
+
});
|
|
97
|
+
ws.send(JSON.stringify({
|
|
98
|
+
type: 'hello',
|
|
99
|
+
protocol: HTTP_BRIDGE_PROTOCOL,
|
|
100
|
+
version: 1
|
|
101
|
+
}));
|
|
102
|
+
ws.on('message', (message) => {
|
|
103
|
+
bridge.receive(ws, String(message));
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
return {
|
|
108
|
+
hostname: options.hostname,
|
|
109
|
+
port: options.port,
|
|
110
|
+
close: async () => {
|
|
111
|
+
const socketClosePromises = Array.from(sockets, (socket) => closeSocket(socket));
|
|
112
|
+
await Promise.all([
|
|
113
|
+
new Promise((resolve, reject) => {
|
|
114
|
+
server.close((error) => {
|
|
115
|
+
if (error)
|
|
116
|
+
reject(error);
|
|
117
|
+
else
|
|
118
|
+
resolve();
|
|
119
|
+
});
|
|
120
|
+
}),
|
|
121
|
+
new Promise((resolve, reject) => {
|
|
122
|
+
wss.close((error) => {
|
|
123
|
+
if (error)
|
|
124
|
+
reject(error);
|
|
125
|
+
else
|
|
126
|
+
resolve();
|
|
127
|
+
});
|
|
128
|
+
}),
|
|
129
|
+
...socketClosePromises
|
|
130
|
+
]);
|
|
131
|
+
sockets.clear();
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
class WebSocketHttpRequestBridge {
|
|
136
|
+
constructor(requestTimeoutMs) {
|
|
137
|
+
this.requestTimeoutMs = requestTimeoutMs;
|
|
138
|
+
this.socket = null;
|
|
139
|
+
this.nextRequestId = 1;
|
|
140
|
+
this.pending = new Map();
|
|
141
|
+
}
|
|
142
|
+
attach(socket) {
|
|
143
|
+
const previousSocket = this.socket;
|
|
144
|
+
this.socket = socket;
|
|
145
|
+
if (previousSocket && previousSocket !== socket) {
|
|
146
|
+
this.failPending('bridge_replaced');
|
|
147
|
+
if (previousSocket.readyState === previousSocket.OPEN)
|
|
148
|
+
previousSocket.close();
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
detach(socket) {
|
|
152
|
+
if (this.socket !== socket)
|
|
153
|
+
return;
|
|
154
|
+
this.socket = null;
|
|
155
|
+
this.failPending('bridge_disconnected');
|
|
156
|
+
}
|
|
157
|
+
failPending(error) {
|
|
158
|
+
for (const [id, pending] of this.pending) {
|
|
159
|
+
clearTimeout(pending.timeout);
|
|
160
|
+
pending.resolve(jsonResponse({ error }, 502));
|
|
161
|
+
this.pending.delete(id);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
async forward(message, method) {
|
|
165
|
+
if (!this.socket || this.socket.readyState !== this.socket.OPEN) {
|
|
166
|
+
return jsonResponse({ error: 'not_connected' }, 503);
|
|
167
|
+
}
|
|
168
|
+
const id = `req-${this.nextRequestId}`;
|
|
169
|
+
this.nextRequestId += 1;
|
|
170
|
+
const requestMessage = { ...message, id };
|
|
171
|
+
return new Promise((resolve) => {
|
|
172
|
+
const timeout = setTimeout(() => {
|
|
173
|
+
this.pending.delete(id);
|
|
174
|
+
resolve(jsonResponse({ error: 'gateway_timeout' }, 504));
|
|
175
|
+
}, this.requestTimeoutMs);
|
|
176
|
+
this.pending.set(id, { method, resolve, timeout });
|
|
177
|
+
try {
|
|
178
|
+
this.socket?.send(JSON.stringify(requestMessage));
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
clearTimeout(timeout);
|
|
182
|
+
this.pending.delete(id);
|
|
183
|
+
resolve(jsonResponse({ error: 'bridge_send_failed' }, 502));
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
receive(socket, message) {
|
|
188
|
+
if (socket !== this.socket)
|
|
189
|
+
return;
|
|
190
|
+
const parsed = parseBridgeClientMessage(message);
|
|
191
|
+
if (!parsed)
|
|
192
|
+
return;
|
|
193
|
+
if (parsed.type === 'error') {
|
|
194
|
+
if (!parsed.id)
|
|
195
|
+
return;
|
|
196
|
+
const pending = this.pending.get(parsed.id);
|
|
197
|
+
if (!pending)
|
|
198
|
+
return;
|
|
199
|
+
clearTimeout(pending.timeout);
|
|
200
|
+
this.pending.delete(parsed.id);
|
|
201
|
+
pending.resolve(jsonResponse({ error: 'bridge_error', message: parsed.message }, 502));
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const pending = this.pending.get(parsed.id);
|
|
205
|
+
if (!pending)
|
|
206
|
+
return;
|
|
207
|
+
clearTimeout(pending.timeout);
|
|
208
|
+
this.pending.delete(parsed.id);
|
|
209
|
+
pending.resolve(toHttpResponse(parsed, pending.method));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
function closeSocket(socket) {
|
|
213
|
+
return new Promise((resolve) => {
|
|
214
|
+
if (socket.readyState === socket.CLOSED) {
|
|
215
|
+
resolve();
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
socket.once('close', () => resolve());
|
|
219
|
+
socket.terminate();
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
async function createBridgeRequestMessage(request, options) {
|
|
223
|
+
const url = new URL(request.url);
|
|
224
|
+
const routeMatch = matchRoute(url.pathname, options.routes);
|
|
225
|
+
const headers = collectHeaders(request.headers);
|
|
226
|
+
delete headers[DIGEST_AUTH_USER_HEADER];
|
|
227
|
+
if (options.authenticatedUser)
|
|
228
|
+
headers[DIGEST_AUTH_USER_HEADER] = [options.authenticatedUser];
|
|
229
|
+
const message = {
|
|
230
|
+
type: 'request',
|
|
231
|
+
protocol: HTTP_BRIDGE_PROTOCOL,
|
|
232
|
+
version: HTTP_BRIDGE_PROTOCOL_VERSION,
|
|
233
|
+
id: '',
|
|
234
|
+
method: request.method.toUpperCase(),
|
|
235
|
+
url: request.url,
|
|
236
|
+
path: url.pathname,
|
|
237
|
+
route: routeMatch.route,
|
|
238
|
+
pathParams: routeMatch.pathParams,
|
|
239
|
+
query: collectQuery(url.searchParams),
|
|
240
|
+
headers,
|
|
241
|
+
body: await readTextBridgeBody(request, options.maxBodyBytes),
|
|
242
|
+
clientAddress: options.clientAddress
|
|
243
|
+
};
|
|
244
|
+
if (options.authenticatedUser) {
|
|
245
|
+
message.auth = {
|
|
246
|
+
type: 'digest',
|
|
247
|
+
username: options.authenticatedUser
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
return message;
|
|
251
|
+
}
|
|
252
|
+
function toHttpResponse(message, method) {
|
|
253
|
+
const status = isValidHttpStatus(message.status) ? message.status : 502;
|
|
254
|
+
if (!isValidHttpStatus(message.status)) {
|
|
255
|
+
return jsonResponse({ error: 'invalid_bridge_status' }, 502);
|
|
256
|
+
}
|
|
257
|
+
const headers = new Headers();
|
|
258
|
+
for (const [name, values] of Object.entries(message.headers)) {
|
|
259
|
+
const normalized = normalizeHeaderName(name);
|
|
260
|
+
if (!validateHeaderName(normalized) ||
|
|
261
|
+
isForbiddenResponseHeader(normalized) ||
|
|
262
|
+
values.some((value) => !validateHeaderValue(value))) {
|
|
263
|
+
return jsonResponse({ error: 'invalid_bridge_header' }, 502);
|
|
264
|
+
}
|
|
265
|
+
for (const value of values) {
|
|
266
|
+
headers.append(normalized, value);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (isBodyForbidden(method, status)) {
|
|
270
|
+
return new Response(null, { status, headers });
|
|
271
|
+
}
|
|
272
|
+
if (message.body.kind === 'text') {
|
|
273
|
+
if (!headers.has('content-type'))
|
|
274
|
+
headers.set('content-type', 'text/plain; charset=utf-8');
|
|
275
|
+
return new Response(message.body.text, { status, headers });
|
|
276
|
+
}
|
|
277
|
+
return new Response(null, { status, headers });
|
|
278
|
+
}
|
|
279
|
+
function collectQuery(params) {
|
|
280
|
+
const query = {};
|
|
281
|
+
for (const [name, value] of params) {
|
|
282
|
+
query[name] ?? (query[name] = []);
|
|
283
|
+
query[name].push(value);
|
|
284
|
+
}
|
|
285
|
+
return query;
|
|
286
|
+
}
|
|
287
|
+
function collectHeaders(headers) {
|
|
288
|
+
const result = {};
|
|
289
|
+
headers.forEach((value, name) => {
|
|
290
|
+
const normalized = normalizeHeaderName(name);
|
|
291
|
+
result[normalized] ?? (result[normalized] = []);
|
|
292
|
+
result[normalized].push(value);
|
|
293
|
+
});
|
|
294
|
+
return result;
|
|
295
|
+
}
|
|
296
|
+
async function readTextBridgeBody(request, maxBytes) {
|
|
297
|
+
if (request.method.toUpperCase() === 'GET' || request.method.toUpperCase() === 'HEAD') {
|
|
298
|
+
return { kind: 'empty' };
|
|
299
|
+
}
|
|
300
|
+
const contentLength = parseContentLength(request.headers.get('content-length'));
|
|
301
|
+
if (contentLength !== null && contentLength > maxBytes) {
|
|
302
|
+
return { kind: 'unsupported', reason: 'request_body_too_large' };
|
|
303
|
+
}
|
|
304
|
+
const contentType = request.headers.get('content-type') ?? '';
|
|
305
|
+
const lowerContentType = contentType.toLowerCase();
|
|
306
|
+
if (!TEXT_BODY_TYPES.some((type) => lowerContentType.startsWith(type))) {
|
|
307
|
+
return { kind: 'unsupported', reason: 'non_text_body' };
|
|
308
|
+
}
|
|
309
|
+
const text = await readTextWithLimit(request, maxBytes);
|
|
310
|
+
return text === null ? { kind: 'unsupported', reason: 'request_body_too_large' } : { kind: 'text', text };
|
|
311
|
+
}
|
|
312
|
+
async function readTextWithLimit(request, maxBytes) {
|
|
313
|
+
if (!request.body)
|
|
314
|
+
return '';
|
|
315
|
+
const reader = request.body.getReader();
|
|
316
|
+
const decoder = new TextDecoder();
|
|
317
|
+
let bytesRead = 0;
|
|
318
|
+
let text = '';
|
|
319
|
+
try {
|
|
320
|
+
for (;;) {
|
|
321
|
+
const result = await reader.read();
|
|
322
|
+
if (result.done)
|
|
323
|
+
break;
|
|
324
|
+
bytesRead += result.value.byteLength;
|
|
325
|
+
if (bytesRead > maxBytes) {
|
|
326
|
+
await reader.cancel();
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
text += decoder.decode(result.value, { stream: true });
|
|
330
|
+
}
|
|
331
|
+
text += decoder.decode();
|
|
332
|
+
return text;
|
|
333
|
+
}
|
|
334
|
+
finally {
|
|
335
|
+
reader.releaseLock();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
function parseContentLength(value) {
|
|
339
|
+
if (value === null)
|
|
340
|
+
return null;
|
|
341
|
+
const length = Number.parseInt(value, 10);
|
|
342
|
+
return Number.isSafeInteger(length) && length >= 0 ? length : null;
|
|
343
|
+
}
|
|
344
|
+
function readClientAddress(c) {
|
|
345
|
+
try {
|
|
346
|
+
return getConnInfo(c).remote.address ?? '';
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
return '';
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
function matchRoute(pathname, routes) {
|
|
353
|
+
for (const route of routes) {
|
|
354
|
+
const params = matchRoutePattern(pathname, route);
|
|
355
|
+
if (params)
|
|
356
|
+
return { route, pathParams: params };
|
|
357
|
+
}
|
|
358
|
+
return { route: pathname, pathParams: {} };
|
|
359
|
+
}
|
|
360
|
+
function matchRoutePattern(pathname, route) {
|
|
361
|
+
const pathSegments = splitRoute(pathname);
|
|
362
|
+
const routeSegments = splitRoute(route);
|
|
363
|
+
if (pathSegments.length !== routeSegments.length)
|
|
364
|
+
return null;
|
|
365
|
+
const params = {};
|
|
366
|
+
for (let index = 0; index < routeSegments.length; index += 1) {
|
|
367
|
+
const routeSegment = routeSegments[index];
|
|
368
|
+
const pathSegment = pathSegments[index] ?? '';
|
|
369
|
+
if (routeSegment?.startsWith(':')) {
|
|
370
|
+
params[routeSegment.slice(1)] = pathSegment;
|
|
371
|
+
}
|
|
372
|
+
else if (routeSegment !== pathSegment) {
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return params;
|
|
377
|
+
}
|
|
378
|
+
function splitRoute(value) {
|
|
379
|
+
return value
|
|
380
|
+
.split('/')
|
|
381
|
+
.filter((segment) => segment.length > 0)
|
|
382
|
+
.map(decodePathSegment);
|
|
383
|
+
}
|
|
384
|
+
async function handleResourceRequest(c, options) {
|
|
385
|
+
const route = parseResourceRoute(new URL(c.req.url).pathname);
|
|
386
|
+
if (!route)
|
|
387
|
+
return null;
|
|
388
|
+
if (route.managementNamespace) {
|
|
389
|
+
return jsonResponse({ error: 'not_found' }, 404);
|
|
390
|
+
}
|
|
391
|
+
const resources = options.resources;
|
|
392
|
+
if (!resources)
|
|
393
|
+
return null;
|
|
394
|
+
const published = await resources.isNamespacePublished?.(route.routeName);
|
|
395
|
+
if (published === false) {
|
|
396
|
+
return jsonResponse({ error: 'not_found' }, 404);
|
|
397
|
+
}
|
|
398
|
+
const method = c.req.method.toUpperCase();
|
|
399
|
+
if (route.listing) {
|
|
400
|
+
if (method !== 'GET' && method !== 'HEAD')
|
|
401
|
+
return methodNotAllowed(['GET', 'HEAD']);
|
|
402
|
+
return handleResourceList(c.req.raw, route.routeName, resources, options, method === 'HEAD');
|
|
403
|
+
}
|
|
404
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
405
|
+
return handleResourceGet(c.req.raw, route.routeName, route.resourceName, resources, options, method);
|
|
406
|
+
}
|
|
407
|
+
if (method === 'PUT') {
|
|
408
|
+
return handleResourcePut(c.req.raw, route.routeName, route.resourceName, resources, options);
|
|
409
|
+
}
|
|
410
|
+
if (method === 'DELETE') {
|
|
411
|
+
return handleResourceDelete(c.req.raw, route.routeName, route.resourceName, resources, options);
|
|
412
|
+
}
|
|
413
|
+
return methodNotAllowed(['GET', 'HEAD', 'PUT', 'DELETE']);
|
|
414
|
+
}
|
|
415
|
+
async function handleResourceGet(request, routeName, resourceName, resources, options, method) {
|
|
416
|
+
if (!(await authorize(options, request, method.toLowerCase(), routeName, resourceName))) {
|
|
417
|
+
return jsonResponse({ error: 'forbidden' }, 403);
|
|
418
|
+
}
|
|
419
|
+
const snapshot = await resources.getResource(routeName, resourceName);
|
|
420
|
+
if (!snapshot) {
|
|
421
|
+
logResource(options, {
|
|
422
|
+
event: method === 'GET' ? 'resource.get' : 'resource.head',
|
|
423
|
+
routeName,
|
|
424
|
+
resourceName,
|
|
425
|
+
status: 404
|
|
426
|
+
});
|
|
427
|
+
return jsonResponse({ error: 'not_found' }, 404);
|
|
428
|
+
}
|
|
429
|
+
const headers = resourceHeaders(snapshot);
|
|
430
|
+
const notModified = isNotModified(request, headers);
|
|
431
|
+
const status = notModified ? 304 : 200;
|
|
432
|
+
logResource(options, {
|
|
433
|
+
event: method === 'GET' ? 'resource.get' : 'resource.head',
|
|
434
|
+
routeName,
|
|
435
|
+
resourceName,
|
|
436
|
+
mimeType: snapshot.mimeType,
|
|
437
|
+
byteLength: getByteLength(snapshot),
|
|
438
|
+
status
|
|
439
|
+
});
|
|
440
|
+
if (notModified)
|
|
441
|
+
return new Response(null, { status, headers });
|
|
442
|
+
return new Response(method === 'HEAD' ? null : toArrayBuffer(snapshot.bytes), { status, headers });
|
|
443
|
+
}
|
|
444
|
+
async function handleResourceList(request, routeName, resources, options, headOnly) {
|
|
445
|
+
if (!(await authorize(options, request, headOnly ? 'head' : 'list', routeName))) {
|
|
446
|
+
return jsonResponse({ error: 'forbidden' }, 403);
|
|
447
|
+
}
|
|
448
|
+
if (!resources.listResources)
|
|
449
|
+
return jsonResponse({ error: 'not_supported' }, 405, { Allow: 'GET, HEAD' });
|
|
450
|
+
const resourcesList = await resources.listResources(routeName);
|
|
451
|
+
const body = JSON.stringify({
|
|
452
|
+
routeName,
|
|
453
|
+
resources: resourcesList.map((resource) => metadataWithoutBody(resource))
|
|
454
|
+
});
|
|
455
|
+
const headers = new Headers({
|
|
456
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
457
|
+
'Content-Length': String(new TextEncoder().encode(body).byteLength),
|
|
458
|
+
'Cache-Control': 'no-store'
|
|
459
|
+
});
|
|
460
|
+
logResource(options, {
|
|
461
|
+
event: 'resource.list',
|
|
462
|
+
routeName,
|
|
463
|
+
status: 200
|
|
464
|
+
});
|
|
465
|
+
return new Response(headOnly ? null : body, { status: 200, headers });
|
|
466
|
+
}
|
|
467
|
+
async function handleResourcePut(request, routeName, resourceName, resources, options) {
|
|
468
|
+
if (!resources.putResource)
|
|
469
|
+
return jsonResponse({ error: 'not_supported' }, 405, { Allow: 'GET, HEAD' });
|
|
470
|
+
if (!(await authorize(options, request, 'put', routeName, resourceName))) {
|
|
471
|
+
return jsonResponse({ error: 'forbidden' }, 403);
|
|
472
|
+
}
|
|
473
|
+
const mimeType = request.headers.get('content-type')?.split(';', 1)[0]?.trim() || 'application/octet-stream';
|
|
474
|
+
const supported = await resources.isSupportedResourceType?.(mimeType);
|
|
475
|
+
if (supported === false)
|
|
476
|
+
return jsonResponse({ error: 'unsupported_media_type' }, 415);
|
|
477
|
+
const maxBytes = options.maxResourceBodyBytes ?? DEFAULT_MAX_RESOURCE_BODY_BYTES;
|
|
478
|
+
const contentLength = request.headers.get('content-length');
|
|
479
|
+
if (contentLength !== null && Number.parseInt(contentLength, 10) > maxBytes) {
|
|
480
|
+
return jsonResponse({ error: 'payload_too_large' }, 413);
|
|
481
|
+
}
|
|
482
|
+
const bytes = await readBodyWithLimit(request, maxBytes);
|
|
483
|
+
if (bytes === null)
|
|
484
|
+
return jsonResponse({ error: 'payload_too_large' }, 413);
|
|
485
|
+
const result = await resources.putResource({ routeName, resourceName, mimeType, bytes });
|
|
486
|
+
logResource(options, {
|
|
487
|
+
event: 'resource.put',
|
|
488
|
+
routeName,
|
|
489
|
+
resourceName,
|
|
490
|
+
mimeType,
|
|
491
|
+
byteLength: bytes.byteLength,
|
|
492
|
+
status: result.created ? 201 : 204
|
|
493
|
+
});
|
|
494
|
+
if (result.created) {
|
|
495
|
+
return new Response(null, {
|
|
496
|
+
status: 201,
|
|
497
|
+
headers: { Location: resourceLocation(routeName, resourceName) }
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
return new Response(null, { status: 204 });
|
|
501
|
+
}
|
|
502
|
+
async function handleResourceDelete(request, routeName, resourceName, resources, options) {
|
|
503
|
+
if (!resources.deleteResource)
|
|
504
|
+
return jsonResponse({ error: 'not_supported' }, 405, { Allow: 'GET, HEAD, PUT' });
|
|
505
|
+
if (!(await authorize(options, request, 'delete', routeName, resourceName))) {
|
|
506
|
+
return jsonResponse({ error: 'forbidden' }, 403);
|
|
507
|
+
}
|
|
508
|
+
const removed = await resources.deleteResource(routeName, resourceName);
|
|
509
|
+
logResource(options, {
|
|
510
|
+
event: 'resource.delete',
|
|
511
|
+
routeName,
|
|
512
|
+
resourceName,
|
|
513
|
+
status: removed ? 204 : 404
|
|
514
|
+
});
|
|
515
|
+
return removed ? new Response(null, { status: 204 }) : jsonResponse({ error: 'not_found' }, 404);
|
|
516
|
+
}
|
|
517
|
+
function parseResourceRoute(pathname) {
|
|
518
|
+
const rawSegments = pathname.split('/').filter((segment) => segment.length > 0);
|
|
519
|
+
const segments = rawSegments.map(decodePathSegment);
|
|
520
|
+
if (segments[0] === '_tw-http') {
|
|
521
|
+
return { routeName: '', resourceName: '', listing: false, managementNamespace: true };
|
|
522
|
+
}
|
|
523
|
+
const assetIndex = segments.indexOf('@assets');
|
|
524
|
+
if (assetIndex < 0)
|
|
525
|
+
return null;
|
|
526
|
+
if (assetIndex !== 0) {
|
|
527
|
+
return { routeName: '', resourceName: '', listing: false, managementNamespace: true };
|
|
528
|
+
}
|
|
529
|
+
const routeName = '';
|
|
530
|
+
const resourceSegments = segments.slice(1);
|
|
531
|
+
const listing = resourceSegments.length === 0;
|
|
532
|
+
const resourceName = resourceSegments.join('/');
|
|
533
|
+
if (!listing && resourceName.length === 0)
|
|
534
|
+
return null;
|
|
535
|
+
return { routeName, resourceName, listing, managementNamespace: false };
|
|
536
|
+
}
|
|
537
|
+
function decodePathSegment(segment) {
|
|
538
|
+
try {
|
|
539
|
+
return decodeURIComponent(segment);
|
|
540
|
+
}
|
|
541
|
+
catch {
|
|
542
|
+
return segment;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
function resourceHeaders(snapshot) {
|
|
546
|
+
const headers = new Headers({
|
|
547
|
+
'Content-Type': snapshot.mimeType,
|
|
548
|
+
'Content-Length': String(getByteLength(snapshot)),
|
|
549
|
+
'Cache-Control': snapshot.cacheControl ?? defaultCacheControl(snapshot)
|
|
550
|
+
});
|
|
551
|
+
const etag = getEtag(snapshot);
|
|
552
|
+
if (etag)
|
|
553
|
+
headers.set('ETag', etag);
|
|
554
|
+
if (snapshot.lastModified)
|
|
555
|
+
headers.set('Last-Modified', snapshot.lastModified.toUTCString());
|
|
556
|
+
return headers;
|
|
557
|
+
}
|
|
558
|
+
function getByteLength(snapshot) {
|
|
559
|
+
return snapshot.bytes.byteLength;
|
|
560
|
+
}
|
|
561
|
+
function getEtag(snapshot) {
|
|
562
|
+
const identity = snapshot.etag ?? snapshot.replacementId;
|
|
563
|
+
if (!identity)
|
|
564
|
+
return undefined;
|
|
565
|
+
if (/^(W\/)?"[^"]*"$/.test(identity))
|
|
566
|
+
return identity;
|
|
567
|
+
return `"${identity.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
568
|
+
}
|
|
569
|
+
function defaultCacheControl(snapshot) {
|
|
570
|
+
return snapshot.etag || snapshot.replacementId || snapshot.lastModified ? 'no-cache' : 'no-store';
|
|
571
|
+
}
|
|
572
|
+
function isNotModified(request, headers) {
|
|
573
|
+
const responseEtag = headers.get('ETag');
|
|
574
|
+
const requestEtags = request.headers.get('if-none-match');
|
|
575
|
+
if (responseEtag && requestEtags) {
|
|
576
|
+
return requestEtags
|
|
577
|
+
.split(',')
|
|
578
|
+
.map((value) => value.trim())
|
|
579
|
+
.some((value) => value === '*' || value === responseEtag);
|
|
580
|
+
}
|
|
581
|
+
const lastModified = headers.get('Last-Modified');
|
|
582
|
+
const ifModifiedSince = request.headers.get('if-modified-since');
|
|
583
|
+
if (!lastModified || !ifModifiedSince)
|
|
584
|
+
return false;
|
|
585
|
+
return Date.parse(ifModifiedSince) >= Date.parse(lastModified);
|
|
586
|
+
}
|
|
587
|
+
async function readBodyWithLimit(request, maxBytes) {
|
|
588
|
+
if (!request.body)
|
|
589
|
+
return new Uint8Array();
|
|
590
|
+
const reader = request.body.getReader();
|
|
591
|
+
const chunks = [];
|
|
592
|
+
let total = 0;
|
|
593
|
+
while (true) {
|
|
594
|
+
const { done, value } = await reader.read();
|
|
595
|
+
if (done)
|
|
596
|
+
break;
|
|
597
|
+
total += value.byteLength;
|
|
598
|
+
if (total > maxBytes) {
|
|
599
|
+
await reader.cancel();
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
chunks.push(value);
|
|
603
|
+
}
|
|
604
|
+
const result = new Uint8Array(total);
|
|
605
|
+
let offset = 0;
|
|
606
|
+
for (const chunk of chunks) {
|
|
607
|
+
result.set(chunk, offset);
|
|
608
|
+
offset += chunk.byteLength;
|
|
609
|
+
}
|
|
610
|
+
return result;
|
|
611
|
+
}
|
|
612
|
+
async function authorize(options, request, operation, routeName, resourceName) {
|
|
613
|
+
return (await options.authorizeResource?.(request, operation, routeName, resourceName)) !== false;
|
|
614
|
+
}
|
|
615
|
+
function metadataWithoutBody(resource) {
|
|
616
|
+
const metadata = {
|
|
617
|
+
name: resource.name,
|
|
618
|
+
mimeType: resource.mimeType
|
|
619
|
+
};
|
|
620
|
+
if (resource.byteLength !== undefined)
|
|
621
|
+
metadata.byteLength = resource.byteLength;
|
|
622
|
+
if (resource.etag !== undefined)
|
|
623
|
+
metadata.etag = resource.etag;
|
|
624
|
+
if (resource.replacementId !== undefined)
|
|
625
|
+
metadata.replacementId = resource.replacementId;
|
|
626
|
+
if (resource.lastModified !== undefined)
|
|
627
|
+
metadata.lastModified = resource.lastModified;
|
|
628
|
+
if (resource.cacheControl !== undefined)
|
|
629
|
+
metadata.cacheControl = resource.cacheControl;
|
|
630
|
+
return metadata;
|
|
631
|
+
}
|
|
632
|
+
function resourceLocation(routeName, resourceName) {
|
|
633
|
+
const encodedName = resourceName.split('/').map(encodeURIComponent).join('/');
|
|
634
|
+
return routeName === '' ? `/@assets/${encodedName}` : `/${encodeURIComponent(routeName)}/${encodedName}`;
|
|
635
|
+
}
|
|
636
|
+
function methodNotAllowed(methods) {
|
|
637
|
+
return jsonResponse({ error: 'method_not_allowed' }, 405, { Allow: methods.join(', ') });
|
|
638
|
+
}
|
|
639
|
+
function jsonResponse(body, status, headers) {
|
|
640
|
+
const responseHeaders = new Headers(headers);
|
|
641
|
+
responseHeaders.set('Content-Type', 'application/json; charset=utf-8');
|
|
642
|
+
return new Response(JSON.stringify(body), { status, headers: responseHeaders });
|
|
643
|
+
}
|
|
644
|
+
function logResource(options, event) {
|
|
645
|
+
options.logger?.info(event);
|
|
646
|
+
}
|
|
647
|
+
function toArrayBuffer(bytes) {
|
|
648
|
+
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
649
|
+
}
|
|
650
|
+
//# sourceMappingURL=server.js.map
|