@loozo/angular-launch 0.0.4 → 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 +695 -102
- package/builders/application.d.ts +4 -0
- package/builders/application.js +71 -0
- package/builders/options.d.ts +10 -0
- package/builders/options.js +64 -0
- package/builders/serve.d.ts +8 -0
- package/builders/serve.js +248 -0
- package/builders.json +15 -0
- package/channel.d.ts +53 -0
- package/channel.js +231 -0
- package/client.d.ts +59 -16
- package/client.js +3 -2
- package/connect.d.ts +201 -0
- package/connect.js +148 -0
- package/generated.d.ts +1 -1
- package/generated.js +86 -3
- package/generation/context-file.d.ts +2 -0
- package/generation/context-file.js +3 -0
- package/generation/index.js +77 -36
- 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 +14 -4
- package/schemas/application.json +756 -0
- package/schemas/serve.json +153 -0
- package/server/backend.d.ts +42 -23
- package/server/backend.js +137 -47
- 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 +463 -181
- package/server/definitions.js +90 -103
- package/server/dispatch.d.ts +99 -20
- package/server/dispatch.js +337 -89
- 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 +6 -3
- package/server/index.js +2 -1
- package/server/outcomes.d.ts +75 -0
- package/server/outcomes.js +90 -0
- 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 +110 -22
- package/tanstack-query/generated.js +5 -2
- package/tanstack-query/queries.d.ts +8 -6
package/server/dispatch.js
CHANGED
|
@@ -1,7 +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";
|
|
7
|
+
import { outcomeOf } from "./outcomes.js";
|
|
8
|
+
import { createResponseEffects, } from "./response-effects.js";
|
|
5
9
|
const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v1");
|
|
6
10
|
const bindingHeader = "x-loozo-launch-scope";
|
|
7
11
|
/**
|
|
@@ -69,6 +73,16 @@ export function assertBoundScope(scope, application, request) {
|
|
|
69
73
|
throw new Error("Launch request/application scope binding mismatch");
|
|
70
74
|
}
|
|
71
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
|
+
}
|
|
72
86
|
export function failure(code) {
|
|
73
87
|
const frame = frameworkFailures[code];
|
|
74
88
|
return { status: frame.status, body: { error: { code, message: frame.message, data: null } } };
|
|
@@ -85,6 +99,93 @@ export function invalidInput(issues = []) {
|
|
|
85
99
|
export function isJsonMediaType(contentType) {
|
|
86
100
|
return contentType?.split(";", 1)[0].trim().toLowerCase() === "application/json";
|
|
87
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Runs `chain` in order around `last`, passing each middleware the context the previous
|
|
104
|
+
* one continued with.
|
|
105
|
+
*
|
|
106
|
+
* @remarks
|
|
107
|
+
* Rejects when a middleware throws, calls `next` twice (whether it then returns or
|
|
108
|
+
* throws) or returns anything other than its `next` result. A misused `next` never causes
|
|
109
|
+
* an unhandled rejection: each promise it returns is observed here. When the rest of the
|
|
110
|
+
* call a middleware started fails, that failure is logged unless the middleware rejected
|
|
111
|
+
* with that same value, as an awaited rethrow does: the middleware may have left it
|
|
112
|
+
* detached, or replaced it with another error such as `forbidden()`.
|
|
113
|
+
*/
|
|
114
|
+
async function runChain(chain, context, args, last) {
|
|
115
|
+
async function step(index, current) {
|
|
116
|
+
if (index === chain.length) {
|
|
117
|
+
await last(current);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const token = {};
|
|
121
|
+
let calls = 0;
|
|
122
|
+
let rest;
|
|
123
|
+
function next(added) {
|
|
124
|
+
calls += 1;
|
|
125
|
+
let continued;
|
|
126
|
+
if (calls > 1) {
|
|
127
|
+
continued = Promise.reject(new Error("Launch middleware called next() more than once"));
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
let merged = current;
|
|
131
|
+
if (added !== undefined) {
|
|
132
|
+
merged = { ...current, ...added };
|
|
133
|
+
}
|
|
134
|
+
continued = step(index + 1, merged).then(() => token);
|
|
135
|
+
rest = continued;
|
|
136
|
+
}
|
|
137
|
+
// A middleware that doesn't await this promise can't leave its rejection unhandled;
|
|
138
|
+
// one that awaits it still sees the rejection.
|
|
139
|
+
continued.catch(() => undefined);
|
|
140
|
+
return continued;
|
|
141
|
+
}
|
|
142
|
+
const run = chain[index].run;
|
|
143
|
+
let returned;
|
|
144
|
+
let thrown;
|
|
145
|
+
try {
|
|
146
|
+
returned = await run({ ...args, context: current, next });
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
thrown = { error };
|
|
150
|
+
}
|
|
151
|
+
// Whether it already failed or fails later, a failure the middleware didn't rethrow
|
|
152
|
+
// reaches nothing else.
|
|
153
|
+
rest?.catch((error) => {
|
|
154
|
+
if (thrown === undefined || error !== thrown.error) {
|
|
155
|
+
console.error("Launch RPC failed inside next(), and its middleware didn't rethrow it", error);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
if (calls > 1 || (thrown === undefined && returned !== token)) {
|
|
159
|
+
throw new Error("Launch middleware must call next() once and return its result", thrown === undefined ? undefined : { cause: thrown.error });
|
|
160
|
+
}
|
|
161
|
+
if (thrown !== undefined) {
|
|
162
|
+
throw thrown.error;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
await step(0, context);
|
|
166
|
+
}
|
|
167
|
+
async function declaredReply(procedure, error) {
|
|
168
|
+
let declared;
|
|
169
|
+
if (typeof error === "object" && error !== null) {
|
|
170
|
+
declared = procedure[declaredFailures]?.get(error);
|
|
171
|
+
}
|
|
172
|
+
if (!declared || !Object.hasOwn(procedure.errors, declared.code)) {
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
const definition = procedure.errors[declared.code];
|
|
176
|
+
if (definition !== declared.definition) {
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
const parsed = await definition.data["~standard"].validate(declared.data);
|
|
180
|
+
if (parsed.issues) {
|
|
181
|
+
throw new Error("Declared RPC error data failed validation", { cause: error });
|
|
182
|
+
}
|
|
183
|
+
const data = JSON.parse(serializeJson(parsed.value));
|
|
184
|
+
return {
|
|
185
|
+
status: definition.status,
|
|
186
|
+
body: { error: { code: declared.code, message: definition.message, data } },
|
|
187
|
+
};
|
|
188
|
+
}
|
|
88
189
|
/**
|
|
89
190
|
* Runs one procedure call within a request scope and produces its reply.
|
|
90
191
|
*
|
|
@@ -96,14 +197,31 @@ export function isJsonMediaType(contentType) {
|
|
|
96
197
|
*
|
|
97
198
|
* In order: the scope must belong to `application` and `request` (`INTERNAL`); the
|
|
98
199
|
* path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
|
|
99
|
-
* (`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
|
|
100
203
|
* envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
|
|
101
|
-
* a cycle or an accessor)
|
|
102
|
-
*
|
|
103
|
-
* or `null` without one (`INVALID_INPUT`
|
|
104
|
-
*
|
|
105
|
-
* handler's strict JSON result is returned with status 200, and its
|
|
106
|
-
* with their status.
|
|
204
|
+
* a cycle or an accessor), and exactly `{ input }` (`INVALID_INPUT` with no issues);
|
|
205
|
+
* the group's middleware runs with no input; the input must pass the schema
|
|
206
|
+
* (`INVALID_INPUT` with the schema's issues), or be `null` without one (`INVALID_INPUT`
|
|
207
|
+
* with no issues); the procedure's middleware runs with the validated input; then the
|
|
208
|
+
* handler. The handler's strict JSON result is returned with status 200, and its
|
|
209
|
+
* declared errors with their status. `forbidden()` thrown from middleware or the
|
|
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.
|
|
107
225
|
*
|
|
108
226
|
* @param registry - The application's RPC groups.
|
|
109
227
|
* @param path - The request path.
|
|
@@ -111,11 +229,16 @@ export function isJsonMediaType(contentType) {
|
|
|
111
229
|
* @param scope - The request scope whose context the call receives.
|
|
112
230
|
* @param application - The application binding the scope must belong to.
|
|
113
231
|
* @param request - The request the scope must be bound to.
|
|
114
|
-
* @param mode - `"http"` for browser requests (the default)
|
|
115
|
-
* 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.
|
|
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.
|
|
116
239
|
* @returns The reply to send.
|
|
117
240
|
*/
|
|
118
|
-
export async function dispatch(registry, path, envelope, scope, application, request, mode = "http") {
|
|
241
|
+
export async function dispatch(registry, path, envelope, scope, application, request, mode = "http", signal = request.signal, effects = createResponseEffects(), start, inbox) {
|
|
119
242
|
try {
|
|
120
243
|
assertBoundScope(scope, application, request);
|
|
121
244
|
const parts = /^\/_rpc\/([A-Za-z_][A-Za-z0-9_]*)\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
|
|
@@ -127,14 +250,23 @@ export async function dispatch(registry, path, envelope, scope, application, req
|
|
|
127
250
|
return failure("RPC_NOT_FOUND");
|
|
128
251
|
}
|
|
129
252
|
const procedure = group.procedures[parts[2]];
|
|
130
|
-
if (procedure.kind !== "query" &&
|
|
253
|
+
if (procedure.kind !== "query" &&
|
|
254
|
+
procedure.kind !== "mutation" &&
|
|
255
|
+
procedure.kind !== "stream" &&
|
|
256
|
+
procedure.kind !== "channel") {
|
|
131
257
|
throw new Error("Launch registry contains an unsupported procedure");
|
|
132
258
|
}
|
|
133
259
|
// Rendering never performs writes, even for unmarked HttpClient calls or
|
|
134
|
-
// callers/interceptors that relabel a generated method or enable caching.
|
|
135
|
-
|
|
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") {
|
|
136
263
|
return failure("FORBIDDEN");
|
|
137
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
|
+
}
|
|
138
270
|
// Even direct transport crosses the exact same strict JSON boundary.
|
|
139
271
|
const normalized = JSON.parse(serializeJson(envelope));
|
|
140
272
|
if (typeof normalized !== "object" ||
|
|
@@ -144,117 +276,233 @@ export async function dispatch(registry, path, envelope, scope, application, req
|
|
|
144
276
|
Object.keys(normalized).length !== 1) {
|
|
145
277
|
return invalidInput();
|
|
146
278
|
}
|
|
147
|
-
let
|
|
148
|
-
|
|
149
|
-
const parsed = await procedure.input["~standard"].validate(normalized.input);
|
|
150
|
-
if (parsed.issues) {
|
|
151
|
-
return invalidInput(inputIssues(parsed.issues));
|
|
152
|
-
}
|
|
153
|
-
input = parsed.value;
|
|
154
|
-
}
|
|
155
|
-
else if (normalized.input !== null) {
|
|
156
|
-
return invalidInput();
|
|
157
|
-
}
|
|
158
|
-
const context = scope.value;
|
|
159
|
-
for (const guard of group.canActivate) {
|
|
160
|
-
if (!(await guard({ context, request }))) {
|
|
161
|
-
return failure("FORBIDDEN");
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
for (const guard of procedure.canActivate) {
|
|
165
|
-
if (!(await guard({ context, request, input }))) {
|
|
166
|
-
return failure("FORBIDDEN");
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
let output;
|
|
279
|
+
let reply;
|
|
280
|
+
const response = effects.control;
|
|
170
281
|
try {
|
|
171
|
-
|
|
282
|
+
// Group middleware runs before validation, so it never sees the raw input.
|
|
283
|
+
await runChain(group.use, scope.value, { input: undefined, request, signal, response }, async (groupContext) => {
|
|
284
|
+
let input;
|
|
285
|
+
if (procedure.input) {
|
|
286
|
+
const parsed = await procedure.input["~standard"].validate(normalized.input);
|
|
287
|
+
if (parsed.issues) {
|
|
288
|
+
reply = invalidInput(inputIssues(parsed.issues));
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
input = parsed.value;
|
|
292
|
+
}
|
|
293
|
+
else if (normalized.input !== null) {
|
|
294
|
+
reply = invalidInput();
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
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 };
|
|
324
|
+
});
|
|
325
|
+
});
|
|
172
326
|
}
|
|
173
327
|
catch (error) {
|
|
174
|
-
|
|
175
|
-
if (
|
|
176
|
-
|
|
177
|
-
}
|
|
178
|
-
if (!declared || !Object.hasOwn(procedure.errors, declared.code)) {
|
|
179
|
-
throw error;
|
|
180
|
-
}
|
|
181
|
-
const definition = procedure.errors[declared.code];
|
|
182
|
-
if (definition !== declared.definition) {
|
|
183
|
-
throw error;
|
|
328
|
+
const outcome = outcomeOf(error);
|
|
329
|
+
if (outcome !== undefined) {
|
|
330
|
+
return outcomeReply(outcome);
|
|
184
331
|
}
|
|
185
|
-
|
|
186
|
-
if (
|
|
187
|
-
|
|
332
|
+
// The caller sent a bad message: its own fault, not an unexpected failure.
|
|
333
|
+
if (error instanceof MessageRefused) {
|
|
334
|
+
return invalidInput(error.issues);
|
|
188
335
|
}
|
|
189
|
-
|
|
190
|
-
return {
|
|
191
|
-
status: definition.status,
|
|
192
|
-
body: { error: { code: declared.code, message: definition.message, data } },
|
|
193
|
-
};
|
|
336
|
+
return await declaredReply(procedure, error);
|
|
194
337
|
}
|
|
195
|
-
|
|
338
|
+
if (!reply) {
|
|
339
|
+
throw new Error("Launch call finished without a reply");
|
|
340
|
+
}
|
|
341
|
+
return reply;
|
|
196
342
|
}
|
|
197
343
|
catch (error) {
|
|
198
344
|
console.error("Launch RPC failed", error);
|
|
199
345
|
return failure("INTERNAL");
|
|
200
346
|
}
|
|
201
347
|
}
|
|
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) {
|
|
357
|
+
for (const allowed of allowedHosts) {
|
|
358
|
+
if (allowed === "*" || allowed === hostname) {
|
|
359
|
+
return true;
|
|
360
|
+
}
|
|
361
|
+
if (allowed.startsWith("*.") && hostname.endsWith(allowed.slice(1))) {
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return false;
|
|
366
|
+
}
|
|
367
|
+
/** Why `request` can't be proven same-origin, or `undefined` when it can. */
|
|
368
|
+
export function crossSiteReason(request, origins) {
|
|
369
|
+
const site = request.headers.get("sec-fetch-site");
|
|
370
|
+
const origin = request.headers.get("origin");
|
|
371
|
+
if (origin !== null && origins.includes(origin)) {
|
|
372
|
+
return undefined;
|
|
373
|
+
}
|
|
374
|
+
if (site !== null) {
|
|
375
|
+
if (site === "same-origin") {
|
|
376
|
+
return undefined;
|
|
377
|
+
}
|
|
378
|
+
return `Sec-Fetch-Site is ${site}`;
|
|
379
|
+
}
|
|
380
|
+
if (origin !== null) {
|
|
381
|
+
const own = new URL(request.url).origin;
|
|
382
|
+
if (origin === own) {
|
|
383
|
+
return undefined;
|
|
384
|
+
}
|
|
385
|
+
return `Origin ${origin} isn't ${own}`;
|
|
386
|
+
}
|
|
387
|
+
return "neither Sec-Fetch-Site nor Origin was sent";
|
|
388
|
+
}
|
|
202
389
|
/**
|
|
203
390
|
* Answers an RPC HTTP request, or returns `null` for any other request.
|
|
204
391
|
*
|
|
205
392
|
* @remarks
|
|
206
393
|
* Internal: exported only from `@loozo/angular-launch/_server` for the generated
|
|
207
394
|
* `handleRequest` in `server.generated.ts`; call that instead.
|
|
208
|
-
* Any path starting with `/_rpc/` is treated as an RPC request.
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
*
|
|
395
|
+
* Any path starting with `/_rpc/` is treated as an RPC request. Its URL's hostname must
|
|
396
|
+
* be in `allowedHosts`, otherwise the reply is a plain-text 400 `Host not allowed`. It
|
|
397
|
+
* must then be a `POST` with an `application/json` content type and no query string,
|
|
398
|
+
* otherwise the reply is `INVALID_INPUT` with no issues. It must then come from the
|
|
399
|
+
* app's own origin, otherwise the reply is `FORBIDDEN`: an `Origin` listed in `origins`
|
|
400
|
+
* passes; otherwise `Sec-Fetch-Site`, when sent, must be `same-origin`; otherwise
|
|
401
|
+
* `Origin`, when sent, must equal the request URL's origin; a request with neither
|
|
402
|
+
* header is refused. No context is created for any of these refusals. A fresh context
|
|
403
|
+
* is then created before the body is parsed; if that fails the reply is `INTERNAL`, even
|
|
404
|
+
* when the body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with
|
|
405
|
+
* no issues.
|
|
406
|
+
* JSON responses carry `Cache-Control: private, no-store`, `Vary: Cookie` and
|
|
407
|
+
* `X-Content-Type-Options: nosniff`.
|
|
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.
|
|
214
420
|
*
|
|
215
421
|
* @typeParam Definition - The application's context definition.
|
|
216
422
|
* @param registry - The application's RPC groups.
|
|
217
423
|
* @param application - The application binding.
|
|
218
424
|
* @param request - The incoming server request.
|
|
425
|
+
* @param options - The allowed hosts and further allowed origins.
|
|
219
426
|
* @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
|
|
220
427
|
*/
|
|
221
|
-
export async function handleRpc(registry, application, request) {
|
|
428
|
+
export async function handleRpc(registry, application, request, { allowedHosts, origins = [] }) {
|
|
222
429
|
const url = new URL(request.url);
|
|
223
430
|
if (!url.pathname.startsWith("/_rpc/")) {
|
|
224
431
|
return null;
|
|
225
432
|
}
|
|
226
|
-
|
|
433
|
+
if (!hostAllowed(url.hostname, allowedHosts)) {
|
|
434
|
+
return hostRefusal(url.hostname);
|
|
435
|
+
}
|
|
227
436
|
if (request.method !== "POST" ||
|
|
228
437
|
!isJsonMediaType(request.headers.get("content-type")) ||
|
|
229
438
|
url.search !== "") {
|
|
230
|
-
|
|
439
|
+
return response(invalidInput());
|
|
440
|
+
}
|
|
441
|
+
const crossSite = crossSiteReason(request, origins);
|
|
442
|
+
if (crossSite !== undefined) {
|
|
443
|
+
console.error(`Launch refused a cross-origin RPC: ${crossSite}`);
|
|
444
|
+
return response(failure("FORBIDDEN"));
|
|
231
445
|
}
|
|
232
|
-
|
|
446
|
+
const effects = createResponseEffects();
|
|
447
|
+
let reply;
|
|
448
|
+
try {
|
|
449
|
+
const scope = await createRequestScope(application, request);
|
|
450
|
+
let envelope;
|
|
233
451
|
try {
|
|
234
|
-
|
|
235
|
-
let envelope;
|
|
236
|
-
try {
|
|
237
|
-
envelope = await request.json();
|
|
238
|
-
}
|
|
239
|
-
catch {
|
|
240
|
-
return response(invalidInput());
|
|
241
|
-
}
|
|
242
|
-
reply = await dispatch(registry, url.pathname, envelope, scope, application, scope.request);
|
|
452
|
+
envelope = parseJson(await request.text());
|
|
243
453
|
}
|
|
244
|
-
catch
|
|
245
|
-
|
|
246
|
-
|
|
454
|
+
catch {
|
|
455
|
+
return response(invalidInput());
|
|
456
|
+
}
|
|
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);
|
|
247
468
|
}
|
|
469
|
+
reply = first;
|
|
248
470
|
}
|
|
249
|
-
|
|
471
|
+
catch (error) {
|
|
472
|
+
console.error("Launch context failed", error);
|
|
473
|
+
reply = failure("INTERNAL");
|
|
474
|
+
}
|
|
475
|
+
effects.commit();
|
|
476
|
+
return response(reply, effects);
|
|
250
477
|
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
}
|
|
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 });
|
|
260
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>;
|