@orpc/server 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.
- package/README.md +6 -4
- package/dist/adapters/aws-lambda/handler.d.mts +25 -0
- package/dist/adapters/aws-lambda/handler.mjs +21 -0
- package/dist/adapters/aws-lambda/index.d.mts +14 -49
- package/dist/adapters/aws-lambda/index.mjs +2 -39
- package/dist/adapters/aws-lambda/rpc-handler.d.mts +18 -0
- package/dist/adapters/aws-lambda/rpc-handler.mjs +10 -0
- package/dist/adapters/crossws/handler.d.mts +41 -0
- package/dist/adapters/crossws/handler.mjs +38 -0
- package/dist/adapters/crossws/index.d.mts +2 -63
- package/dist/adapters/crossws/index.mjs +2 -68
- package/dist/adapters/crossws/rpc-handler.d.mts +15 -0
- package/dist/adapters/crossws/rpc-handler.mjs +10 -0
- package/dist/adapters/fastify/handler.d.mts +21 -0
- package/dist/adapters/fastify/handler.mjs +20 -0
- package/dist/adapters/fastify/index.d.mts +2 -42
- package/dist/adapters/fastify/index.mjs +2 -39
- package/dist/adapters/fastify/rpc-handler.d.mts +14 -0
- package/dist/adapters/fastify/rpc-handler.mjs +10 -0
- package/dist/adapters/fetch/handler.d.mts +23 -0
- package/dist/adapters/fetch/handler.mjs +22 -0
- package/dist/adapters/fetch/index.d.mts +6 -46
- package/dist/adapters/fetch/index.mjs +4 -41
- package/dist/adapters/fetch/rpc-handler.d.mts +16 -0
- package/dist/adapters/fetch/rpc-handler.mjs +10 -0
- package/dist/adapters/message-port/handler.d.mts +57 -0
- package/dist/adapters/message-port/handler.mjs +62 -0
- package/dist/adapters/message-port/index.d.mts +2 -77
- package/dist/adapters/message-port/index.mjs +2 -87
- package/dist/adapters/message-port/rpc-handler.d.mts +15 -0
- package/dist/adapters/message-port/rpc-handler.mjs +10 -0
- package/dist/adapters/node/handler.d.mts +21 -0
- package/dist/adapters/node/handler.mjs +20 -0
- package/dist/adapters/node/index.d.mts +6 -43
- package/dist/adapters/node/index.mjs +4 -40
- package/dist/adapters/node/rpc-handler.d.mts +15 -0
- package/dist/adapters/node/rpc-handler.mjs +10 -0
- package/dist/adapters/standard/codec.d.mts +16 -0
- package/dist/adapters/standard/codec.mjs +1 -0
- package/dist/adapters/standard/handler.d.mts +68 -0
- package/dist/adapters/standard/handler.mjs +185 -0
- package/dist/adapters/standard/index.d.mts +6 -95
- package/dist/adapters/standard/index.mjs +5 -8
- package/dist/adapters/standard/plugin.d.mts +32 -0
- package/dist/adapters/standard/plugin.mjs +16 -0
- package/dist/adapters/standard/rpc-handler-codec.d.mts +42 -0
- package/dist/adapters/standard/rpc-handler-codec.mjs +51 -0
- package/dist/adapters/standard/rpc-matcher.d.mts +53 -0
- package/dist/adapters/standard/rpc-matcher.mjs +140 -0
- package/dist/adapters/standard/utils.d.mts +10 -0
- package/dist/adapters/standard/utils.mjs +6 -0
- package/dist/adapters/standard-peer/index.d.mts +1 -11
- package/dist/adapters/standard-peer/index.mjs +1 -10
- package/dist/adapters/standard-peer/utils.d.mts +4 -0
- package/dist/adapters/standard-peer/utils.mjs +11 -0
- package/dist/adapters/websocket/handler.d.mts +55 -0
- package/dist/adapters/websocket/handler.mjs +55 -0
- package/dist/adapters/websocket/index.d.mts +2 -77
- package/dist/adapters/websocket/index.mjs +2 -87
- package/dist/adapters/websocket/rpc-handler.d.mts +15 -0
- package/dist/adapters/websocket/rpc-handler.mjs +10 -0
- package/dist/builder-variants.d.mts +267 -0
- package/dist/builder-variants.mjs +1 -0
- package/dist/builder.d.mts +141 -0
- package/dist/builder.mjs +145 -0
- package/dist/constants.d.mts +2 -0
- package/dist/constants.mjs +2 -0
- package/dist/context.d.mts +13 -0
- package/dist/context.mjs +1 -0
- package/dist/extensions/callable.d.mts +16 -9
- package/dist/extensions/callable.mjs +5 -9
- package/dist/helpers/base64url.d.mts +31 -0
- package/dist/helpers/base64url.mjs +25 -0
- package/dist/helpers/cookie.d.mts +50 -0
- package/dist/helpers/cookie.mjs +35 -0
- package/dist/helpers/encryption.d.mts +28 -0
- package/dist/helpers/encryption.mjs +62 -0
- package/dist/helpers/index.d.mts +4 -167
- package/dist/helpers/index.mjs +4 -200
- package/dist/helpers/signing.d.mts +50 -0
- package/dist/helpers/signing.mjs +43 -0
- package/dist/implementer-procedure.d.mts +36 -0
- package/dist/implementer-procedure.mjs +38 -0
- package/dist/implementer-router.d.mts +78 -0
- package/dist/implementer-router.mjs +77 -0
- package/dist/implementer.d.mts +22 -0
- package/dist/implementer.mjs +30 -0
- package/dist/index.d.mts +57 -476
- package/dist/index.mjs +25 -458
- package/dist/lazy.d.mts +20 -0
- package/dist/lazy.mjs +22 -0
- package/dist/middleware-decorated.d.mts +27 -0
- package/dist/middleware-decorated.mjs +65 -0
- package/dist/middleware.d.mts +70 -0
- package/dist/middleware.mjs +1 -0
- package/dist/plugins/batch.d.mts +104 -0
- package/dist/plugins/batch.mjs +373 -0
- package/dist/plugins/cors.d.mts +67 -0
- package/dist/plugins/cors.mjs +134 -0
- package/dist/plugins/get-method-csrf-protection.d.mts +23 -0
- package/dist/plugins/get-method-csrf-protection.mjs +45 -0
- package/dist/plugins/head-method.d.mts +23 -0
- package/dist/plugins/head-method.mjs +95 -0
- package/dist/plugins/index.d.mts +39 -432
- package/dist/plugins/index.mjs +23 -967
- package/dist/plugins/method-override.d.mts +38 -0
- package/dist/plugins/method-override.mjs +50 -0
- package/dist/plugins/request-compression.d.mts +16 -0
- package/dist/plugins/request-compression.mjs +67 -0
- package/dist/plugins/request-headers.d.mts +22 -0
- package/dist/plugins/request-headers.mjs +21 -0
- package/dist/plugins/request-limit.d.mts +30 -0
- package/dist/plugins/request-limit.mjs +53 -0
- package/dist/plugins/response-compression.d.mts +59 -0
- package/dist/plugins/response-compression.mjs +172 -0
- package/dist/plugins/response-headers.d.mts +30 -0
- package/dist/plugins/response-headers.mjs +34 -0
- package/dist/plugins/rethrow.d.mts +33 -0
- package/dist/plugins/rethrow.mjs +46 -0
- package/dist/plugins/signal-sync.d.mts +13 -0
- package/dist/plugins/signal-sync.mjs +84 -0
- package/dist/plugins/timeout.d.mts +37 -0
- package/dist/plugins/timeout.mjs +56 -0
- package/dist/procedure-client.d.mts +41 -0
- package/dist/procedure-client.mjs +157 -0
- package/dist/procedure-decorated.d.mts +20 -0
- package/dist/procedure-decorated.mjs +41 -0
- package/dist/procedure-utils.d.mts +52 -0
- package/dist/procedure-utils.mjs +33 -0
- package/dist/procedure.d.mts +93 -0
- package/dist/procedure.mjs +20 -0
- package/dist/router-client.d.mts +27 -0
- package/dist/router-client.mjs +35 -0
- package/dist/router-hidden.d.mts +5 -0
- package/dist/router-hidden.mjs +12 -0
- package/dist/router-utils.d.mts +59 -0
- package/dist/router-utils.mjs +191 -0
- package/dist/router.d.mts +61 -0
- package/dist/router.mjs +1 -0
- package/package.json +11 -11
- package/dist/adapters/aws-lambda/index.d.ts +0 -51
- package/dist/adapters/crossws/index.d.ts +0 -63
- package/dist/adapters/fastify/index.d.ts +0 -42
- package/dist/adapters/fetch/index.d.ts +0 -47
- package/dist/adapters/message-port/index.d.ts +0 -77
- package/dist/adapters/node/index.d.ts +0 -44
- package/dist/adapters/standard/index.d.ts +0 -95
- package/dist/adapters/standard-peer/index.d.ts +0 -11
- package/dist/adapters/websocket/index.d.ts +0 -77
- package/dist/extensions/callable.d.ts +0 -10
- package/dist/helpers/index.d.ts +0 -167
- package/dist/index.d.ts +0 -476
- package/dist/plugins/index.d.ts +0 -432
- package/dist/shared/server.1ExWFMze.mjs +0 -69
- package/dist/shared/server.9B1jEm5a.d.mts +0 -105
- package/dist/shared/server.BB464y-6.mjs +0 -207
- package/dist/shared/server.BC5BIu02.d.mts +0 -73
- package/dist/shared/server.BSYGskId.d.ts +0 -14
- package/dist/shared/server.BvG3boBj.d.mts +0 -14
- package/dist/shared/server.CTV_mC2P.d.mts +0 -34
- package/dist/shared/server.CYbIpHbH.mjs +0 -239
- package/dist/shared/server.CgBF3Vj1.d.ts +0 -34
- package/dist/shared/server.Chq5FpXf.mjs +0 -353
- package/dist/shared/server.DFPxP2v3.d.mts +0 -166
- package/dist/shared/server.DFPxP2v3.d.ts +0 -166
- package/dist/shared/server.DOg7ke6y.d.ts +0 -105
- package/dist/shared/server.Dz7j9BEh.d.ts +0 -73
- package/dist/shared/server.W91HSRkE.mjs +0 -9
- package/dist/shared/server.sBQSgqK3.mjs +0 -41
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { Promisable, Value } from "@orpc/shared";
|
|
2
|
+
import type { StandardHeaders, StandardLazyRequest, StandardResponse } from "@standard-server/core";
|
|
3
|
+
import type { StandardHandlerOptions, StandardHandlerPlugin, StandardHandlerRoutingInterceptorOptions } from "../adapters/standard/index.mjs";
|
|
4
|
+
import type { Context } from "../context.mjs";
|
|
5
|
+
/**
|
|
6
|
+
* Content type for batch responses that use the length-prefixed binary framing,
|
|
7
|
+
* which they do in `streaming` mode, or when any sub-response contains binary or is a stream.
|
|
8
|
+
*
|
|
9
|
+
* Decoding is driven by the `standard-server` body hint, not this header,
|
|
10
|
+
* so it only serves to describe the payload to logs, proxies, and dev tools.
|
|
11
|
+
*/
|
|
12
|
+
export declare const BATCH_CONTENT_TYPE = "application/vnd.orpc.batch";
|
|
13
|
+
export interface BatchHandlerPluginOptions<T extends Context> {
|
|
14
|
+
/**
|
|
15
|
+
* The max size of the batch allowed. Larger batches are rejected with a `413`,
|
|
16
|
+
* so keep the client Batch Link Plugin's `maxSize` at or below it.
|
|
17
|
+
*
|
|
18
|
+
* @default DEFAULT_BATCH_MAX_SIZE (10)
|
|
19
|
+
* @see {@link https://orpc.dev/docs/plugins/batch#max-size | Batch Plugin - Max Size}
|
|
20
|
+
*/
|
|
21
|
+
maxSize?: Value<Promisable<number>, [options: StandardHandlerRoutingInterceptorOptions<T>]> | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Map each subrequest in the batch before it is processed.
|
|
24
|
+
*
|
|
25
|
+
* @default merges the batch request headers into the subrequest, giving them priority over
|
|
26
|
+
* the subrequest headers, and removes the `orpc-batch` header to prevent nested batching
|
|
27
|
+
*/
|
|
28
|
+
mapSubrequest?: ((subrequest: StandardLazyRequest, batchOptions: StandardHandlerRoutingInterceptorOptions<T>) => StandardLazyRequest) | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Map each sub-response in the batch before it is sent.
|
|
31
|
+
*
|
|
32
|
+
* @default removes the headers the batch response already has with the same value, which the client
|
|
33
|
+
* merges back, and `set-cookie`, which the browser ignores there and JavaScript could read
|
|
34
|
+
*/
|
|
35
|
+
mapSubresponse?: ((subresponse: StandardResponse, partialBatchResponse: Pick<StandardResponse, "status" | "headers">, batchOptions: StandardHandlerRoutingInterceptorOptions<T>) => StandardResponse) | undefined;
|
|
36
|
+
/**
|
|
37
|
+
* Success batch response status code.
|
|
38
|
+
*
|
|
39
|
+
* @default 207
|
|
40
|
+
*/
|
|
41
|
+
successStatus?: Value<Promisable<number>, [batchOptions: StandardHandlerRoutingInterceptorOptions<T>]> | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* Success batch response headers.
|
|
44
|
+
*
|
|
45
|
+
* In `buffered` mode, the batch response also gets the cookies its sub-responses set, and the headers they all share.
|
|
46
|
+
* In `streaming` mode, it gets only the cookies of the first sub-response to be ready.
|
|
47
|
+
* Headers set here win, and setting one to `undefined` keeps it off, except `set-cookie` and `vary`, which merge.
|
|
48
|
+
*
|
|
49
|
+
* @default {}
|
|
50
|
+
*/
|
|
51
|
+
headers?: Value<Promisable<StandardHeaders>, [batchOptions: StandardHandlerRoutingInterceptorOptions<T>]> | undefined;
|
|
52
|
+
/**
|
|
53
|
+
* Keep-alive settings for batch responses that stream.
|
|
54
|
+
*
|
|
55
|
+
* When enabled, a zero-length length-prefixed frame is sent periodically while the
|
|
56
|
+
* stream is idle (no message sent for `interval` ms). Clients ignore these frames.
|
|
57
|
+
*
|
|
58
|
+
* @default { enabled: true, interval: 15000 }
|
|
59
|
+
*/
|
|
60
|
+
keepAlive?: {
|
|
61
|
+
/**
|
|
62
|
+
* If true, a keep-alive frame is sent periodically while the stream is idle.
|
|
63
|
+
*
|
|
64
|
+
* @default true
|
|
65
|
+
*/
|
|
66
|
+
enabled: boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Interval (in milliseconds) between keep-alive frames after the last message.
|
|
69
|
+
*
|
|
70
|
+
* @default 15000
|
|
71
|
+
*/
|
|
72
|
+
interval?: number | undefined;
|
|
73
|
+
} | undefined;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Handles batch requests sent by the client Batch Link Plugin, splitting each
|
|
77
|
+
* batch into sub-requests and sending their responses back together.
|
|
78
|
+
*
|
|
79
|
+
* @remarks
|
|
80
|
+
* The client Batch Link Plugin's `mode` picks how each batch responds: `buffered` (default) waits for every
|
|
81
|
+
* sub-response and carries their cookies and shared headers; `streaming` starts once the first is ready and
|
|
82
|
+
* carries only its cookies.
|
|
83
|
+
*
|
|
84
|
+
* **Note**: HTTP/2 and later already multiplex requests over a single connection, which often makes this plugin unnecessary.
|
|
85
|
+
*
|
|
86
|
+
* @see {@link https://orpc.dev/docs/plugins/batch | Batch Plugin}
|
|
87
|
+
*/
|
|
88
|
+
export declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
|
|
89
|
+
name: string;
|
|
90
|
+
/**
|
|
91
|
+
* Run batch interceptors inside the tracing interceptors
|
|
92
|
+
* so each subrequest gets its own span instead of sharing one batch-level span.
|
|
93
|
+
*/
|
|
94
|
+
after: string[];
|
|
95
|
+
private readonly maxSize;
|
|
96
|
+
private readonly mapSubrequest;
|
|
97
|
+
private readonly mapSubresponse;
|
|
98
|
+
private readonly successStatus;
|
|
99
|
+
private readonly headers;
|
|
100
|
+
private readonly keepAliveEnabled;
|
|
101
|
+
private readonly keepAliveInterval;
|
|
102
|
+
constructor(options?: BatchHandlerPluginOptions<T>);
|
|
103
|
+
init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
|
|
104
|
+
}
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import { ORPCError } from "@orpc/client";
|
|
2
|
+
import { BATCH_HEADER, DEFAULT_BATCH_MAX_SIZE } from "@orpc/client/plugins";
|
|
3
|
+
import { isAsyncIteratorObject, promiseWithResolvers, toArray, value } from "@orpc/shared";
|
|
4
|
+
import { flattenStandardHeader, parseStandardUrl } from "@standard-server/core";
|
|
5
|
+
import { encodePeerMessage, isClientPeerSendMessage, isPeerMessage, ServerPeer } from "@standard-server/peer";
|
|
6
|
+
|
|
7
|
+
export const BATCH_CONTENT_TYPE = "application/vnd.orpc.batch";
|
|
8
|
+
const textEncoder = /* @__PURE__ */ new TextEncoder();
|
|
9
|
+
function encodeLengthPrefix(length) {
|
|
10
|
+
const prefix = new Uint8Array(4);
|
|
11
|
+
new DataView(prefix.buffer).setUint32(0, length, false);
|
|
12
|
+
return prefix;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function encodeFrame(message) {
|
|
16
|
+
const encoded = await encodePeerMessage(message);
|
|
17
|
+
const bytes = typeof encoded === "string" ? textEncoder.encode(encoded) : encoded;
|
|
18
|
+
return [encodeLengthPrefix(bytes.byteLength), bytes];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function isBodyHeader(name) {
|
|
22
|
+
return name.startsWith("content-") || name === "standard-server";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function isClientPeerSendMessages(maybe) {
|
|
26
|
+
return Array.isArray(maybe) && maybe.every((m) => isPeerMessage(m) && isClientPeerSendMessage(m));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function internalError(err) {
|
|
30
|
+
Promise.reject(err);
|
|
31
|
+
return {
|
|
32
|
+
status: 500,
|
|
33
|
+
headers: {},
|
|
34
|
+
body: "Internal server error"
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function firstSubresponseHead(heads) {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
for (const promise of heads) {
|
|
41
|
+
void promise.then((head) => head && resolve(head));
|
|
42
|
+
}
|
|
43
|
+
void Promise.all(heads).then(() => resolve(undefined));
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function liftCookies(headers, sources) {
|
|
48
|
+
const cookies = new Set(sources.flatMap((source) => toArray(source["set-cookie"])));
|
|
49
|
+
return cookies.size > 0 ? {
|
|
50
|
+
...headers,
|
|
51
|
+
"set-cookie": [...cookies]
|
|
52
|
+
} : headers;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function liftSubresponseHeaders(batchHeaders, subresponseHeaders) {
|
|
56
|
+
const [first = {}, ...rest] = subresponseHeaders;
|
|
57
|
+
const shared = {};
|
|
58
|
+
for (const [name, value] of Object.entries(first)) {
|
|
59
|
+
if (value === undefined || isBodyHeader(name)) {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const flattened = flattenStandardHeader(value);
|
|
63
|
+
if (rest.every((other) => flattenStandardHeader(other[name]) === flattened)) {
|
|
64
|
+
shared[name] = value;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const headers = liftCookies({
|
|
68
|
+
...shared,
|
|
69
|
+
...batchHeaders
|
|
70
|
+
}, [batchHeaders, ...subresponseHeaders]);
|
|
71
|
+
const varies = new Map();
|
|
72
|
+
for (const value of [batchHeaders, ...subresponseHeaders].flatMap((other) => toArray(other.vary))) {
|
|
73
|
+
for (const field of value.split(",")) {
|
|
74
|
+
const name = field.trim();
|
|
75
|
+
const key = name.toLowerCase();
|
|
76
|
+
if (name && !varies.has(key)) {
|
|
77
|
+
varies.set(key, name);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (varies.size > 0) {
|
|
82
|
+
headers.vary = varies.has("*") ? "*" : [...varies.values()].join(", ");
|
|
83
|
+
}
|
|
84
|
+
return headers;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export class BatchHandlerPlugin {
|
|
88
|
+
name = "~batch";
|
|
89
|
+
|
|
90
|
+
after = ["~tracing"];
|
|
91
|
+
maxSize;
|
|
92
|
+
mapSubrequest;
|
|
93
|
+
mapSubresponse;
|
|
94
|
+
successStatus;
|
|
95
|
+
headers;
|
|
96
|
+
keepAliveEnabled;
|
|
97
|
+
keepAliveInterval;
|
|
98
|
+
constructor(options = {}) {
|
|
99
|
+
this.maxSize = options.maxSize ?? DEFAULT_BATCH_MAX_SIZE;
|
|
100
|
+
this.mapSubrequest = options.mapSubrequest ?? ((subRequest, { request: batchRequest }) => ({
|
|
101
|
+
...subRequest,
|
|
102
|
+
headers: {
|
|
103
|
+
...subRequest.headers,
|
|
104
|
+
|
|
105
|
+
...batchRequest.headers,
|
|
106
|
+
[BATCH_HEADER]: undefined
|
|
107
|
+
}
|
|
108
|
+
}));
|
|
109
|
+
this.mapSubresponse = options.mapSubresponse ?? ((subresponse, { headers: batchHeaders }) => {
|
|
110
|
+
const headers = {};
|
|
111
|
+
for (const [name, value] of Object.entries(subresponse.headers)) {
|
|
112
|
+
if (name !== "set-cookie" && flattenStandardHeader(value) !== flattenStandardHeader(batchHeaders[name])) {
|
|
113
|
+
headers[name] = value;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
...subresponse,
|
|
118
|
+
headers
|
|
119
|
+
};
|
|
120
|
+
});
|
|
121
|
+
this.successStatus = options.successStatus ?? 207;
|
|
122
|
+
this.headers = options.headers ?? {};
|
|
123
|
+
this.keepAliveEnabled = options.keepAlive?.enabled ?? true;
|
|
124
|
+
this.keepAliveInterval = options.keepAlive?.interval ?? 15e3;
|
|
125
|
+
}
|
|
126
|
+
init(options) {
|
|
127
|
+
const routingInterceptor = async (interceptorOptions) => {
|
|
128
|
+
const batchHeader = flattenStandardHeader(interceptorOptions.request.headers[BATCH_HEADER]);
|
|
129
|
+
if (batchHeader === undefined) {
|
|
130
|
+
return interceptorOptions.next();
|
|
131
|
+
}
|
|
132
|
+
const streaming = batchHeader === "streaming";
|
|
133
|
+
let messages;
|
|
134
|
+
try {
|
|
135
|
+
if (interceptorOptions.request.method === "GET") {
|
|
136
|
+
const [, search] = parseStandardUrl(interceptorOptions.request.url);
|
|
137
|
+
const params = new URLSearchParams(search);
|
|
138
|
+
const data = params.getAll("data").at(-1);
|
|
139
|
+
if (!data) {
|
|
140
|
+
return {
|
|
141
|
+
matched: true,
|
|
142
|
+
response: {
|
|
143
|
+
status: 400,
|
|
144
|
+
headers: {},
|
|
145
|
+
body: "Missing data parameter for batch request"
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const mightBeMessages = JSON.parse(data);
|
|
150
|
+
if (!isClientPeerSendMessages(mightBeMessages)) {
|
|
151
|
+
return {
|
|
152
|
+
matched: true,
|
|
153
|
+
response: {
|
|
154
|
+
status: 400,
|
|
155
|
+
headers: {},
|
|
156
|
+
body: "Invalid batch request data parameter"
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
messages = mightBeMessages;
|
|
161
|
+
} else {
|
|
162
|
+
const mightBeMessages = await interceptorOptions.request.resolveBody();
|
|
163
|
+
if (!isClientPeerSendMessages(mightBeMessages)) {
|
|
164
|
+
return {
|
|
165
|
+
matched: true,
|
|
166
|
+
response: {
|
|
167
|
+
status: 400,
|
|
168
|
+
headers: {},
|
|
169
|
+
body: "Invalid batch request body"
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
messages = mightBeMessages;
|
|
174
|
+
}
|
|
175
|
+
} catch (error) {
|
|
176
|
+
return {
|
|
177
|
+
matched: true,
|
|
178
|
+
response: {
|
|
179
|
+
status: 400,
|
|
180
|
+
headers: {},
|
|
181
|
+
body: error instanceof ORPCError ? error.message : "Invalid batch request"
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const outerMethod = interceptorOptions.request.method;
|
|
186
|
+
if ((outerMethod === "GET" || outerMethod === "QUERY") && messages.some((message) => message.kind === "request" && message.json.method !== outerMethod)) {
|
|
187
|
+
return {
|
|
188
|
+
matched: true,
|
|
189
|
+
response: {
|
|
190
|
+
status: 400,
|
|
191
|
+
headers: {},
|
|
192
|
+
body: `${outerMethod} batch requests only accept ${outerMethod} sub-requests`
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
const maxSize = await value(this.maxSize, interceptorOptions);
|
|
197
|
+
if (messages.length > maxSize) {
|
|
198
|
+
return {
|
|
199
|
+
matched: true,
|
|
200
|
+
response: {
|
|
201
|
+
status: 413,
|
|
202
|
+
headers: {},
|
|
203
|
+
body: "Batch request size exceeds the maximum allowed size"
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
const status = await value(this.successStatus, interceptorOptions);
|
|
208
|
+
const headers = await value(this.headers, interceptorOptions);
|
|
209
|
+
|
|
210
|
+
const bufferedMessages = [];
|
|
211
|
+
let streamController;
|
|
212
|
+
let keepAliveTimer;
|
|
213
|
+
|
|
214
|
+
const ready = messages.map(() => promiseWithResolvers());
|
|
215
|
+
const heads = ready.map(({ promise }) => promise);
|
|
216
|
+
const lifting = streaming ? firstSubresponseHead(heads).then((head) => ({
|
|
217
|
+
batchHeaders: liftCookies(headers, [headers, head?.headers ?? {}]),
|
|
218
|
+
streams: true
|
|
219
|
+
})) : Promise.all(heads).then((all) => {
|
|
220
|
+
const present = all.filter((head) => head !== undefined);
|
|
221
|
+
return {
|
|
222
|
+
batchHeaders: liftSubresponseHeaders(headers, present.map((head) => head.headers)),
|
|
223
|
+
streams: present.some((head) => head.stream)
|
|
224
|
+
};
|
|
225
|
+
});
|
|
226
|
+
const clearKeepAlive = () => {
|
|
227
|
+
if (keepAliveTimer !== undefined) {
|
|
228
|
+
clearInterval(keepAliveTimer);
|
|
229
|
+
keepAliveTimer = undefined;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
const scheduleKeepAlive = () => {
|
|
233
|
+
if (!this.keepAliveEnabled) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
clearKeepAlive();
|
|
237
|
+
keepAliveTimer = setInterval(() => {
|
|
238
|
+
try {
|
|
239
|
+
|
|
240
|
+
streamController.enqueue(encodeLengthPrefix(0));
|
|
241
|
+
} catch {
|
|
242
|
+
|
|
243
|
+
clearKeepAlive();
|
|
244
|
+
}
|
|
245
|
+
}, this.keepAliveInterval);
|
|
246
|
+
};
|
|
247
|
+
const enqueueMessage = async (message) => {
|
|
248
|
+
for (const chunk of await encodeFrame(message)) {
|
|
249
|
+
streamController.enqueue(chunk);
|
|
250
|
+
}
|
|
251
|
+
scheduleKeepAlive();
|
|
252
|
+
};
|
|
253
|
+
const peer = new ServerPeer(async (message) => {
|
|
254
|
+
if (streamController === undefined) {
|
|
255
|
+
bufferedMessages.push(message);
|
|
256
|
+
} else {
|
|
257
|
+
await enqueueMessage(message);
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
const handleIndividualRequest = async (request, markReady) => {
|
|
261
|
+
let response;
|
|
262
|
+
try {
|
|
263
|
+
request = this.mapSubrequest(request, interceptorOptions);
|
|
264
|
+
const result = await interceptorOptions.next({
|
|
265
|
+
...interceptorOptions,
|
|
266
|
+
request
|
|
267
|
+
});
|
|
268
|
+
response = result.matched ? result.response : {
|
|
269
|
+
status: 404,
|
|
270
|
+
headers: {},
|
|
271
|
+
body: "No procedure matched"
|
|
272
|
+
};
|
|
273
|
+
} catch (err) {
|
|
274
|
+
response = internalError(err);
|
|
275
|
+
}
|
|
276
|
+
markReady({
|
|
277
|
+
headers: response.headers,
|
|
278
|
+
stream: response.body instanceof ReadableStream || isAsyncIteratorObject(response.body)
|
|
279
|
+
});
|
|
280
|
+
const { batchHeaders } = await lifting;
|
|
281
|
+
try {
|
|
282
|
+
return this.mapSubresponse(response, {
|
|
283
|
+
status,
|
|
284
|
+
headers: batchHeaders
|
|
285
|
+
}, interceptorOptions);
|
|
286
|
+
} catch (err) {
|
|
287
|
+
return internalError(err);
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
const runSubrequests = async () => {
|
|
291
|
+
const promise = Promise.all(messages.map((msg, i) => {
|
|
292
|
+
const { resolve } = ready[i];
|
|
293
|
+
|
|
294
|
+
return peer.message(msg, (request) => handleIndividualRequest(request, resolve)).finally(() => resolve(undefined));
|
|
295
|
+
}));
|
|
296
|
+
const signal = interceptorOptions.request.signal;
|
|
297
|
+
const closePeer = () => peer.close(signal?.reason);
|
|
298
|
+
if (signal?.aborted) {
|
|
299
|
+
closePeer();
|
|
300
|
+
}
|
|
301
|
+
signal?.addEventListener("abort", closePeer);
|
|
302
|
+
try {
|
|
303
|
+
await promise;
|
|
304
|
+
} finally {
|
|
305
|
+
signal?.removeEventListener("abort", closePeer);
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
const subrequests = runSubrequests();
|
|
309
|
+
const { batchHeaders, streams } = await lifting;
|
|
310
|
+
const framedHeaders = {
|
|
311
|
+
...batchHeaders,
|
|
312
|
+
"content-type": batchHeaders["content-type"] ?? BATCH_CONTENT_TYPE
|
|
313
|
+
};
|
|
314
|
+
if (!streams) {
|
|
315
|
+
await subrequests;
|
|
316
|
+
await peer.close();
|
|
317
|
+
if (bufferedMessages.some((msg) => msg.binary !== undefined)) {
|
|
318
|
+
const chunks = (await Promise.all(bufferedMessages.map(encodeFrame))).flat();
|
|
319
|
+
return {
|
|
320
|
+
matched: true,
|
|
321
|
+
response: {
|
|
322
|
+
status,
|
|
323
|
+
headers: framedHeaders,
|
|
324
|
+
body: new Blob(chunks)
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
matched: true,
|
|
330
|
+
response: {
|
|
331
|
+
status,
|
|
332
|
+
headers: batchHeaders,
|
|
333
|
+
body: bufferedMessages
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const body = new ReadableStream({
|
|
339
|
+
start(controller) {
|
|
340
|
+
streamController = controller;
|
|
341
|
+
scheduleKeepAlive();
|
|
342
|
+
},
|
|
343
|
+
async cancel(reason) {
|
|
344
|
+
clearKeepAlive();
|
|
345
|
+
await peer.close(reason);
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
const flushed = Promise.all(bufferedMessages.splice(0).map(enqueueMessage));
|
|
349
|
+
|
|
350
|
+
Promise.all([flushed, subrequests]).then(async () => {
|
|
351
|
+
clearKeepAlive();
|
|
352
|
+
streamController.close();
|
|
353
|
+
await peer.close();
|
|
354
|
+
}).catch(async (error) => {
|
|
355
|
+
clearKeepAlive();
|
|
356
|
+
streamController.error(error);
|
|
357
|
+
await peer.close(error);
|
|
358
|
+
});
|
|
359
|
+
return {
|
|
360
|
+
matched: true,
|
|
361
|
+
response: {
|
|
362
|
+
status,
|
|
363
|
+
headers: framedHeaders,
|
|
364
|
+
body
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
};
|
|
368
|
+
return {
|
|
369
|
+
...options,
|
|
370
|
+
routingInterceptors: [routingInterceptor, ...toArray(options.routingInterceptors)]
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { Promisable, Value } from "@orpc/shared";
|
|
2
|
+
import type { StandardHandlerOptions, StandardHandlerPlugin, StandardHandlerRoutingInterceptorOptions } from "../adapters/standard/index.mjs";
|
|
3
|
+
import type { Context } from "../context.mjs";
|
|
4
|
+
export interface CORSHandlerPluginOptions<T extends Context> {
|
|
5
|
+
/**
|
|
6
|
+
* Configures the `Access-Control-Allow-Origin` header.
|
|
7
|
+
* Can be a string, an array of allowed origins, or a function (optionally async) that returns the allowed origin(s).
|
|
8
|
+
*
|
|
9
|
+
* A function must only return origins it has validated: returning the incoming origin
|
|
10
|
+
* unchecked allows every origin.
|
|
11
|
+
*
|
|
12
|
+
* @default '*'
|
|
13
|
+
*/
|
|
14
|
+
origin?: Value<Promisable<string | readonly string[] | null | undefined>, [origin: string, options: StandardHandlerRoutingInterceptorOptions<T>]> | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Configures the `Timing-Allow-Origin` header.
|
|
17
|
+
* Can be a string, an array of allowed origins, or a function (optionally async) that returns the allowed origin(s).
|
|
18
|
+
*/
|
|
19
|
+
timingOrigin?: Value<Promisable<string | readonly string[] | null | undefined>, [origin: string, options: StandardHandlerRoutingInterceptorOptions<T>]> | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* Configures the `Access-Control-Allow-Methods` header for preflight requests.
|
|
22
|
+
*
|
|
23
|
+
* @default ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY']
|
|
24
|
+
*/
|
|
25
|
+
allowMethods?: readonly string[] | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Configures the `Access-Control-Allow-Headers` header for preflight requests.
|
|
28
|
+
* Falls back to the request's `Access-Control-Request-Headers` if not set.
|
|
29
|
+
* When set, it replaces that fallback, so include every non-safelisted header
|
|
30
|
+
* clients send, such as `Content-Type`.
|
|
31
|
+
*/
|
|
32
|
+
allowHeaders?: readonly string[] | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* Configures the `Access-Control-Max-Age` header (in seconds) for preflight requests.
|
|
35
|
+
*/
|
|
36
|
+
maxAge?: number | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Configures the `Access-Control-Allow-Credentials` header.
|
|
39
|
+
*
|
|
40
|
+
* When enabled, `origin` must allow trusted origins only: every allowed origin can send
|
|
41
|
+
* authenticated requests as your users and read the responses.
|
|
42
|
+
*/
|
|
43
|
+
credentials?: boolean | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* Configures the `Access-Control-Expose-Headers` header.
|
|
46
|
+
*/
|
|
47
|
+
exposeHeaders?: readonly string[] | undefined;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Configures the [CORS Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
|
|
51
|
+
* for your API, including preflight requests.
|
|
52
|
+
*
|
|
53
|
+
* @see {@link https://orpc.dev/docs/plugins/cors | CORS Handler Plugin}
|
|
54
|
+
*/
|
|
55
|
+
export declare class CORSHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
|
|
56
|
+
private readonly options;
|
|
57
|
+
name: string;
|
|
58
|
+
/**
|
|
59
|
+
* - Do not create spans for CORS preflight requests.
|
|
60
|
+
* - Run CORS interceptors before batch interceptors so headers are applied to
|
|
61
|
+
* the actual response rather than sub-responses.
|
|
62
|
+
*/
|
|
63
|
+
after: string[];
|
|
64
|
+
constructor(options?: CORSHandlerPluginOptions<T>);
|
|
65
|
+
init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
|
|
66
|
+
private resolveOrigin;
|
|
67
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { toArray } from "@orpc/shared";
|
|
2
|
+
import { flattenStandardHeader } from "@standard-server/core";
|
|
3
|
+
|
|
4
|
+
export class CORSHandlerPlugin {
|
|
5
|
+
options;
|
|
6
|
+
name = "~cors";
|
|
7
|
+
|
|
8
|
+
after = ["~tracing", "~batch"];
|
|
9
|
+
constructor(options = {}) {
|
|
10
|
+
const defaults = {
|
|
11
|
+
origin: "*",
|
|
12
|
+
allowMethods: [
|
|
13
|
+
"GET",
|
|
14
|
+
"HEAD",
|
|
15
|
+
"PUT",
|
|
16
|
+
"POST",
|
|
17
|
+
"DELETE",
|
|
18
|
+
"PATCH",
|
|
19
|
+
"QUERY"
|
|
20
|
+
]
|
|
21
|
+
};
|
|
22
|
+
this.options = {
|
|
23
|
+
...defaults,
|
|
24
|
+
...options
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
init(options) {
|
|
28
|
+
const corsHeadersInterceptor = async (interceptorOptions) => {
|
|
29
|
+
const result = await interceptorOptions.next();
|
|
30
|
+
if (!result.matched) {
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
const resHeaders = { ...result.response.headers };
|
|
34
|
+
const origin = flattenStandardHeader(interceptorOptions.request.headers.origin);
|
|
35
|
+
const allowOrigin = await this.resolveOrigin(this.options.origin, origin, interceptorOptions);
|
|
36
|
+
const timingAllowOrigin = await this.resolveOrigin(this.options.timingOrigin, origin, interceptorOptions);
|
|
37
|
+
if (allowOrigin.value !== undefined) {
|
|
38
|
+
resHeaders["access-control-allow-origin"] = allowOrigin.value;
|
|
39
|
+
}
|
|
40
|
+
if (timingAllowOrigin.value !== undefined) {
|
|
41
|
+
resHeaders["timing-allow-origin"] = timingAllowOrigin.value;
|
|
42
|
+
}
|
|
43
|
+
if (allowOrigin.varies || timingAllowOrigin.varies) {
|
|
44
|
+
const existingVary = flattenStandardHeader(resHeaders.vary);
|
|
45
|
+
if (!existingVary?.split(",").some((v) => v.trim().toLowerCase() === "origin")) {
|
|
46
|
+
resHeaders.vary = existingVary ? `${existingVary}, Origin` : "Origin";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (this.options.credentials) {
|
|
50
|
+
resHeaders["access-control-allow-credentials"] = "true";
|
|
51
|
+
}
|
|
52
|
+
if (this.options.exposeHeaders?.length) {
|
|
53
|
+
resHeaders["access-control-expose-headers"] = flattenStandardHeader(this.options.exposeHeaders);
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
...result,
|
|
57
|
+
response: {
|
|
58
|
+
...result.response,
|
|
59
|
+
headers: resHeaders
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
const preflightInterceptor = async (interceptorOptions) => {
|
|
64
|
+
if (interceptorOptions.request.method === "OPTIONS") {
|
|
65
|
+
const resHeaders = {};
|
|
66
|
+
if (this.options.maxAge !== undefined) {
|
|
67
|
+
resHeaders["access-control-max-age"] = this.options.maxAge.toString();
|
|
68
|
+
}
|
|
69
|
+
if (this.options.allowMethods?.length) {
|
|
70
|
+
resHeaders["access-control-allow-methods"] = flattenStandardHeader(this.options.allowMethods);
|
|
71
|
+
}
|
|
72
|
+
const allowHeaders = this.options.allowHeaders ?? interceptorOptions.request.headers["access-control-request-headers"];
|
|
73
|
+
if (typeof allowHeaders === "string" || allowHeaders?.length) {
|
|
74
|
+
resHeaders["access-control-allow-headers"] = flattenStandardHeader(allowHeaders);
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
matched: true,
|
|
78
|
+
response: {
|
|
79
|
+
status: 204,
|
|
80
|
+
headers: resHeaders,
|
|
81
|
+
body: undefined
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
return interceptorOptions.next();
|
|
86
|
+
};
|
|
87
|
+
return {
|
|
88
|
+
...options,
|
|
89
|
+
routingInterceptors: [
|
|
90
|
+
corsHeadersInterceptor,
|
|
91
|
+
preflightInterceptor,
|
|
92
|
+
...toArray(options.routingInterceptors)
|
|
93
|
+
]
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
async resolveOrigin(option, origin, interceptorOptions) {
|
|
97
|
+
if (typeof option === "function") {
|
|
98
|
+
if (origin === undefined) {
|
|
99
|
+
return {
|
|
100
|
+
value: undefined,
|
|
101
|
+
varies: true
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
const allowed = toArray(await option(origin, interceptorOptions));
|
|
105
|
+
if (allowed.includes("*")) {
|
|
106
|
+
return {
|
|
107
|
+
value: "*",
|
|
108
|
+
varies: true
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
value: allowed.includes(origin) ? origin : undefined,
|
|
113
|
+
varies: true
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const allowed = toArray(await option);
|
|
117
|
+
if (allowed.includes("*")) {
|
|
118
|
+
return {
|
|
119
|
+
value: "*",
|
|
120
|
+
varies: false
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
if (origin !== undefined && allowed.includes(origin)) {
|
|
124
|
+
return {
|
|
125
|
+
value: origin,
|
|
126
|
+
varies: true
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
value: undefined,
|
|
131
|
+
varies: allowed.length > 0
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { StandardHandlerOptions, StandardHandlerPlugin } from "../adapters/standard/index.mjs";
|
|
2
|
+
import type { Context } from "../context.mjs";
|
|
3
|
+
/**
|
|
4
|
+
* Adds Cross-Site Request Forgery (CSRF) protection that makes the safe `GET` method as
|
|
5
|
+
* secure as unsafe ones such as `POST`. It rejects `GET` requests arriving as top-level
|
|
6
|
+
* navigations initiated cross-site or from outside the browser, the only context where
|
|
7
|
+
* another site can make a browser attach `SameSite=Lax` cookies to a safe-method request.
|
|
8
|
+
* Requests matching no procedure stay unmatched, so they can fall through to whatever
|
|
9
|
+
* serves the rest of the site.
|
|
10
|
+
*
|
|
11
|
+
* @remarks
|
|
12
|
+
* **Note**: Requests browsers send without `SameSite=Lax` cookies, such as cross-site `fetch`
|
|
13
|
+
* and `<img>`, pass through, so procedures stay reachable from other sites. This safeguard
|
|
14
|
+
* requires authentication cookies explicitly marked `SameSite=Lax` or `SameSite=Strict`,
|
|
15
|
+
* since browsers may attach other cookies to the requests that pass.
|
|
16
|
+
*
|
|
17
|
+
* @see {@link https://orpc.dev/docs/plugins/get-method-csrf-protection | GET Method CSRF Protection Plugin}
|
|
18
|
+
*/
|
|
19
|
+
export declare class GetMethodCsrfProtectionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
|
|
20
|
+
name: string;
|
|
21
|
+
init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
|
|
22
|
+
private isAllowed;
|
|
23
|
+
}
|