@orpc/node 2.0.0-beta.46 → 2.0.0-beta.48

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.
@@ -0,0 +1,60 @@
1
+ import { Buffer } from "node:buffer";
2
+ export interface MultipartPart {
3
+ /**
4
+ * The `name` parameter of the part's `Content-Disposition` header, with the
5
+ * serialization escapes of `"`, `\r`, and `\n` decoded.
6
+ */
7
+ name: string;
8
+ /**
9
+ * The `filename` parameter of the part's `Content-Disposition` header,
10
+ * decoded like `name`, or `undefined` when the part is a plain field. An
11
+ * empty string is a file part, matching how browsers submit an empty file
12
+ * input.
13
+ */
14
+ filename: string | undefined;
15
+ /**
16
+ * The part's `Content-Type` header value, if present.
17
+ */
18
+ type: string | undefined;
19
+ /**
20
+ * The size in bytes of the part's header block, including the blank line.
21
+ */
22
+ headerSize: number;
23
+ }
24
+ export interface MultipartPartWriter {
25
+ /**
26
+ * Receives one chunk of the part's body. The chunk is only valid until the
27
+ * returned promise resolves, so it must be consumed or copied synchronously.
28
+ */
29
+ write(chunk: Buffer): void | Promise<void>;
30
+ /**
31
+ * Called once after the part's final chunk.
32
+ */
33
+ end(): void | Promise<void>;
34
+ }
35
+ /**
36
+ * Parses a `multipart/form-data` byte stream part by part, so a part's body can be
37
+ * consumed as it arrives instead of being buffered whole. Bodies are delivered to the
38
+ * writer `onPart` returns, with writer promises awaited for backpressure, so parts are
39
+ * processed strictly one at a time.
40
+ *
41
+ * Line endings are strictly CRLF, every part must carry a `form-data` content
42
+ * disposition with a `name` parameter, and a malformed or truncated body throws a
43
+ * `TypeError`, matching the standard parser's strictness.
44
+ *
45
+ * @see https://www.rfc-editor.org/rfc/rfc7578
46
+ * @see https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1
47
+ */
48
+ export declare function parseMultipart(source: ReadableStream<Uint8Array>, boundary: string, onPart: (part: MultipartPart) => MultipartPartWriter | Promise<MultipartPartWriter>): Promise<void>;
49
+ /**
50
+ * Extracts the `key=value` parameters that follow a header's leading token.
51
+ * The first occurrence of a parameter wins.
52
+ *
53
+ * A backslash inside a quoted value is a literal character rather than an
54
+ * escape, matching the standard parser: the multipart serialization escapes
55
+ * `"` as `%22`, so a quote can never occur inside a value, while filenames
56
+ * with literal backslashes are common and must survive verbatim.
57
+ *
58
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm
59
+ */
60
+ export declare function parseHeaderParameters(header: string): Map<string, string>;
@@ -0,0 +1,179 @@
1
+ import { Buffer } from "node:buffer";
2
+
3
+ const MAX_PART_HEADER_SIZE = 16 * 1024;
4
+ const CRLF = /* @__PURE__ */ Buffer.from("\r\n");
5
+ const HEADER_BLOCK_END = /* @__PURE__ */ Buffer.from("\r\n\r\n");
6
+
7
+ export async function parseMultipart(source, boundary, onPart) {
8
+ const delimiter = Buffer.from(`\r\n--${boundary}`);
9
+
10
+ let buffer = CRLF;
11
+ let state = "preamble";
12
+ let writer;
13
+ let done = false;
14
+ const process = async () => {
15
+ while (true) {
16
+ if (state === "preamble" || state === "body") {
17
+ const index = buffer.indexOf(delimiter);
18
+ if (index === -1) {
19
+
20
+ const settledLength = buffer.length - delimiter.length + 1;
21
+ if (settledLength > 0) {
22
+ if (state === "body") {
23
+ await writer.write(buffer.subarray(0, settledLength));
24
+ }
25
+ buffer = buffer.subarray(settledLength);
26
+ }
27
+ return;
28
+ }
29
+ if (state === "body") {
30
+ if (index > 0) {
31
+ await writer.write(buffer.subarray(0, index));
32
+ }
33
+ await writer.end();
34
+ writer = undefined;
35
+ }
36
+ buffer = buffer.subarray(index + delimiter.length);
37
+ state = "delimiter-end";
38
+ continue;
39
+ }
40
+ if (state === "delimiter-end") {
41
+ if (buffer.length < 2) {
42
+ return;
43
+ }
44
+
45
+ if (buffer[0] === 45 && buffer[1] === 45) {
46
+ done = true;
47
+ buffer = Buffer.alloc(0);
48
+ return;
49
+ }
50
+ state = "transport-padding";
51
+ continue;
52
+ }
53
+ if (state === "transport-padding") {
54
+ let index = 0;
55
+ while (index < buffer.length && (buffer[index] === 32 || buffer[index] === 9)) {
56
+ index++;
57
+ }
58
+ buffer = buffer.subarray(index);
59
+ if (buffer.length < 2) {
60
+ return;
61
+ }
62
+ if (buffer[0] !== 13 || buffer[1] !== 10) {
63
+ throw new TypeError("Invalid multipart body: expected CRLF after a boundary delimiter");
64
+ }
65
+ buffer = buffer.subarray(2);
66
+ state = "headers";
67
+ continue;
68
+ }
69
+
70
+ if (buffer[0] === 13 && buffer[1] === 10) {
71
+ throw new TypeError("Invalid multipart body: part is missing the content-disposition header");
72
+ }
73
+ const headerWindow = MAX_PART_HEADER_SIZE + HEADER_BLOCK_END.length;
74
+ const headerEnd = buffer.subarray(0, headerWindow).indexOf(HEADER_BLOCK_END);
75
+ if (headerEnd === -1) {
76
+ if (buffer.length >= headerWindow) {
77
+ throw new TypeError("Invalid multipart body: part headers exceed the maximum allowed size");
78
+ }
79
+ return;
80
+ }
81
+ const headerSize = headerEnd + HEADER_BLOCK_END.length;
82
+ const part = parsePartHeaders(buffer.subarray(0, headerEnd).toString(), headerSize);
83
+ buffer = buffer.subarray(headerSize);
84
+ writer = await onPart(part);
85
+ state = "body";
86
+ }
87
+ };
88
+ for await (const chunk of source) {
89
+ if (done) {
90
+ continue;
91
+ }
92
+
93
+ buffer = buffer.length === 0 ? Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) : Buffer.concat([buffer, chunk]);
94
+ await process();
95
+ }
96
+ if (!done) {
97
+ throw new TypeError("Invalid multipart body: unexpected end of body");
98
+ }
99
+ }
100
+ function parsePartHeaders(block, headerSize) {
101
+ let contentDisposition;
102
+ let contentType;
103
+ for (const line of block.split("\r\n")) {
104
+ const colon = line.indexOf(":");
105
+ if (colon === -1) {
106
+ throw new TypeError("Invalid multipart body: malformed part header");
107
+ }
108
+ const name = line.slice(0, colon).trim().toLowerCase();
109
+ if (name === "content-disposition") {
110
+ contentDisposition = line.slice(colon + 1).trim();
111
+ } else if (name === "content-type") {
112
+ contentType = line.slice(colon + 1).trim();
113
+ }
114
+ }
115
+ if (contentDisposition === undefined) {
116
+ throw new TypeError("Invalid multipart body: part is missing the content-disposition header");
117
+ }
118
+
119
+ const semicolon = contentDisposition.indexOf(";");
120
+ const dispositionType = (semicolon === -1 ? contentDisposition : contentDisposition.slice(0, semicolon)).trim().toLowerCase();
121
+ if (dispositionType !== "form-data") {
122
+ throw new TypeError("Invalid multipart body: content-disposition must be form-data");
123
+ }
124
+ const parameters = parseHeaderParameters(contentDisposition);
125
+ const name = parameters.get("name");
126
+ if (name === undefined) {
127
+ throw new TypeError("Invalid multipart body: content-disposition header is missing the name parameter");
128
+ }
129
+ const filename = parameters.get("filename");
130
+ return {
131
+ name: decodeContentDispositionParameter(name),
132
+ filename: filename === undefined ? undefined : decodeContentDispositionParameter(filename),
133
+ type: contentType,
134
+ headerSize
135
+ };
136
+ }
137
+
138
+ function decodeContentDispositionParameter(value) {
139
+ return value.replaceAll("%22", "\"").replaceAll("%0D", "\r").replaceAll("%0A", "\n");
140
+ }
141
+
142
+ export function parseHeaderParameters(header) {
143
+ const parameters = new Map();
144
+ let index = header.indexOf(";");
145
+ while (index !== -1 && index < header.length) {
146
+ index++;
147
+ while (index < header.length && (header[index] === " " || header[index] === " ")) {
148
+ index++;
149
+ }
150
+ let equals = index;
151
+ while (equals < header.length && header[equals] !== "=" && header[equals] !== ";") {
152
+ equals++;
153
+ }
154
+ if (equals === header.length) {
155
+ break;
156
+ }
157
+
158
+ if (header[equals] === ";") {
159
+ index = equals;
160
+ continue;
161
+ }
162
+ const key = header.slice(index, equals).trim().toLowerCase();
163
+ index = equals + 1;
164
+ let value;
165
+ if (header[index] === "\"") {
166
+ const closing = header.indexOf("\"", index + 1);
167
+ value = closing === -1 ? header.slice(index + 1) : header.slice(index + 1, closing);
168
+ index = closing === -1 ? -1 : header.indexOf(";", closing + 1);
169
+ } else {
170
+ const semicolon = header.indexOf(";", index);
171
+ value = (semicolon === -1 ? header.slice(index) : header.slice(index, semicolon)).trim();
172
+ index = semicolon;
173
+ }
174
+ if (!parameters.has(key)) {
175
+ parameters.set(key, value);
176
+ }
177
+ }
178
+ return parameters;
179
+ }
@@ -0,0 +1,133 @@
1
+ import type { Context } from "@orpc/server";
2
+ import type { StandardHandlerOptions, StandardHandlerPlugin } from "@orpc/server/standard";
3
+ export interface StaticFileHandlerPluginOptions {
4
+ /**
5
+ * The directory files are served from. Resolved against the working
6
+ * directory when relative.
7
+ */
8
+ rootDir: string;
9
+ /**
10
+ * The URL path files are served under, appended to the handler prefix
11
+ * when one is set.
12
+ *
13
+ * @default '/'
14
+ */
15
+ path?: `/${string}` | undefined;
16
+ /**
17
+ * The file served when the request path resolves to a directory.
18
+ * Set to `false` to disable directory index files.
19
+ *
20
+ * @default 'index.html'
21
+ */
22
+ indexFile?: string | false | undefined;
23
+ /**
24
+ * A file served with status 200 when no file matches the request path,
25
+ * relative to `rootDir`. Useful for single-page application routing.
26
+ *
27
+ * @default undefined
28
+ */
29
+ fallbackFile?: string | undefined;
30
+ /**
31
+ * The `Cache-Control` response header value. Set to `false` to omit the header.
32
+ *
33
+ * @default 'public, max-age=0'
34
+ */
35
+ cacheControl?: string | false | undefined;
36
+ /**
37
+ * Whether files and directories whose name starts with a dot can be served.
38
+ * When disabled, names shaped like 8.3 short names, such as `ENV~1`, are refused too,
39
+ * since NTFS and FAT resolve them to dotfiles.
40
+ *
41
+ * @default false
42
+ */
43
+ dotfiles?: boolean | undefined;
44
+ /**
45
+ * Whether precompressed sidecar files (`.br`, `.zst`, `.gz`) can be served
46
+ * when the client accepts their encoding and the content type is compressible.
47
+ *
48
+ * @default false
49
+ */
50
+ precompressed?: boolean | undefined;
51
+ /**
52
+ * Whether symbolic links whose target lies outside `rootDir` can be served.
53
+ * Enabling this makes every file the links reach publicly readable.
54
+ *
55
+ * @default false
56
+ */
57
+ allowSymlinks?: boolean | undefined;
58
+ /**
59
+ * Content types keyed by lowercase file extension without the dot, taking precedence over
60
+ * the type detected from the extension. Values are sent verbatim, so a text type needs its
61
+ * own charset. Extensions that neither this nor the detection recognises are served as
62
+ * `application/octet-stream`.
63
+ */
64
+ mimeTypes?: Record<string, string> | undefined;
65
+ }
66
+ /**
67
+ * Serves static files from a directory with standard HTTP semantics:
68
+ * `ETag`/`Last-Modified` conditional requests, range requests, index files,
69
+ * and directory traversal protection. Files are served as a fallback,
70
+ * so matched procedures always win.
71
+ *
72
+ * @remarks
73
+ * Deliberate deviations, all matching `send`, nginx, and Hono: range handling applies to `GET`
74
+ * only, so `HEAD` always reports the full length even though `Accept-Ranges` advertises support;
75
+ * a suffix range against an empty file answers `416`; and `dotfiles` is a request-path policy,
76
+ * so it never applies to a configured `indexFile` or `fallbackFile`.
77
+ *
78
+ * @see {@link https://orpc.dev/docs/plugins/static-file | Static File Plugin}
79
+ */
80
+ export declare class StaticFileHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
81
+ name: string;
82
+ /**
83
+ * Ensure the request span is available when the interceptor renames it.
84
+ */
85
+ after: string[];
86
+ /**
87
+ * Should run outside the HEAD method plugin's `GET` fallback, so files keep answering `HEAD`
88
+ * themselves and procedures routed as `GET` still take precedence over them.
89
+ */
90
+ before: string[];
91
+ private readonly rootDir;
92
+ /** `rootDir` with a trailing separator, precomputed for the lexical containment check. */
93
+ private readonly rootDirPrefix;
94
+ /**
95
+ * `rootDir` with its own symbolic links resolved, paired with its trailing separator form.
96
+ * Resolved once, so a symlinked `rootDir` keeps working and platform links like the macOS
97
+ * `/var` to `/private/var` do not reject every file.
98
+ */
99
+ private readonly rootDirRealPaths;
100
+ private readonly path;
101
+ private readonly indexFile;
102
+ private readonly fallbackFile;
103
+ private readonly cacheControl;
104
+ private readonly dotfiles;
105
+ private readonly precompressed;
106
+ private readonly allowSymlinks;
107
+ private readonly mimeTypes;
108
+ constructor(options: StaticFileHandlerPluginOptions);
109
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
110
+ /**
111
+ * Joins segments under `rootDir` and guarantees the result cannot escape it,
112
+ * as a second layer of defense after URL segment validation.
113
+ */
114
+ private resolveWithinRoot;
115
+ /**
116
+ * Resolves symbolic links and confirms the target is still inside the root,
117
+ * which the lexical `resolveWithinRoot` check cannot see.
118
+ */
119
+ private resolveContainedRealPath;
120
+ private resolveContentType;
121
+ private resolveBasePath;
122
+ /**
123
+ * Resolves segments under `rootDir` and stats the result, rejecting anything that
124
+ * escapes the root either lexically or by following a symbolic link.
125
+ */
126
+ private lookup;
127
+ /**
128
+ * Normalizes the url path into filesystem segments,
129
+ * returning `undefined` when the request can never map to a servable file.
130
+ */
131
+ private resolveSegments;
132
+ private serve;
133
+ }