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