keryx 0.41.3 → 0.42.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/actions/swagger.ts +14 -6
- package/classes/Action.ts +18 -0
- package/classes/Connection.ts +10 -0
- package/initializers/hooks.ts +4 -0
- package/package.json +1 -1
- package/servers/web.ts +37 -10
- package/util/webRouting.ts +43 -9
package/actions/swagger.ts
CHANGED
|
@@ -129,11 +129,13 @@ export class Swagger implements Action {
|
|
|
129
129
|
});
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
-
//
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
132
|
+
// Endpoints whose inputs never come from the body: GET/HEAD, and raw-body
|
|
133
|
+
// actions (whose bodies Keryx hands to the action instead of parsing).
|
|
134
|
+
const inputsFromQuery =
|
|
135
|
+
method === "get" || method === "head" || action.web?.rawBody === true;
|
|
136
|
+
|
|
137
|
+
// Convert remaining Zod inputs into query parameters
|
|
138
|
+
if (inputsFromQuery && Object.keys(zodProperties).length > 0) {
|
|
137
139
|
const fullSchema = z.toJSONSchema(action.inputs!, {
|
|
138
140
|
io: "input",
|
|
139
141
|
unrepresentable: "any",
|
|
@@ -157,7 +159,13 @@ export class Swagger implements Action {
|
|
|
157
159
|
|
|
158
160
|
// Build requestBody if Zod inputs exist and method supports body
|
|
159
161
|
let requestBody: Record<string, unknown> | undefined = undefined;
|
|
160
|
-
if (
|
|
162
|
+
if (action.web?.rawBody && method !== "get" && method !== "head") {
|
|
163
|
+
// The body is opaque to the framework — document it as arbitrary bytes
|
|
164
|
+
requestBody = {
|
|
165
|
+
required: false,
|
|
166
|
+
content: { "*/*": { schema: { type: "string", format: "binary" } } },
|
|
167
|
+
};
|
|
168
|
+
} else if (
|
|
161
169
|
action.inputs &&
|
|
162
170
|
typeof action.inputs.parse === "function" &&
|
|
163
171
|
method !== "get" &&
|
package/classes/Action.ts
CHANGED
|
@@ -168,6 +168,22 @@ export type ActionConstructorInputs = {
|
|
|
168
168
|
* set this when the action hands back a raw `Response` wrapping a stream.
|
|
169
169
|
*/
|
|
170
170
|
streaming?: boolean;
|
|
171
|
+
/**
|
|
172
|
+
* When true, the framework never reads the request body. `params` are built
|
|
173
|
+
* from path and query params only, and the action reads the untouched body
|
|
174
|
+
* itself via `connection.rawRequest` (`.text()`, `.arrayBuffer()`,
|
|
175
|
+
* `.body` for a stream). Use this for proxies, webhook signature
|
|
176
|
+
* verification, and binary uploads — anything that needs the bytes exactly
|
|
177
|
+
* as sent, or needs to avoid buffering them twice.
|
|
178
|
+
*
|
|
179
|
+
* Because the body is never merged into `params`, a body key that collides
|
|
180
|
+
* with a path param cannot override it.
|
|
181
|
+
*
|
|
182
|
+
* `config.server.web.maxBodySize` is still enforced against the
|
|
183
|
+
* `Content-Length` header, but not while the action reads the stream — an
|
|
184
|
+
* action consuming a chunked body owns that limit itself.
|
|
185
|
+
*/
|
|
186
|
+
rawBody?: boolean;
|
|
171
187
|
};
|
|
172
188
|
|
|
173
189
|
/** Per-action timeout in ms (overrides global `config.actions.timeout`; 0 disables) */
|
|
@@ -232,6 +248,7 @@ export abstract class Action {
|
|
|
232
248
|
route: RegExp | string;
|
|
233
249
|
method: HTTP_METHOD;
|
|
234
250
|
streaming?: boolean;
|
|
251
|
+
rawBody?: boolean;
|
|
235
252
|
};
|
|
236
253
|
timeout?: number;
|
|
237
254
|
task?: {
|
|
@@ -251,6 +268,7 @@ export abstract class Action {
|
|
|
251
268
|
route: args.web?.route ?? `/${this.name}`,
|
|
252
269
|
method: args.web?.method ?? HTTP_METHOD.GET,
|
|
253
270
|
streaming: args.web?.streaming ?? false,
|
|
271
|
+
rawBody: args.web?.rawBody ?? false,
|
|
254
272
|
};
|
|
255
273
|
this.task = {
|
|
256
274
|
frequency: args.task?.frequency,
|
package/classes/Connection.ts
CHANGED
|
@@ -112,6 +112,16 @@ export class Connection<
|
|
|
112
112
|
sessionLoaded: boolean;
|
|
113
113
|
/** The underlying transport handle (e.g., Bun `ServerWebSocket`). */
|
|
114
114
|
rawConnection?: any;
|
|
115
|
+
/**
|
|
116
|
+
* The underlying `Request` for HTTP connections (`type === CONNECTION_TYPE.WEB`),
|
|
117
|
+
* giving actions access to headers, URL, and body. `undefined` for every other
|
|
118
|
+
* transport.
|
|
119
|
+
*
|
|
120
|
+
* The **body** is only readable when the action declares `web.rawBody: true` —
|
|
121
|
+
* otherwise the framework has already consumed it to build `params`, and
|
|
122
|
+
* `rawRequest.text()` resolves to `""`. Headers are always safe to read.
|
|
123
|
+
*/
|
|
124
|
+
rawRequest?: Request;
|
|
115
125
|
/** Rate-limit metadata populated by the rate-limit middleware. */
|
|
116
126
|
rateLimitInfo?: RateLimitInfo;
|
|
117
127
|
/** Request correlation ID for distributed tracing. Propagated from the incoming `X-Request-Id` header when `config.server.web.correlationId.trustProxy` is enabled. */
|
package/initializers/hooks.ts
CHANGED
|
@@ -60,6 +60,10 @@ export class Hooks extends Initializer {
|
|
|
60
60
|
* Register a hook to run at the start of every HTTP request, before
|
|
61
61
|
* routing. Covers static files, OAuth, MCP, metrics, and actions.
|
|
62
62
|
* Does not fire for WebSocket upgrades.
|
|
63
|
+
*
|
|
64
|
+
* A hook that returns a `Response` answers the request itself: later
|
|
65
|
+
* `beforeRequest` hooks and all routing are skipped, while
|
|
66
|
+
* `afterRequest` hooks still fire.
|
|
63
67
|
*/
|
|
64
68
|
beforeRequest(hook: BeforeRequestHook): void {
|
|
65
69
|
self.webBeforeRequest.push(hook);
|
package/package.json
CHANGED
package/servers/web.ts
CHANGED
|
@@ -70,11 +70,17 @@ export interface RequestOutcome {
|
|
|
70
70
|
* Runs at the start of every HTTP request, before any routing or static file handling.
|
|
71
71
|
* WebSocket upgrades do not fire this hook. Throwing an error propagates out of the
|
|
72
72
|
* request handler. Hooks run sequentially in registration order.
|
|
73
|
+
*
|
|
74
|
+
* Returning a `Response` **short-circuits** the request: no later `beforeRequest` hook
|
|
75
|
+
* runs, routing (static files, OAuth, MCP, metrics, actions) is skipped, and the returned
|
|
76
|
+
* response is what the client receives. `afterRequest` hooks still fire, with
|
|
77
|
+
* `outcome.actionName` unset, and the response is still compressed. Return nothing — the
|
|
78
|
+
* common case — to let the request continue down the pipeline.
|
|
73
79
|
*/
|
|
74
80
|
export type BeforeRequestHook = (
|
|
75
81
|
req: Request,
|
|
76
82
|
ctx: RequestContext,
|
|
77
|
-
) => Promise<void> | void;
|
|
83
|
+
) => Promise<Response | void> | Response | void;
|
|
78
84
|
|
|
79
85
|
/**
|
|
80
86
|
* Runs after the `Response` is built and before compression. Receives the same `ctx`
|
|
@@ -232,7 +238,8 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
|
|
|
232
238
|
|
|
233
239
|
/**
|
|
234
240
|
* Main request handler passed to `Bun.serve({ fetch })`. Dispatches to WebSocket upgrade,
|
|
235
|
-
* static files, OAuth, MCP, or REST action handling in that order.
|
|
241
|
+
* static files, OAuth, MCP, or REST action handling in that order. A `beforeRequest` hook
|
|
242
|
+
* that returns a `Response` short-circuits everything after it.
|
|
236
243
|
*/
|
|
237
244
|
async handleIncomingConnection(
|
|
238
245
|
req: Request,
|
|
@@ -268,16 +275,24 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
|
|
|
268
275
|
|
|
269
276
|
const ctx: RequestContext = { ip, id, metadata: {} };
|
|
270
277
|
const requestStart = Date.now();
|
|
278
|
+
|
|
279
|
+
// A `beforeRequest` hook that returns a Response answers the request itself —
|
|
280
|
+
// remaining hooks and all routing are skipped, but `afterRequest` still fires.
|
|
281
|
+
let response: Response | undefined;
|
|
282
|
+
let actionName: string | undefined;
|
|
271
283
|
for (const hook of api.hooks.web.beforeRequestHooks) {
|
|
272
|
-
await hook(req, ctx);
|
|
284
|
+
const hookResponse = await hook(req, ctx);
|
|
285
|
+
if (hookResponse instanceof Response) {
|
|
286
|
+
response = hookResponse;
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
273
289
|
}
|
|
274
290
|
|
|
275
|
-
|
|
276
|
-
req,
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
);
|
|
291
|
+
if (!response) {
|
|
292
|
+
const routed = await this.handleHttpRequest(req, server, ip, id);
|
|
293
|
+
response = routed.response;
|
|
294
|
+
actionName = routed.actionName;
|
|
295
|
+
}
|
|
281
296
|
|
|
282
297
|
const outcome: RequestOutcome = {
|
|
283
298
|
method: req.method.toUpperCase(),
|
|
@@ -537,6 +552,10 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
|
|
|
537
552
|
|
|
538
553
|
const connection = new Connection(CONNECTION_TYPE.WEB, ip, id);
|
|
539
554
|
|
|
555
|
+
// Expose the underlying request so actions can read headers and — when the
|
|
556
|
+
// action declares `web.rawBody` — the untouched body.
|
|
557
|
+
connection.rawRequest = req;
|
|
558
|
+
|
|
540
559
|
if (
|
|
541
560
|
config.server.web.correlationId.header &&
|
|
542
561
|
config.server.web.correlationId.trustProxy
|
|
@@ -574,9 +593,17 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
|
|
|
574
593
|
);
|
|
575
594
|
if (!actionName) errorStatusCode = 404;
|
|
576
595
|
|
|
596
|
+
// Actions that opt into `web.rawBody` read the body themselves off
|
|
597
|
+
// `connection.rawRequest`, so param parsing must leave it unread.
|
|
598
|
+
const rawBody =
|
|
599
|
+
api.actions.actions.find((a) => a.name === actionName)?.web?.rawBody ===
|
|
600
|
+
true;
|
|
601
|
+
|
|
577
602
|
let params: Record<string, unknown>;
|
|
578
603
|
try {
|
|
579
|
-
params = await parseRequestParams(req, url, pathParams ?? undefined
|
|
604
|
+
params = await parseRequestParams(req, url, pathParams ?? undefined, {
|
|
605
|
+
rawBody,
|
|
606
|
+
});
|
|
580
607
|
} catch (e) {
|
|
581
608
|
if (
|
|
582
609
|
e instanceof TypedError &&
|
package/util/webRouting.ts
CHANGED
|
@@ -112,6 +112,21 @@ async function readBodyWithLimit(req: Request): Promise<string> {
|
|
|
112
112
|
return new TextDecoder().decode(merged);
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Extract the base media type from a request's `Content-Type` header — the
|
|
117
|
+
* `type/subtype` with parameters stripped, trimmed, and lowercased. So
|
|
118
|
+
* `"application/json; charset=utf-8"` and `"Application/JSON"` both yield
|
|
119
|
+
* `"application/json"`.
|
|
120
|
+
*
|
|
121
|
+
* @param req - The incoming HTTP request.
|
|
122
|
+
* @returns The base media type, or `null` when the header is absent.
|
|
123
|
+
*/
|
|
124
|
+
export function baseMediaType(req: Request): string | null {
|
|
125
|
+
const header = req.headers.get("content-type");
|
|
126
|
+
if (header === null) return null;
|
|
127
|
+
return header.split(";")[0].trim().toLowerCase();
|
|
128
|
+
}
|
|
129
|
+
|
|
115
130
|
/**
|
|
116
131
|
* Merge a value into the params object under `key`, appending to any existing
|
|
117
132
|
* value rather than replacing it. If `key` is not set, assigns `value` as-is.
|
|
@@ -134,6 +149,17 @@ function appendParam(
|
|
|
134
149
|
: [params[key], ...incoming];
|
|
135
150
|
}
|
|
136
151
|
|
|
152
|
+
/** Options for {@link parseRequestParams}. */
|
|
153
|
+
export type ParseRequestParamsOptions = {
|
|
154
|
+
/**
|
|
155
|
+
* Skip body parsing entirely, leaving `req.body` unread so the action can
|
|
156
|
+
* consume it itself via `connection.rawRequest`. Path params and query params
|
|
157
|
+
* still populate. Set by the web server when the routed action declares
|
|
158
|
+
* `web.rawBody: true`.
|
|
159
|
+
*/
|
|
160
|
+
rawBody?: boolean;
|
|
161
|
+
};
|
|
162
|
+
|
|
137
163
|
/**
|
|
138
164
|
* Parse request parameters from path params, request body (JSON or form-data),
|
|
139
165
|
* and query string into a single plain object.
|
|
@@ -141,17 +167,26 @@ function appendParam(
|
|
|
141
167
|
* JSON bodies are preserved with full type fidelity (nested objects, arrays,
|
|
142
168
|
* booleans, numbers). FormData bodies (multipart/form-data and
|
|
143
169
|
* application/x-www-form-urlencoded) are converted to a plain object where
|
|
144
|
-
* repeated keys become arrays and `File` values are preserved.
|
|
170
|
+
* repeated keys become arrays and `File` values are preserved. Content types are
|
|
171
|
+
* matched on the base media type, so parameters like `; charset=utf-8` do not
|
|
172
|
+
* change how a body is handled.
|
|
145
173
|
*
|
|
146
174
|
* @param req - The incoming HTTP request.
|
|
147
175
|
* @param url - The parsed URL (for query string).
|
|
148
176
|
* @param pathParams - Path parameters extracted by route matching.
|
|
177
|
+
* @param options - Parsing options. Pass `{ rawBody: true }` to leave the body
|
|
178
|
+
* unread — nothing is consumed off `req`, so a later reader (typically the
|
|
179
|
+
* action, via `connection.rawRequest`) still sees the bytes exactly as sent.
|
|
149
180
|
* @returns A plain object containing all merged parameters.
|
|
181
|
+
* @throws {TypedError} With type {@link ErrorType.CONNECTION_ACTION_RUN} when a
|
|
182
|
+
* JSON body cannot be parsed, or when the body exceeds
|
|
183
|
+
* {@link config.server.web.maxBodySize}.
|
|
150
184
|
*/
|
|
151
185
|
export async function parseRequestParams(
|
|
152
186
|
req: Request,
|
|
153
187
|
url: ReturnType<typeof parse>,
|
|
154
188
|
pathParams?: Record<string, string>,
|
|
189
|
+
options?: ParseRequestParamsOptions,
|
|
155
190
|
): Promise<Record<string, unknown>> {
|
|
156
191
|
// param load order: path params -> body params -> query params
|
|
157
192
|
const params: Record<string, unknown> = {};
|
|
@@ -163,10 +198,11 @@ export async function parseRequestParams(
|
|
|
163
198
|
}
|
|
164
199
|
}
|
|
165
200
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
201
|
+
// Raw-body actions own the body — resolve the content type to null so both
|
|
202
|
+
// body-reading branches are skipped and `req.body` is left untouched.
|
|
203
|
+
const contentType = options?.rawBody ? null : baseMediaType(req);
|
|
204
|
+
|
|
205
|
+
if (req.method !== "GET" && contentType === "application/json") {
|
|
170
206
|
try {
|
|
171
207
|
// Use streaming reader that aborts early if the body exceeds the
|
|
172
208
|
// configured limit — never allocates the full oversized payload.
|
|
@@ -186,10 +222,8 @@ export async function parseRequestParams(
|
|
|
186
222
|
}
|
|
187
223
|
} else if (
|
|
188
224
|
req.method !== "GET" &&
|
|
189
|
-
(
|
|
190
|
-
|
|
191
|
-
.get("content-type")
|
|
192
|
-
?.includes("application/x-www-form-urlencoded"))
|
|
225
|
+
(contentType === "multipart/form-data" ||
|
|
226
|
+
contentType === "application/x-www-form-urlencoded")
|
|
193
227
|
) {
|
|
194
228
|
// For form data without a Content-Length header, stream-read the clone
|
|
195
229
|
// to enforce the body size limit before handing off to the FormData parser.
|