@loozo/angular-launch 0.0.5 → 0.0.6
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 +463 -42
- package/channel.d.ts +53 -0
- package/channel.js +231 -0
- package/client.d.ts +50 -10
- package/connect.d.ts +201 -0
- package/connect.js +148 -0
- package/generated.d.ts +1 -1
- package/generated.js +86 -3
- package/generation/index.js +25 -9
- package/index.d.ts +6 -1
- package/index.js +2 -0
- package/json.d.ts +9 -0
- package/json.js +24 -0
- package/navigation.d.ts +36 -0
- package/navigation.js +47 -0
- package/node/index.d.ts +57 -0
- package/node/index.js +175 -0
- package/outcomes.d.ts +55 -0
- package/outcomes.js +100 -0
- package/package.json +9 -3
- package/server/backend.d.ts +42 -23
- package/server/backend.js +127 -48
- package/server/channel-messages.d.ts +54 -0
- package/server/channel-messages.js +84 -0
- package/server/channel-socket.d.ts +67 -0
- package/server/channel-socket.js +322 -0
- package/server/definitions.d.ts +152 -24
- package/server/definitions.js +13 -5
- package/server/dispatch.d.ts +62 -11
- package/server/dispatch.js +156 -36
- package/server/event-stream.d.ts +63 -0
- package/server/event-stream.js +173 -0
- package/server/generated.d.ts +1 -0
- package/server/generated.js +1 -0
- package/server/index.d.ts +4 -2
- package/server/index.js +1 -1
- package/server/outcomes.d.ts +51 -2
- package/server/outcomes.js +58 -4
- package/server/response-effects.d.ts +105 -0
- package/server/response-effects.js +78 -0
- package/server/upgrade.d.ts +58 -0
- package/server/upgrade.js +117 -0
- package/stream.d.ts +31 -0
- package/stream.js +159 -0
- package/tanstack-query/README.md +101 -9
- package/tanstack-query/generated.js +5 -2
- package/tanstack-query/queries.d.ts +8 -6
package/server/dispatch.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { type FrameworkCode } from "../client.js";
|
|
2
2
|
import { type InputIssue } from "../input-issues.js";
|
|
3
3
|
import type { ContextDefinition, ContextOf, Group, ProcedureDefinition } from "./definitions.js";
|
|
4
|
+
import { type ChannelInbox } from "./channel-messages.js";
|
|
5
|
+
import { type StreamStart } from "./event-stream.js";
|
|
6
|
+
import { type ResponseEffects } from "./response-effects.js";
|
|
4
7
|
/**
|
|
5
8
|
* The application's RPC groups, keyed by namespace.
|
|
6
9
|
*
|
|
@@ -79,11 +82,20 @@ export declare function isRequestScope(value: unknown): value is RequestScope;
|
|
|
79
82
|
*/
|
|
80
83
|
export declare function createRequestScope<Definition extends ContextDefinition<unknown>>(application: ApplicationBinding<Definition>, request: Request): Promise<RequestScope<ContextOf<Definition>>>;
|
|
81
84
|
export declare function assertBoundScope(scope: unknown, application: ApplicationBinding, request: Request): asserts scope is RequestScope;
|
|
82
|
-
/**
|
|
85
|
+
/**
|
|
86
|
+
* The HTTP status and JSON body {@link dispatch} produces for one call. Internal.
|
|
87
|
+
*
|
|
88
|
+
* @remarks
|
|
89
|
+
* Only status 200 is a result; every other status carries a frame dispatch built itself,
|
|
90
|
+
* so a result shaped like a frame stays data.
|
|
91
|
+
*/
|
|
83
92
|
export interface Reply {
|
|
84
|
-
/**
|
|
93
|
+
/** 200 for a result, 303 for a redirect, otherwise the error's or not-found's status. */
|
|
85
94
|
readonly status: number;
|
|
86
|
-
/**
|
|
95
|
+
/**
|
|
96
|
+
* The result, an `{ error: { code, message, data } }` frame, `{ redirect: { to } }` or
|
|
97
|
+
* `{ notFound: null }`.
|
|
98
|
+
*/
|
|
87
99
|
readonly body: unknown;
|
|
88
100
|
}
|
|
89
101
|
export declare function failure(code: Exclude<FrameworkCode, "INVALID_INPUT">): Reply;
|
|
@@ -100,7 +112,9 @@ export declare function isJsonMediaType(contentType: string | null): boolean;
|
|
|
100
112
|
*
|
|
101
113
|
* In order: the scope must belong to `application` and `request` (`INTERNAL`); the
|
|
102
114
|
* path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
|
|
103
|
-
* (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused
|
|
115
|
+
* (`RPC_NOT_FOUND`); a mutation, stream or channel in `"rendering"` mode is refused
|
|
116
|
+
* (`FORBIDDEN`); a channel in `"http"` mode, or any other kind in `"socket"` mode, is
|
|
117
|
+
* `RPC_NOT_FOUND`; the
|
|
104
118
|
* envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
|
|
105
119
|
* a cycle or an accessor), and exactly `{ input }` (`INVALID_INPUT` with no issues);
|
|
106
120
|
* the group's middleware runs with no input; the input must pass the schema
|
|
@@ -108,8 +122,21 @@ export declare function isJsonMediaType(contentType: string | null): boolean;
|
|
|
108
122
|
* with no issues); the procedure's middleware runs with the validated input; then the
|
|
109
123
|
* handler. The handler's strict JSON result is returned with status 200, and its
|
|
110
124
|
* declared errors with their status. `forbidden()` thrown from middleware or the
|
|
111
|
-
* handler gives `FORBIDDEN
|
|
112
|
-
*
|
|
125
|
+
* handler gives `FORBIDDEN`, `notFound()` a 404 with `{ notFound: null }` and
|
|
126
|
+
* `redirect(to)` a 303 with `{ redirect: { to } }`; a middleware that calls `next` twice
|
|
127
|
+
* or doesn't return its result gives `INTERNAL`.
|
|
128
|
+
*
|
|
129
|
+
* A stream's handler returns an iterable instead of a result. Its iterator goes to
|
|
130
|
+
* `start`, and the call goes on until the stream ends: the reply is then a 200 with
|
|
131
|
+
* `null` body, or the failure the stream ended with. Without `start`, a stream fails
|
|
132
|
+
* with `INTERNAL`.
|
|
133
|
+
*
|
|
134
|
+
* A channel runs like a stream, and its handler also receives `messages`, read from
|
|
135
|
+
* `inbox` and validated with its message schema. A message that fails validation, or a
|
|
136
|
+
* protocol violation the inbox reports, ends the call with `INVALID_INPUT`.
|
|
137
|
+
*
|
|
138
|
+
* Middleware and handlers set cookies and headers through `effects.control`; the caller
|
|
139
|
+
* commits and applies them.
|
|
113
140
|
*
|
|
114
141
|
* @param registry - The application's RPC groups.
|
|
115
142
|
* @param path - The request path.
|
|
@@ -117,20 +144,24 @@ export declare function isJsonMediaType(contentType: string | null): boolean;
|
|
|
117
144
|
* @param scope - The request scope whose context the call receives.
|
|
118
145
|
* @param application - The application binding the scope must belong to.
|
|
119
146
|
* @param request - The request the scope must be bound to.
|
|
120
|
-
* @param mode - `"http"` for browser requests (the default)
|
|
121
|
-
* made during server rendering.
|
|
147
|
+
* @param mode - `"http"` for browser requests (the default), `"socket"` for websocket
|
|
148
|
+
* upgrades, or `"rendering"` for calls made during server rendering.
|
|
122
149
|
* @param signal - The call's abort signal. Defaults to `request`'s signal.
|
|
150
|
+
* @param effects - Collects the call's cookies and headers. Defaults to fresh effects
|
|
151
|
+
* nothing reads.
|
|
152
|
+
* @param start - Receives a stream's or channel's iterator once its handler returned it.
|
|
153
|
+
* @param inbox - A channel's incoming messages.
|
|
123
154
|
* @returns The reply to send.
|
|
124
155
|
*/
|
|
125
|
-
export declare function dispatch(registry: Registry, path: string, envelope: unknown, scope: RequestScope, application: ApplicationBinding, request: Request, mode?: "http" | "rendering", signal?: AbortSignal): Promise<Reply>;
|
|
156
|
+
export declare function dispatch(registry: Registry, path: string, envelope: unknown, scope: RequestScope, application: ApplicationBinding, request: Request, mode?: "http" | "socket" | "rendering", signal?: AbortSignal, effects?: ResponseEffects, start?: (stream: StreamStart) => void, inbox?: ChannelInbox): Promise<Reply>;
|
|
126
157
|
/**
|
|
127
|
-
* Options for the generated `handleRequest` in `server.generated.ts`.
|
|
158
|
+
* Options for the generated `handleRequest` and `handleUpgrade` in `server.generated.ts`.
|
|
128
159
|
*/
|
|
129
160
|
export interface HandleOptions {
|
|
130
161
|
/**
|
|
131
162
|
* Hostnames RPCs are answered for, matched like Angular's `allowedHosts`: exactly,
|
|
132
163
|
* `*.example.com` for subdomains only, or `*` for any host. An empty list refuses every
|
|
133
|
-
* RPC. Pass the same array to `AngularNodeAppEngine`.
|
|
164
|
+
* RPC. Pass the same array to `AngularNodeAppEngine`, `handleRequest` and `handleUpgrade`.
|
|
134
165
|
*/
|
|
135
166
|
readonly allowedHosts: readonly string[];
|
|
136
167
|
/**
|
|
@@ -140,6 +171,11 @@ export interface HandleOptions {
|
|
|
140
171
|
*/
|
|
141
172
|
readonly origins?: readonly string[];
|
|
142
173
|
}
|
|
174
|
+
/** The plain-text 400 for an RPC to a host that isn't allowed, logged. */
|
|
175
|
+
export declare function hostRefusal(hostname: string): Response;
|
|
176
|
+
export declare function hostAllowed(hostname: string, allowedHosts: readonly string[]): boolean;
|
|
177
|
+
/** Why `request` can't be proven same-origin, or `undefined` when it can. */
|
|
178
|
+
export declare function crossSiteReason(request: Request, origins: readonly string[]): string | undefined;
|
|
143
179
|
/**
|
|
144
180
|
* Answers an RPC HTTP request, or returns `null` for any other request.
|
|
145
181
|
*
|
|
@@ -160,6 +196,18 @@ export interface HandleOptions {
|
|
|
160
196
|
* JSON responses carry `Cache-Control: private, no-store`, `Vary: Cookie` and
|
|
161
197
|
* `X-Content-Type-Options: nosniff`.
|
|
162
198
|
*
|
|
199
|
+
* Once the call reached `dispatch`, its response carries the headers and cookies the
|
|
200
|
+
* call set, whatever its outcome. Launch's own headers replace the call's headers of the
|
|
201
|
+
* same name, and each cookie adds a `Set-Cookie` header.
|
|
202
|
+
*
|
|
203
|
+
* A stream answers like any call until its handler returns its iterable. From then on the
|
|
204
|
+
* response is a 200 `text/event-stream` (see `eventStream`) with
|
|
205
|
+
* `Cache-Control: private, no-store, no-transform`, `Vary: Cookie`,
|
|
206
|
+
* `X-Content-Type-Options: nosniff` and `X-Accel-Buffering: no`, and the call's signal
|
|
207
|
+
* also aborts when the host cancels the body. The response's cookies and headers are the
|
|
208
|
+
* ones set when the handler returned its iterable: setting a cookie later throws, and
|
|
209
|
+
* later header changes are ignored.
|
|
210
|
+
*
|
|
163
211
|
* @typeParam Definition - The application's context definition.
|
|
164
212
|
* @param registry - The application's RPC groups.
|
|
165
213
|
* @param application - The application binding.
|
|
@@ -168,4 +216,7 @@ export interface HandleOptions {
|
|
|
168
216
|
* @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
|
|
169
217
|
*/
|
|
170
218
|
export declare function handleRpc<Definition extends ContextDefinition<unknown>>(registry: Registry, application: ApplicationBinding<Definition>, request: Request, { allowedHosts, origins }: HandleOptions): Promise<Response | null>;
|
|
219
|
+
/** The call's headers, then Launch's own over them, then the call's cookies. */
|
|
220
|
+
export declare function responseHeaders(own: Readonly<Record<string, string>>, effects: ResponseEffects | undefined): Headers;
|
|
221
|
+
export declare function response(reply: Reply, effects?: ResponseEffects): Response;
|
|
171
222
|
export {};
|
package/server/dispatch.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { frameworkFailures } from "../client.js";
|
|
2
|
-
import { serializeJson } from "../json.js";
|
|
2
|
+
import { parseJson, serializeJson } from "../json.js";
|
|
3
3
|
import { inputIssues } from "../input-issues.js";
|
|
4
|
+
import { channelMessages, MessageRefused } from "./channel-messages.js";
|
|
4
5
|
import { declaredFailures } from "./errors.js";
|
|
6
|
+
import { eventStream } from "./event-stream.js";
|
|
5
7
|
import { outcomeOf } from "./outcomes.js";
|
|
8
|
+
import { createResponseEffects, } from "./response-effects.js";
|
|
6
9
|
const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v1");
|
|
7
10
|
const bindingHeader = "x-loozo-launch-scope";
|
|
8
11
|
/**
|
|
@@ -70,6 +73,16 @@ export function assertBoundScope(scope, application, request) {
|
|
|
70
73
|
throw new Error("Launch request/application scope binding mismatch");
|
|
71
74
|
}
|
|
72
75
|
}
|
|
76
|
+
function outcomeReply(outcome) {
|
|
77
|
+
if (outcome.kind === "forbidden") {
|
|
78
|
+
return failure("FORBIDDEN");
|
|
79
|
+
}
|
|
80
|
+
if (outcome.kind === "notFound") {
|
|
81
|
+
return { status: 404, body: { notFound: null } };
|
|
82
|
+
}
|
|
83
|
+
// No Location header: fetch then hands the 303 to the client instead of following it.
|
|
84
|
+
return { status: 303, body: { redirect: { to: outcome.to } } };
|
|
85
|
+
}
|
|
73
86
|
export function failure(code) {
|
|
74
87
|
const frame = frameworkFailures[code];
|
|
75
88
|
return { status: frame.status, body: { error: { code, message: frame.message, data: null } } };
|
|
@@ -184,7 +197,9 @@ async function declaredReply(procedure, error) {
|
|
|
184
197
|
*
|
|
185
198
|
* In order: the scope must belong to `application` and `request` (`INTERNAL`); the
|
|
186
199
|
* path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
|
|
187
|
-
* (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused
|
|
200
|
+
* (`RPC_NOT_FOUND`); a mutation, stream or channel in `"rendering"` mode is refused
|
|
201
|
+
* (`FORBIDDEN`); a channel in `"http"` mode, or any other kind in `"socket"` mode, is
|
|
202
|
+
* `RPC_NOT_FOUND`; the
|
|
188
203
|
* envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
|
|
189
204
|
* a cycle or an accessor), and exactly `{ input }` (`INVALID_INPUT` with no issues);
|
|
190
205
|
* the group's middleware runs with no input; the input must pass the schema
|
|
@@ -192,8 +207,21 @@ async function declaredReply(procedure, error) {
|
|
|
192
207
|
* with no issues); the procedure's middleware runs with the validated input; then the
|
|
193
208
|
* handler. The handler's strict JSON result is returned with status 200, and its
|
|
194
209
|
* declared errors with their status. `forbidden()` thrown from middleware or the
|
|
195
|
-
* handler gives `FORBIDDEN
|
|
196
|
-
*
|
|
210
|
+
* handler gives `FORBIDDEN`, `notFound()` a 404 with `{ notFound: null }` and
|
|
211
|
+
* `redirect(to)` a 303 with `{ redirect: { to } }`; a middleware that calls `next` twice
|
|
212
|
+
* or doesn't return its result gives `INTERNAL`.
|
|
213
|
+
*
|
|
214
|
+
* A stream's handler returns an iterable instead of a result. Its iterator goes to
|
|
215
|
+
* `start`, and the call goes on until the stream ends: the reply is then a 200 with
|
|
216
|
+
* `null` body, or the failure the stream ended with. Without `start`, a stream fails
|
|
217
|
+
* with `INTERNAL`.
|
|
218
|
+
*
|
|
219
|
+
* A channel runs like a stream, and its handler also receives `messages`, read from
|
|
220
|
+
* `inbox` and validated with its message schema. A message that fails validation, or a
|
|
221
|
+
* protocol violation the inbox reports, ends the call with `INVALID_INPUT`.
|
|
222
|
+
*
|
|
223
|
+
* Middleware and handlers set cookies and headers through `effects.control`; the caller
|
|
224
|
+
* commits and applies them.
|
|
197
225
|
*
|
|
198
226
|
* @param registry - The application's RPC groups.
|
|
199
227
|
* @param path - The request path.
|
|
@@ -201,12 +229,16 @@ async function declaredReply(procedure, error) {
|
|
|
201
229
|
* @param scope - The request scope whose context the call receives.
|
|
202
230
|
* @param application - The application binding the scope must belong to.
|
|
203
231
|
* @param request - The request the scope must be bound to.
|
|
204
|
-
* @param mode - `"http"` for browser requests (the default)
|
|
205
|
-
* made during server rendering.
|
|
232
|
+
* @param mode - `"http"` for browser requests (the default), `"socket"` for websocket
|
|
233
|
+
* upgrades, or `"rendering"` for calls made during server rendering.
|
|
206
234
|
* @param signal - The call's abort signal. Defaults to `request`'s signal.
|
|
235
|
+
* @param effects - Collects the call's cookies and headers. Defaults to fresh effects
|
|
236
|
+
* nothing reads.
|
|
237
|
+
* @param start - Receives a stream's or channel's iterator once its handler returned it.
|
|
238
|
+
* @param inbox - A channel's incoming messages.
|
|
207
239
|
* @returns The reply to send.
|
|
208
240
|
*/
|
|
209
|
-
export async function dispatch(registry, path, envelope, scope, application, request, mode = "http", signal = request.signal) {
|
|
241
|
+
export async function dispatch(registry, path, envelope, scope, application, request, mode = "http", signal = request.signal, effects = createResponseEffects(), start, inbox) {
|
|
210
242
|
try {
|
|
211
243
|
assertBoundScope(scope, application, request);
|
|
212
244
|
const parts = /^\/_rpc\/([A-Za-z_][A-Za-z0-9_]*)\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
|
|
@@ -218,14 +250,23 @@ export async function dispatch(registry, path, envelope, scope, application, req
|
|
|
218
250
|
return failure("RPC_NOT_FOUND");
|
|
219
251
|
}
|
|
220
252
|
const procedure = group.procedures[parts[2]];
|
|
221
|
-
if (procedure.kind !== "query" &&
|
|
253
|
+
if (procedure.kind !== "query" &&
|
|
254
|
+
procedure.kind !== "mutation" &&
|
|
255
|
+
procedure.kind !== "stream" &&
|
|
256
|
+
procedure.kind !== "channel") {
|
|
222
257
|
throw new Error("Launch registry contains an unsupported procedure");
|
|
223
258
|
}
|
|
224
259
|
// Rendering never performs writes, even for unmarked HttpClient calls or
|
|
225
|
-
// callers/interceptors that relabel a generated method or enable caching.
|
|
226
|
-
|
|
260
|
+
// callers/interceptors that relabel a generated method or enable caching. Streams
|
|
261
|
+
// and channels don't finish, so they don't run during rendering either.
|
|
262
|
+
if (mode === "rendering" && procedure.kind !== "query") {
|
|
227
263
|
return failure("FORBIDDEN");
|
|
228
264
|
}
|
|
265
|
+
// A channel exists only as a websocket, and a websocket carries only channels.
|
|
266
|
+
const isChannel = procedure.kind === "channel";
|
|
267
|
+
if ((mode === "http" && isChannel) || (mode === "socket" && !isChannel)) {
|
|
268
|
+
return failure("RPC_NOT_FOUND");
|
|
269
|
+
}
|
|
229
270
|
// Even direct transport crosses the exact same strict JSON boundary.
|
|
230
271
|
const normalized = JSON.parse(serializeJson(envelope));
|
|
231
272
|
if (typeof normalized !== "object" ||
|
|
@@ -236,9 +277,10 @@ export async function dispatch(registry, path, envelope, scope, application, req
|
|
|
236
277
|
return invalidInput();
|
|
237
278
|
}
|
|
238
279
|
let reply;
|
|
280
|
+
const response = effects.control;
|
|
239
281
|
try {
|
|
240
282
|
// Group middleware runs before validation, so it never sees the raw input.
|
|
241
|
-
await runChain(group.use, scope.value, { input: undefined, request, signal }, async (groupContext) => {
|
|
283
|
+
await runChain(group.use, scope.value, { input: undefined, request, signal, response }, async (groupContext) => {
|
|
242
284
|
let input;
|
|
243
285
|
if (procedure.input) {
|
|
244
286
|
const parsed = await procedure.input["~standard"].validate(normalized.input);
|
|
@@ -252,16 +294,44 @@ export async function dispatch(registry, path, envelope, scope, application, req
|
|
|
252
294
|
reply = invalidInput();
|
|
253
295
|
return;
|
|
254
296
|
}
|
|
255
|
-
await runChain(procedure.use, groupContext, { input, request, signal }, async (context) => {
|
|
256
|
-
const
|
|
257
|
-
|
|
297
|
+
await runChain(procedure.use, groupContext, { input, request, signal, response }, async (context) => {
|
|
298
|
+
const args = { context, input, request, signal, response };
|
|
299
|
+
if (isChannel) {
|
|
300
|
+
// The caller left while the pipeline ran: the handler doesn't run, and the
|
|
301
|
+
// middleware's `next()` resolves.
|
|
302
|
+
if (signal.aborted) {
|
|
303
|
+
reply = { status: 200, body: null };
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (!inbox || !procedure.message) {
|
|
307
|
+
throw new Error("Launch channels need a websocket and a message schema");
|
|
308
|
+
}
|
|
309
|
+
args.messages = channelMessages(inbox, procedure.message);
|
|
310
|
+
}
|
|
311
|
+
const output = await procedure.handler(args);
|
|
312
|
+
if (procedure.kind !== "stream" && !isChannel) {
|
|
313
|
+
reply = { status: 200, body: JSON.parse(serializeJson(output)) };
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if (!start) {
|
|
317
|
+
throw new Error("Launch streams need an HTTP response to run in");
|
|
318
|
+
}
|
|
319
|
+
const iterator = output[Symbol.asyncIterator]();
|
|
320
|
+
const finished = Promise.withResolvers();
|
|
321
|
+
start({ iterator, finished });
|
|
322
|
+
await finished.promise;
|
|
323
|
+
reply = { status: 200, body: null };
|
|
258
324
|
});
|
|
259
325
|
});
|
|
260
326
|
}
|
|
261
327
|
catch (error) {
|
|
262
328
|
const outcome = outcomeOf(error);
|
|
263
|
-
if (outcome
|
|
264
|
-
return
|
|
329
|
+
if (outcome !== undefined) {
|
|
330
|
+
return outcomeReply(outcome);
|
|
331
|
+
}
|
|
332
|
+
// The caller sent a bad message: its own fault, not an unexpected failure.
|
|
333
|
+
if (error instanceof MessageRefused) {
|
|
334
|
+
return invalidInput(error.issues);
|
|
265
335
|
}
|
|
266
336
|
return await declaredReply(procedure, error);
|
|
267
337
|
}
|
|
@@ -275,7 +345,15 @@ export async function dispatch(registry, path, envelope, scope, application, req
|
|
|
275
345
|
return failure("INTERNAL");
|
|
276
346
|
}
|
|
277
347
|
}
|
|
278
|
-
|
|
348
|
+
/** The plain-text 400 for an RPC to a host that isn't allowed, logged. */
|
|
349
|
+
export function hostRefusal(hostname) {
|
|
350
|
+
console.error(`Launch refused an RPC for host ${hostname}`);
|
|
351
|
+
return new Response("Host not allowed", {
|
|
352
|
+
status: 400,
|
|
353
|
+
headers: { "content-type": "text/plain", "x-content-type-options": "nosniff" },
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
export function hostAllowed(hostname, allowedHosts) {
|
|
279
357
|
for (const allowed of allowedHosts) {
|
|
280
358
|
if (allowed === "*" || allowed === hostname) {
|
|
281
359
|
return true;
|
|
@@ -287,7 +365,7 @@ function hostAllowed(hostname, allowedHosts) {
|
|
|
287
365
|
return false;
|
|
288
366
|
}
|
|
289
367
|
/** Why `request` can't be proven same-origin, or `undefined` when it can. */
|
|
290
|
-
function crossSiteReason(request, origins) {
|
|
368
|
+
export function crossSiteReason(request, origins) {
|
|
291
369
|
const site = request.headers.get("sec-fetch-site");
|
|
292
370
|
const origin = request.headers.get("origin");
|
|
293
371
|
if (origin !== null && origins.includes(origin)) {
|
|
@@ -328,6 +406,18 @@ function crossSiteReason(request, origins) {
|
|
|
328
406
|
* JSON responses carry `Cache-Control: private, no-store`, `Vary: Cookie` and
|
|
329
407
|
* `X-Content-Type-Options: nosniff`.
|
|
330
408
|
*
|
|
409
|
+
* Once the call reached `dispatch`, its response carries the headers and cookies the
|
|
410
|
+
* call set, whatever its outcome. Launch's own headers replace the call's headers of the
|
|
411
|
+
* same name, and each cookie adds a `Set-Cookie` header.
|
|
412
|
+
*
|
|
413
|
+
* A stream answers like any call until its handler returns its iterable. From then on the
|
|
414
|
+
* response is a 200 `text/event-stream` (see `eventStream`) with
|
|
415
|
+
* `Cache-Control: private, no-store, no-transform`, `Vary: Cookie`,
|
|
416
|
+
* `X-Content-Type-Options: nosniff` and `X-Accel-Buffering: no`, and the call's signal
|
|
417
|
+
* also aborts when the host cancels the body. The response's cookies and headers are the
|
|
418
|
+
* ones set when the handler returned its iterable: setting a cookie later throws, and
|
|
419
|
+
* later header changes are ignored.
|
|
420
|
+
*
|
|
331
421
|
* @typeParam Definition - The application's context definition.
|
|
332
422
|
* @param registry - The application's RPC groups.
|
|
333
423
|
* @param application - The application binding.
|
|
@@ -341,11 +431,7 @@ export async function handleRpc(registry, application, request, { allowedHosts,
|
|
|
341
431
|
return null;
|
|
342
432
|
}
|
|
343
433
|
if (!hostAllowed(url.hostname, allowedHosts)) {
|
|
344
|
-
|
|
345
|
-
return new Response("Host not allowed", {
|
|
346
|
-
status: 400,
|
|
347
|
-
headers: { "content-type": "text/plain", "x-content-type-options": "nosniff" },
|
|
348
|
-
});
|
|
434
|
+
return hostRefusal(url.hostname);
|
|
349
435
|
}
|
|
350
436
|
if (request.method !== "POST" ||
|
|
351
437
|
!isJsonMediaType(request.headers.get("content-type")) ||
|
|
@@ -357,32 +443,66 @@ export async function handleRpc(registry, application, request, { allowedHosts,
|
|
|
357
443
|
console.error(`Launch refused a cross-origin RPC: ${crossSite}`);
|
|
358
444
|
return response(failure("FORBIDDEN"));
|
|
359
445
|
}
|
|
446
|
+
const effects = createResponseEffects();
|
|
360
447
|
let reply;
|
|
361
448
|
try {
|
|
362
449
|
const scope = await createRequestScope(application, request);
|
|
363
450
|
let envelope;
|
|
364
451
|
try {
|
|
365
|
-
envelope = await request.
|
|
452
|
+
envelope = parseJson(await request.text());
|
|
366
453
|
}
|
|
367
454
|
catch {
|
|
368
455
|
return response(invalidInput());
|
|
369
456
|
}
|
|
370
|
-
|
|
457
|
+
// Hosts cancel a streaming body when its client goes away; that aborts the call too.
|
|
458
|
+
const cancel = new AbortController();
|
|
459
|
+
const signal = AbortSignal.any([scope.request.signal, cancel.signal]);
|
|
460
|
+
const started = Promise.withResolvers();
|
|
461
|
+
const outcome = dispatch(registry, url.pathname, envelope, scope, application, scope.request, "http", signal, effects, started.resolve);
|
|
462
|
+
// Failures before a stream's handler returned are ordinary replies.
|
|
463
|
+
const first = await Promise.race([outcome, started.promise]);
|
|
464
|
+
if ("iterator" in first) {
|
|
465
|
+
// The response starts now; the rest of the call is the stream itself.
|
|
466
|
+
effects.commit();
|
|
467
|
+
return streamResponse(eventStream(first, outcome, cancel, signal), effects);
|
|
468
|
+
}
|
|
469
|
+
reply = first;
|
|
371
470
|
}
|
|
372
471
|
catch (error) {
|
|
373
472
|
console.error("Launch context failed", error);
|
|
374
473
|
reply = failure("INTERNAL");
|
|
375
474
|
}
|
|
376
|
-
|
|
475
|
+
effects.commit();
|
|
476
|
+
return response(reply, effects);
|
|
377
477
|
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
478
|
+
/** The call's headers, then Launch's own over them, then the call's cookies. */
|
|
479
|
+
export function responseHeaders(own, effects) {
|
|
480
|
+
const headers = new Headers(effects?.headers);
|
|
481
|
+
for (const [name, value] of Object.entries(own)) {
|
|
482
|
+
headers.set(name, value);
|
|
483
|
+
}
|
|
484
|
+
for (const cookie of effects?.cookies ?? []) {
|
|
485
|
+
headers.append("set-cookie", cookie);
|
|
486
|
+
}
|
|
487
|
+
return headers;
|
|
488
|
+
}
|
|
489
|
+
function streamResponse(body, effects) {
|
|
490
|
+
const headers = responseHeaders({
|
|
491
|
+
"content-type": "text/event-stream",
|
|
492
|
+
"cache-control": "private, no-store, no-transform",
|
|
493
|
+
vary: "Cookie",
|
|
494
|
+
"x-content-type-options": "nosniff",
|
|
495
|
+
// nginx buffers proxied responses unless told not to.
|
|
496
|
+
"x-accel-buffering": "no",
|
|
497
|
+
}, effects);
|
|
498
|
+
return new Response(body, { status: 200, headers });
|
|
499
|
+
}
|
|
500
|
+
export function response(reply, effects) {
|
|
501
|
+
const headers = responseHeaders({
|
|
502
|
+
"content-type": "application/json",
|
|
503
|
+
"cache-control": "private, no-store",
|
|
504
|
+
vary: "Cookie",
|
|
505
|
+
"x-content-type-options": "nosniff",
|
|
506
|
+
}, effects);
|
|
507
|
+
return new Response(serializeJson(reply.body), { status: reply.status, headers });
|
|
388
508
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Reply } from "./dispatch.js";
|
|
2
|
+
/** How often a stream sends a comment, so idle proxies keep its connection open. */
|
|
3
|
+
export declare const keepAliveMs = 15000;
|
|
4
|
+
/**
|
|
5
|
+
* A stream whose handler returned its iterable: the response can start.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* Internal. `dispatch` hands it over and waits for `finished`: resolving it ends the
|
|
9
|
+
* handler's part of the call, rejecting it fails the call with that error.
|
|
10
|
+
*/
|
|
11
|
+
export interface StreamStart {
|
|
12
|
+
/** The handler's iterator. */
|
|
13
|
+
readonly iterator: AsyncIterator<unknown>;
|
|
14
|
+
/** Settles the handler's part of the call. */
|
|
15
|
+
readonly finished: {
|
|
16
|
+
readonly resolve: () => void;
|
|
17
|
+
readonly reject: (error: unknown) => void;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Ends the handler's part of a stream or channel that stopped early, such as when its caller
|
|
22
|
+
* went away.
|
|
23
|
+
*
|
|
24
|
+
* @remarks
|
|
25
|
+
* Internal. Lets the handler's pending step finish, then asks the iterator to return, which
|
|
26
|
+
* runs a generator's `finally` blocks. The step's failure, if any, settles the call, but only
|
|
27
|
+
* after that cleanup ran.
|
|
28
|
+
*
|
|
29
|
+
* @param start - The started stream or channel.
|
|
30
|
+
* @param pending - The handler's last requested step, if any.
|
|
31
|
+
*/
|
|
32
|
+
export declare function settleStopped(start: StreamStart, pending: Promise<IteratorResult<unknown>> | undefined): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* The frame that ends a failed stream or channel: the reply's body with its status, as
|
|
35
|
+
* `{ status, error }`, `{ status, redirect }` or `{ status, notFound }`.
|
|
36
|
+
*
|
|
37
|
+
* @param reply - The call's failure reply.
|
|
38
|
+
* @returns The frame as strict JSON text.
|
|
39
|
+
*/
|
|
40
|
+
export declare function failureFrame(reply: Reply): string;
|
|
41
|
+
/**
|
|
42
|
+
* The `text/event-stream` body of a started stream.
|
|
43
|
+
*
|
|
44
|
+
* @remarks
|
|
45
|
+
* Internal. Sends one `value` event per yielded value, then, once the whole call settled
|
|
46
|
+
* (`outcome`, middleware included), one `end` event or one `error` event whose data is
|
|
47
|
+
* the reply's frame with its status: `{ status, error }`, `{ status, redirect }` or
|
|
48
|
+
* `{ status, notFound }`. A comment goes out every {@link keepAliveMs}.
|
|
49
|
+
*
|
|
50
|
+
* Pull-based, so a slow reader pauses the handler. A yielded value that isn't strict JSON
|
|
51
|
+
* fails the call. The stream stops when `signal` aborts, which it does when the host
|
|
52
|
+
* cancels the body or aborts the request: the body errors, the handler's pending step is
|
|
53
|
+
* awaited and the iterator asked to return, which runs a generator's `finally` blocks once
|
|
54
|
+
* it next yields. The handler's part of the call then ends, with the failure if that step
|
|
55
|
+
* threw, so middleware that wraps the stream never cleans up under a running handler.
|
|
56
|
+
*
|
|
57
|
+
* @param start - The started stream.
|
|
58
|
+
* @param outcome - The whole call's reply, from `dispatch`.
|
|
59
|
+
* @param cancel - Aborted when the body is cancelled.
|
|
60
|
+
* @param signal - The call's signal: it follows `cancel` and the request's signal.
|
|
61
|
+
* @returns The response body.
|
|
62
|
+
*/
|
|
63
|
+
export declare function eventStream(start: StreamStart, outcome: Promise<Reply>, cancel: AbortController, signal: AbortSignal): ReadableStream<Uint8Array>;
|