@loozo/angular-launch 0.0.4 → 0.0.5

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.
@@ -2,6 +2,7 @@ import { frameworkFailures } from "../client.js";
2
2
  import { serializeJson } from "../json.js";
3
3
  import { inputIssues } from "../input-issues.js";
4
4
  import { declaredFailures } from "./errors.js";
5
+ import { outcomeOf } from "./outcomes.js";
5
6
  const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v1");
6
7
  const bindingHeader = "x-loozo-launch-scope";
7
8
  /**
@@ -85,6 +86,93 @@ export function invalidInput(issues = []) {
85
86
  export function isJsonMediaType(contentType) {
86
87
  return contentType?.split(";", 1)[0].trim().toLowerCase() === "application/json";
87
88
  }
89
+ /**
90
+ * Runs `chain` in order around `last`, passing each middleware the context the previous
91
+ * one continued with.
92
+ *
93
+ * @remarks
94
+ * Rejects when a middleware throws, calls `next` twice (whether it then returns or
95
+ * throws) or returns anything other than its `next` result. A misused `next` never causes
96
+ * an unhandled rejection: each promise it returns is observed here. When the rest of the
97
+ * call a middleware started fails, that failure is logged unless the middleware rejected
98
+ * with that same value, as an awaited rethrow does: the middleware may have left it
99
+ * detached, or replaced it with another error such as `forbidden()`.
100
+ */
101
+ async function runChain(chain, context, args, last) {
102
+ async function step(index, current) {
103
+ if (index === chain.length) {
104
+ await last(current);
105
+ return;
106
+ }
107
+ const token = {};
108
+ let calls = 0;
109
+ let rest;
110
+ function next(added) {
111
+ calls += 1;
112
+ let continued;
113
+ if (calls > 1) {
114
+ continued = Promise.reject(new Error("Launch middleware called next() more than once"));
115
+ }
116
+ else {
117
+ let merged = current;
118
+ if (added !== undefined) {
119
+ merged = { ...current, ...added };
120
+ }
121
+ continued = step(index + 1, merged).then(() => token);
122
+ rest = continued;
123
+ }
124
+ // A middleware that doesn't await this promise can't leave its rejection unhandled;
125
+ // one that awaits it still sees the rejection.
126
+ continued.catch(() => undefined);
127
+ return continued;
128
+ }
129
+ const run = chain[index].run;
130
+ let returned;
131
+ let thrown;
132
+ try {
133
+ returned = await run({ ...args, context: current, next });
134
+ }
135
+ catch (error) {
136
+ thrown = { error };
137
+ }
138
+ // Whether it already failed or fails later, a failure the middleware didn't rethrow
139
+ // reaches nothing else.
140
+ rest?.catch((error) => {
141
+ if (thrown === undefined || error !== thrown.error) {
142
+ console.error("Launch RPC failed inside next(), and its middleware didn't rethrow it", error);
143
+ }
144
+ });
145
+ if (calls > 1 || (thrown === undefined && returned !== token)) {
146
+ throw new Error("Launch middleware must call next() once and return its result", thrown === undefined ? undefined : { cause: thrown.error });
147
+ }
148
+ if (thrown !== undefined) {
149
+ throw thrown.error;
150
+ }
151
+ }
152
+ await step(0, context);
153
+ }
154
+ async function declaredReply(procedure, error) {
155
+ let declared;
156
+ if (typeof error === "object" && error !== null) {
157
+ declared = procedure[declaredFailures]?.get(error);
158
+ }
159
+ if (!declared || !Object.hasOwn(procedure.errors, declared.code)) {
160
+ throw error;
161
+ }
162
+ const definition = procedure.errors[declared.code];
163
+ if (definition !== declared.definition) {
164
+ throw error;
165
+ }
166
+ const parsed = await definition.data["~standard"].validate(declared.data);
167
+ if (parsed.issues) {
168
+ throw new Error("Declared RPC error data failed validation", { cause: error });
169
+ }
170
+ const data = JSON.parse(serializeJson(parsed.value));
171
+ return {
172
+ status: definition.status,
173
+ body: { error: { code: declared.code, message: definition.message, data } },
174
+ };
175
+ }
88
176
  /**
89
177
  * Runs one procedure call within a request scope and produces its reply.
90
178
  *
@@ -98,12 +186,14 @@ export function isJsonMediaType(contentType) {
98
186
  * path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
99
187
  * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
100
188
  * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
101
- * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT` with no
102
- * issues) with input that passes the schema (`INVALID_INPUT` with the schema's issues),
103
- * or `null` without one (`INVALID_INPUT` with no issues); the group's
104
- * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
105
- * handler's strict JSON result is returned with status 200, and its declared errors
106
- * with their status.
189
+ * a cycle or an accessor), and exactly `{ input }` (`INVALID_INPUT` with no issues);
190
+ * the group's middleware runs with no input; the input must pass the schema
191
+ * (`INVALID_INPUT` with the schema's issues), or be `null` without one (`INVALID_INPUT`
192
+ * with no issues); the procedure's middleware runs with the validated input; then the
193
+ * handler. The handler's strict JSON result is returned with status 200, and its
194
+ * declared errors with their status. `forbidden()` thrown from middleware or the
195
+ * handler gives `FORBIDDEN`; a middleware that calls `next` twice or doesn't return its
196
+ * result gives `INTERNAL`.
107
197
  *
108
198
  * @param registry - The application's RPC groups.
109
199
  * @param path - The request path.
@@ -113,9 +203,10 @@ export function isJsonMediaType(contentType) {
113
203
  * @param request - The request the scope must be bound to.
114
204
  * @param mode - `"http"` for browser requests (the default) or `"rendering"` for calls
115
205
  * made during server rendering.
206
+ * @param signal - The call's abort signal. Defaults to `request`'s signal.
116
207
  * @returns The reply to send.
117
208
  */
118
- export async function dispatch(registry, path, envelope, scope, application, request, mode = "http") {
209
+ export async function dispatch(registry, path, envelope, scope, application, request, mode = "http", signal = request.signal) {
119
210
  try {
120
211
  assertBoundScope(scope, application, request);
121
212
  const parts = /^\/_rpc\/([A-Za-z_][A-Za-z0-9_]*)\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
@@ -144,107 +235,143 @@ export async function dispatch(registry, path, envelope, scope, application, req
144
235
  Object.keys(normalized).length !== 1) {
145
236
  return invalidInput();
146
237
  }
147
- let input;
148
- if (procedure.input) {
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;
238
+ let reply;
170
239
  try {
171
- output = await procedure.handler({ context, input });
240
+ // 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) => {
242
+ let input;
243
+ if (procedure.input) {
244
+ const parsed = await procedure.input["~standard"].validate(normalized.input);
245
+ if (parsed.issues) {
246
+ reply = invalidInput(inputIssues(parsed.issues));
247
+ return;
248
+ }
249
+ input = parsed.value;
250
+ }
251
+ else if (normalized.input !== null) {
252
+ reply = invalidInput();
253
+ return;
254
+ }
255
+ await runChain(procedure.use, groupContext, { input, request, signal }, async (context) => {
256
+ const output = await procedure.handler({ context, input, request, signal });
257
+ reply = { status: 200, body: JSON.parse(serializeJson(output)) };
258
+ });
259
+ });
172
260
  }
173
261
  catch (error) {
174
- let declared;
175
- if (typeof error === "object" && error !== null) {
176
- declared = procedure[declaredFailures]?.get(error);
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;
184
- }
185
- const parsed = await definition.data["~standard"].validate(declared.data);
186
- if (parsed.issues) {
187
- throw new Error("Declared RPC error data failed validation", { cause: error });
262
+ const outcome = outcomeOf(error);
263
+ if (outcome?.kind === "forbidden") {
264
+ return failure("FORBIDDEN");
188
265
  }
189
- const data = JSON.parse(serializeJson(parsed.value));
190
- return {
191
- status: definition.status,
192
- body: { error: { code: declared.code, message: definition.message, data } },
193
- };
266
+ return await declaredReply(procedure, error);
194
267
  }
195
- return { status: 200, body: JSON.parse(serializeJson(output)) };
268
+ if (!reply) {
269
+ throw new Error("Launch call finished without a reply");
270
+ }
271
+ return reply;
196
272
  }
197
273
  catch (error) {
198
274
  console.error("Launch RPC failed", error);
199
275
  return failure("INTERNAL");
200
276
  }
201
277
  }
278
+ function hostAllowed(hostname, allowedHosts) {
279
+ for (const allowed of allowedHosts) {
280
+ if (allowed === "*" || allowed === hostname) {
281
+ return true;
282
+ }
283
+ if (allowed.startsWith("*.") && hostname.endsWith(allowed.slice(1))) {
284
+ return true;
285
+ }
286
+ }
287
+ return false;
288
+ }
289
+ /** Why `request` can't be proven same-origin, or `undefined` when it can. */
290
+ function crossSiteReason(request, origins) {
291
+ const site = request.headers.get("sec-fetch-site");
292
+ const origin = request.headers.get("origin");
293
+ if (origin !== null && origins.includes(origin)) {
294
+ return undefined;
295
+ }
296
+ if (site !== null) {
297
+ if (site === "same-origin") {
298
+ return undefined;
299
+ }
300
+ return `Sec-Fetch-Site is ${site}`;
301
+ }
302
+ if (origin !== null) {
303
+ const own = new URL(request.url).origin;
304
+ if (origin === own) {
305
+ return undefined;
306
+ }
307
+ return `Origin ${origin} isn't ${own}`;
308
+ }
309
+ return "neither Sec-Fetch-Site nor Origin was sent";
310
+ }
202
311
  /**
203
312
  * Answers an RPC HTTP request, or returns `null` for any other request.
204
313
  *
205
314
  * @remarks
206
315
  * Internal: exported only from `@loozo/angular-launch/_server` for the generated
207
316
  * `handleRequest` in `server.generated.ts`; call that instead.
208
- * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
209
- * with an `application/json` content type and no query string, otherwise the reply is
210
- * `INVALID_INPUT` with no issues and no context is created. A fresh context is then
211
- * created before the body is parsed; if that fails the reply is `INTERNAL`, even when the
212
- * body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with no issues.
213
- * Responses are JSON with `Cache-Control: private, no-store` and `Vary: Cookie`.
317
+ * Any path starting with `/_rpc/` is treated as an RPC request. Its URL's hostname must
318
+ * be in `allowedHosts`, otherwise the reply is a plain-text 400 `Host not allowed`. It
319
+ * must then be a `POST` with an `application/json` content type and no query string,
320
+ * otherwise the reply is `INVALID_INPUT` with no issues. It must then come from the
321
+ * app's own origin, otherwise the reply is `FORBIDDEN`: an `Origin` listed in `origins`
322
+ * passes; otherwise `Sec-Fetch-Site`, when sent, must be `same-origin`; otherwise
323
+ * `Origin`, when sent, must equal the request URL's origin; a request with neither
324
+ * header is refused. No context is created for any of these refusals. A fresh context
325
+ * is then created before the body is parsed; if that fails the reply is `INTERNAL`, even
326
+ * when the body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with
327
+ * no issues.
328
+ * JSON responses carry `Cache-Control: private, no-store`, `Vary: Cookie` and
329
+ * `X-Content-Type-Options: nosniff`.
214
330
  *
215
331
  * @typeParam Definition - The application's context definition.
216
332
  * @param registry - The application's RPC groups.
217
333
  * @param application - The application binding.
218
334
  * @param request - The incoming server request.
335
+ * @param options - The allowed hosts and further allowed origins.
219
336
  * @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
220
337
  */
221
- export async function handleRpc(registry, application, request) {
338
+ export async function handleRpc(registry, application, request, { allowedHosts, origins = [] }) {
222
339
  const url = new URL(request.url);
223
340
  if (!url.pathname.startsWith("/_rpc/")) {
224
341
  return null;
225
342
  }
226
- let reply;
343
+ if (!hostAllowed(url.hostname, allowedHosts)) {
344
+ console.error(`Launch refused an RPC for host ${url.hostname}`);
345
+ return new Response("Host not allowed", {
346
+ status: 400,
347
+ headers: { "content-type": "text/plain", "x-content-type-options": "nosniff" },
348
+ });
349
+ }
227
350
  if (request.method !== "POST" ||
228
351
  !isJsonMediaType(request.headers.get("content-type")) ||
229
352
  url.search !== "") {
230
- reply = invalidInput();
353
+ return response(invalidInput());
354
+ }
355
+ const crossSite = crossSiteReason(request, origins);
356
+ if (crossSite !== undefined) {
357
+ console.error(`Launch refused a cross-origin RPC: ${crossSite}`);
358
+ return response(failure("FORBIDDEN"));
231
359
  }
232
- else {
360
+ let reply;
361
+ try {
362
+ const scope = await createRequestScope(application, request);
363
+ let envelope;
233
364
  try {
234
- const scope = await createRequestScope(application, request);
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);
365
+ envelope = await request.json();
243
366
  }
244
- catch (error) {
245
- console.error("Launch context failed", error);
246
- reply = failure("INTERNAL");
367
+ catch {
368
+ return response(invalidInput());
247
369
  }
370
+ reply = await dispatch(registry, url.pathname, envelope, scope, application, scope.request);
371
+ }
372
+ catch (error) {
373
+ console.error("Launch context failed", error);
374
+ reply = failure("INTERNAL");
248
375
  }
249
376
  return response(reply);
250
377
  }
@@ -255,6 +382,7 @@ function response(reply) {
255
382
  "content-type": "application/json",
256
383
  "cache-control": "private, no-store",
257
384
  vary: "Cookie",
385
+ "x-content-type-options": "nosniff",
258
386
  },
259
387
  });
260
388
  }
package/server/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- export { defineContext, defineRpc, query, mutation } from "./definitions.js";
2
- export type { Register, Context, ContextOf, ContextDefinition, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, Group, Guard, InputOf, OutputOf, Procedure, ProcedureDefinition, ProcedureGuard, ProcedureKind, ProcedureOptions, Schema, } from "./definitions.js";
1
+ export { defineContext, defineRpc, middleware } from "./definitions.js";
2
+ export { forbidden } from "./outcomes.js";
3
+ export type { Register, CallArgs, Context, ContextOf, ContextDefinition, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, Group, InputOf, MiddlewareDefinition, MiddlewareArgs, MiddlewareResult, OutputOf, Procedure, ProcedureBuilder, ProcedureDefinition, ProcedureKind, ProcedureOptions, Schema, } from "./definitions.js";
3
4
  export type { DeclaredFailure } from "./errors.js";
4
5
  export type { JsonShape } from "../json.js";
5
- export type { RequestScope } from "./dispatch.js";
6
+ export type { HandleOptions, RequestScope } from "./dispatch.js";
6
7
  export { finishLaunchRendering } from "./backend.js";
package/server/index.js CHANGED
@@ -1,2 +1,3 @@
1
- export { defineContext, defineRpc, query, mutation } from "./definitions.js";
1
+ export { defineContext, defineRpc, middleware } from "./definitions.js";
2
+ export { forbidden } from "./outcomes.js";
2
3
  export { finishLaunchRendering } from "./backend.js";
@@ -0,0 +1,26 @@
1
+ /** What a thrown outcome asks the server to answer with. Internal. */
2
+ export interface Outcome {
3
+ readonly kind: "forbidden";
4
+ }
5
+ /**
6
+ * Creates an error that refuses the call with `FORBIDDEN` when thrown from middleware
7
+ * or a handler.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * if (context.user === null) {
12
+ * throw forbidden();
13
+ * }
14
+ * ```
15
+ *
16
+ * @returns The error to `throw`.
17
+ */
18
+ export declare function forbidden(): Error;
19
+ /**
20
+ * Reads the outcome a thrown value carries, if it was created by an outcome factory.
21
+ * Internal.
22
+ *
23
+ * @param error - The thrown value.
24
+ * @returns The outcome, or `undefined` for any other value.
25
+ */
26
+ export declare function outcomeOf(error: unknown): Outcome | undefined;
@@ -0,0 +1,36 @@
1
+ // Keyed with Symbol.for so the brand survives the duplicate module copies a native SSR
2
+ // bundle may load, and non-enumerable so it never reaches JSON.
3
+ const outcomeKey = Symbol.for("@loozo/angular-launch/outcome/v1");
4
+ /**
5
+ * Creates an error that refuses the call with `FORBIDDEN` when thrown from middleware
6
+ * or a handler.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * if (context.user === null) {
11
+ * throw forbidden();
12
+ * }
13
+ * ```
14
+ *
15
+ * @returns The error to `throw`.
16
+ */
17
+ export function forbidden() {
18
+ const error = new Error("RPC forbidden");
19
+ const outcome = { kind: "forbidden" };
20
+ Object.defineProperty(error, outcomeKey, { value: outcome });
21
+ return error;
22
+ }
23
+ /**
24
+ * Reads the outcome a thrown value carries, if it was created by an outcome factory.
25
+ * Internal.
26
+ *
27
+ * @param error - The thrown value.
28
+ * @returns The outcome, or `undefined` for any other value.
29
+ */
30
+ export function outcomeOf(error) {
31
+ if (typeof error !== "object" || error === null) {
32
+ return undefined;
33
+ }
34
+ const descriptor = Object.getOwnPropertyDescriptor(error, outcomeKey);
35
+ return descriptor?.value;
36
+ }
@@ -12,19 +12,15 @@ Install the adapter. Launch supports `@tanstack/angular-query` `^5.0.0-rc.5` as
12
12
  pnpm add @tanstack/angular-query@5.0.0-rc.5
13
13
  ```
14
14
 
15
- Turn on the `tanstackQuery` generation option:
16
-
17
- ```js
18
- // generate.mjs
19
- import { generate } from "@loozo/angular-launch/generation";
20
-
21
- await generate(import.meta.dirname, {
22
- tsconfig: "tsconfig.app.json",
23
- scanDirectories: ["src/routes"],
24
- outDirectory: "generated",
25
- tanstackQuery: true,
26
- check: process.argv.includes("--check"),
27
- });
15
+ Turn on the `tanstackQuery` generation option in your `@loozo/angular-launch:application` build target (or pass `tanstackQuery: true` to `generate`):
16
+
17
+ ```json
18
+ "options": {
19
+ "tsconfig": "tsconfig.app.json",
20
+ "scanDirectories": ["src/routes"],
21
+ "outDirectory": "generated",
22
+ "tanstackQuery": true
23
+ }
28
24
  ```
29
25
 
30
26
  Each `rpc.generated.ts` then also exports `injectQueries()` and its type `Queries`, for the same groups as its `injectRpc()`. With the option off, generated files are exactly as without this entry point.