@loozo/angular-launch 0.0.3 → 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.
@@ -9,8 +9,8 @@ import { createErrors, declaredFailures } from "./errors.js";
9
9
  * from this entry point and call it without type arguments; a context assigned to a
10
10
  * variable and exported later, or `defineContext<MyContext>(...)`, fails generation.
11
11
  * The factory runs once per live server request, for page renders
12
- * and RPC requests alike, and its value is what handlers and guards receive as
13
- * `context`. Keep per-request state in the context rather than in module variables.
12
+ * and RPC requests alike, and its value is the `context` middleware and handlers start
13
+ * from. Keep per-request state in the context rather than in module variables.
14
14
  *
15
15
  * @example
16
16
  * ```ts
@@ -30,100 +30,73 @@ import { createErrors, declaredFailures } from "./errors.js";
30
30
  export function defineContext(create) {
31
31
  return { create };
32
32
  }
33
- function procedure(kind, options) {
34
- const definitions = (options.errors ?? {});
35
- const { factories, failures } = createErrors(definitions);
36
- return {
37
- kind,
38
- input: options.input,
39
- errors: definitions,
40
- canActivate: options.canActivate ?? [],
41
- handler: ({ context, input }) => options.handler({ context, input, errors: factories }),
42
- [declaredFailures]: failures,
43
- };
44
- }
45
33
  /**
46
- * Defines a procedure that reads data.
34
+ * Creates a middleware: code that runs around a procedure call, to refuse it, add typed
35
+ * values to its context, or wrap the rest of it.
47
36
  *
48
37
  * @remarks
49
- * The handler receives `{ context, input, errors }`: the request's {@link Context},
50
- * the validated input (`undefined` without an input schema) and the
51
- * error factories for the declared errors. A call validates the input, runs the
52
- * group's guards, then the procedure's guards, then the handler. Inputs and results
53
- * must be strict JSON; a result that isn't fails the call with `INTERNAL`. Throwing an
54
- * error created by `errors` returns that declared error; any other exception fails the
55
- * call with `INTERNAL` and is logged on the server.
56
- *
57
- * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
58
- * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
59
- * rejected. The schema's caller input type may still be a JSON union, as in
60
- * `Schema<string | number, number>`.
61
- *
62
- * Query responses are stored in Angular's HTTP transfer cache during server rendering
63
- * by default, so hydration reuses them.
38
+ * List middleware in `defineRpc`'s `use` to run it for every procedure in the group, or
39
+ * in a procedure's `use` to run it for that procedure. A call runs the group's
40
+ * middleware with no input, then validates the input, then runs the procedure's
41
+ * middleware with the validated input, then the handler. Middleware runs for every
42
+ * call, also during server rendering, where `request` is the page request.
43
+ *
44
+ * `run` must call `next()` exactly once and return its result: calling it twice or
45
+ * returning anything else fails the call with `INTERNAL`. `next(added)` merges `added`
46
+ * into the context by spread, so the context must be a plain object. The context is
47
+ * read-only at the top level: change it through `next()`. Every `next(...)` in a
48
+ * middleware adds the same keys, and a value that differs per branch goes in one
49
+ * `next()` call with a union-typed value, such as
50
+ * `next({ user: preview ? null : context.user })`: separate `next({ user: null })` and
51
+ * `next({ user: context.user })` calls don't infer `User | null` when `context.user` is
52
+ * a `User`. `next()` rejects when anything after it throws, so `await next()` in a `try`
53
+ * wraps the rest of the call.
54
+ *
55
+ * Refuse a call with `throw forbidden()`, which fails it with `FORBIDDEN`. Any other
56
+ * exception fails it with `INTERNAL` and is logged on the server. Declared errors belong
57
+ * to handlers.
64
58
  *
65
59
  * @example
66
60
  * ```ts
67
- * list: query({
68
- * handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
69
- * }),
70
- * ```
71
- *
72
- * @typeParam Input - The input schema; omit `input` for a procedure without input.
73
- * @typeParam Output - The handler's return type.
74
- * @typeParam Errors - The declared errors, written inline.
75
- * @param options - The procedure's `input` schema, `canActivate` guards, inline
76
- * `errors` declarations and `handler`.
77
- * @returns The procedure, to use as a value in `defineRpc`.
78
- * @throws TypeError when a declared error is invalid: its code isn't an identifier, is
79
- * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
80
- * message is empty, or its data isn't a Standard Schema V1.
81
- */
82
- export function query(options) {
83
- return procedure("query", options);
84
- }
85
- /**
86
- * Defines a procedure that writes data.
61
+ * import { forbidden, middleware } from "@loozo/angular-launch/server";
87
62
  *
88
- * @remarks
89
- * The handler receives `{ context, input, errors }`: the request's {@link Context},
90
- * the validated input (`undefined` without an input schema) and the
91
- * error factories for the declared errors. A call validates the input, runs the
92
- * group's guards, then the procedure's guards, then the handler. Inputs and results
93
- * must be strict JSON; a result that isn't fails the call with `INTERNAL`. Throwing an
94
- * error created by `errors` returns that declared error; any other exception fails the
95
- * call with `INTERNAL` and is logged on the server.
96
- *
97
- * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
98
- * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
99
- * rejected. The schema's caller input type may still be a JSON union, as in
100
- * `Schema<string | number, number>`.
101
- *
102
- * Mutations never use the HTTP transfer cache. During server rendering they fail with
103
- * `FORBIDDEN` before validation, guards or the handler run.
63
+ * export const signedIn = middleware(async ({ context, next }) => {
64
+ * if (context.user === null) {
65
+ * throw forbidden();
66
+ * }
104
67
  *
105
- * @example
106
- * ```ts
107
- * add: mutation({
108
- * input: titleSchema,
109
- * handler: ({ input, context }) =>
110
- * context.db.todos.addForUser(requireUser(context).id, input.title),
111
- * }),
68
+ * return next({ user: context.user });
69
+ * });
112
70
  * ```
113
71
  *
114
- * @typeParam Input - The input schema; omit `input` for a procedure without input.
115
- * @typeParam Output - The handler's return type.
116
- * @typeParam Errors - The declared errors, written inline.
117
- * @param options - The procedure's `input` schema, `canActivate` guards, inline
118
- * `errors` declarations and `handler`.
119
- * @returns The procedure, to use as a value in `defineRpc`.
120
- * @throws TypeError when a declared error is invalid: its code isn't an identifier, is
121
- * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
122
- * message is empty, or its data isn't a Standard Schema V1.
72
+ * @typeParam Needs - The context it needs, from an annotated argument. Defaults to
73
+ * {@link Context}.
74
+ * @typeParam Added - The values it adds, inferred from what it passes to `next()`.
75
+ * @typeParam Input - The input it needs, from an annotated argument. Defaults to
76
+ * `unknown`.
77
+ * @param run - Runs the middleware for one call.
78
+ * @returns The middleware, to list in a `use` array.
123
79
  */
124
- export function mutation(options) {
125
- return procedure("mutation", options);
80
+ export function middleware(run) {
81
+ return { run };
82
+ }
83
+ function procedure(kind, { input, use = [], errors = {}, handler }) {
84
+ const { factories, failures } = createErrors(errors);
85
+ const run = handler;
86
+ return {
87
+ kind,
88
+ input,
89
+ errors,
90
+ use,
91
+ handler: (args) => run({ ...args, errors: factories }),
92
+ [declaredFailures]: failures,
93
+ };
126
94
  }
95
+ // The checked option types above tie each result to its builder's type parameters.
96
+ const builder = {
97
+ query: (options) => procedure("query", options),
98
+ mutation: (options) => procedure("mutation", options),
99
+ };
127
100
  /**
128
101
  * Defines the RPC group for the route declared in the same directory.
129
102
  *
@@ -131,41 +104,47 @@ export function mutation(options) {
131
104
  * Default-export the result from a file next to the route's `route.ts`; one group per
132
105
  * route. That route must be one that gets generated files: not a redirect, and with a
133
106
  * page or descendants with pages that aren't all redirects. Generation reads the call
134
- * statically without running it: import `defineRpc`, `query` and `mutation` by name
135
- * from this entry point, call them directly without type arguments, use literal
136
- * identifiers other than `__proto__` for the namespace and procedure names, and
137
- * write the procedures, options and `canActivate` arrays inline. Each route's
138
- * generated `injectRpc()` exposes its own group and its ancestors' groups under their
139
- * namespaces. Each namespace must be unique across the app: calls go to
140
- * `/_rpc/<namespace>/<procedure>`.
107
+ * statically without running it: import `defineRpc` by name from this entry point and
108
+ * call it directly without type arguments, with a literal identifier other than
109
+ * `__proto__` for the namespace; pass an arrow function whose parameter destructures
110
+ * `query` and/or `mutation` without renaming and whose body is a parenthesized object
111
+ * literal of procedures, each a direct `query(...)` or `mutation(...)` call with inline
112
+ * options; and write the group options inline. Each route's generated `injectRpc()`
113
+ * exposes its own group and its ancestors' groups under their namespaces. Each namespace
114
+ * must be unique across the app: calls go to `/_rpc/<namespace>/<procedure>`.
115
+ *
116
+ * The group's `use` middleware runs for every procedure in the group, before input
117
+ * validation, and the procedures' handlers and middleware see what it adds to the
118
+ * context. It isn't inherited through the route tree.
141
119
  *
142
120
  * Exposure isn't authorization: anyone who can reach the server can call any
143
- * procedure, so guard every group and procedure that needs it.
121
+ * procedure, so protect every group and procedure that needs it.
144
122
  *
145
123
  * @example
146
124
  * ```ts
147
- * import { defineRpc, query } from "@loozo/angular-launch/server";
148
- * import { isSignedIn, requireUser } from "../../auth.server";
125
+ * import { defineRpc } from "@loozo/angular-launch/server";
126
+ * import { signedIn } from "../../auth.server";
149
127
  *
150
128
  * export default defineRpc(
151
129
  * "todos",
152
- * {
130
+ * ({ query }) => ({
153
131
  * list: query({
154
- * handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
132
+ * handler: ({ context }) => context.db.todos.listForUser(context.user.id),
155
133
  * }),
156
- * },
157
- * { canActivate: [isSignedIn] },
134
+ * }),
135
+ * { use: [signedIn] },
158
136
  * );
159
137
  * ```
160
138
  *
161
139
  * @typeParam Name - The namespace literal.
140
+ * @typeParam Use - The group's middleware, written inline.
162
141
  * @typeParam Procedures - The procedures, keyed by name.
163
142
  * @param name - The namespace the generated client exposes the group under.
164
- * @param procedures - The procedures, keyed by name.
165
- * @param options - `canActivate`: group guards that run for every procedure in the
166
- * group.
143
+ * @param build - Returns the procedures, keyed by name, built with the `query` and
144
+ * `mutation` builders it receives.
145
+ * @param options - `use`: middleware that runs for every procedure in the group.
167
146
  * @returns The group, to default-export.
168
147
  */
169
- export function defineRpc(name, procedures, { canActivate = [], } = {}) {
170
- return { name, procedures, canActivate };
148
+ export function defineRpc(name, build, { use, } = {}) {
149
+ return { name, procedures: build(builder), use: use ?? [] };
171
150
  }
@@ -1,4 +1,5 @@
1
1
  import { type FrameworkCode } from "../client.js";
2
+ import { type InputIssue } from "../input-issues.js";
2
3
  import type { ContextDefinition, ContextOf, Group, ProcedureDefinition } from "./definitions.js";
3
4
  /**
4
5
  * The application's RPC groups, keyed by namespace.
@@ -85,7 +86,8 @@ export interface Reply {
85
86
  /** The result, or an `{ error: { code, message, data } }` frame. */
86
87
  readonly body: unknown;
87
88
  }
88
- export declare function failure(code: FrameworkCode): Reply;
89
+ export declare function failure(code: Exclude<FrameworkCode, "INVALID_INPUT">): Reply;
90
+ export declare function invalidInput(issues?: readonly InputIssue[]): Reply;
89
91
  export declare function isJsonMediaType(contentType: string | null): boolean;
90
92
  /**
91
93
  * Runs one procedure call within a request scope and produces its reply.
@@ -100,11 +102,14 @@ export declare function isJsonMediaType(contentType: string | null): boolean;
100
102
  * path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
101
103
  * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
102
104
  * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
103
- * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT`) with
104
- * input that passes the schema, or `null` without one (`INVALID_INPUT`); the group's
105
- * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
106
- * handler's strict JSON result is returned with status 200, and its declared errors
107
- * with their status.
105
+ * a cycle or an accessor), and exactly `{ input }` (`INVALID_INPUT` with no issues);
106
+ * the group's middleware runs with no input; the input must pass the schema
107
+ * (`INVALID_INPUT` with the schema's issues), or be `null` without one (`INVALID_INPUT`
108
+ * with no issues); the procedure's middleware runs with the validated input; then the
109
+ * handler. The handler's strict JSON result is returned with status 200, and its
110
+ * declared errors with their status. `forbidden()` thrown from middleware or the
111
+ * handler gives `FORBIDDEN`; a middleware that calls `next` twice or doesn't return its
112
+ * result gives `INTERNAL`.
108
113
  *
109
114
  * @param registry - The application's RPC groups.
110
115
  * @param path - The request path.
@@ -114,27 +119,53 @@ export declare function isJsonMediaType(contentType: string | null): boolean;
114
119
  * @param request - The request the scope must be bound to.
115
120
  * @param mode - `"http"` for browser requests (the default) or `"rendering"` for calls
116
121
  * made during server rendering.
122
+ * @param signal - The call's abort signal. Defaults to `request`'s signal.
117
123
  * @returns The reply to send.
118
124
  */
119
- export declare function dispatch(registry: Registry, path: string, envelope: unknown, scope: RequestScope, application: ApplicationBinding, request: Request, mode?: "http" | "rendering"): Promise<Reply>;
125
+ export declare function dispatch(registry: Registry, path: string, envelope: unknown, scope: RequestScope, application: ApplicationBinding, request: Request, mode?: "http" | "rendering", signal?: AbortSignal): Promise<Reply>;
126
+ /**
127
+ * Options for the generated `handleRequest` in `server.generated.ts`.
128
+ */
129
+ export interface HandleOptions {
130
+ /**
131
+ * Hostnames RPCs are answered for, matched like Angular's `allowedHosts`: exactly,
132
+ * `*.example.com` for subdomains only, or `*` for any host. An empty list refuses every
133
+ * RPC. Pass the same array to `AngularNodeAppEngine`.
134
+ */
135
+ readonly allowedHosts: readonly string[];
136
+ /**
137
+ * Further origins allowed to call, as exact serialized origins such as
138
+ * `https://app.example.com`: a public origin behind a proxy that rewrites `Host`, or a
139
+ * sibling site. Defaults to none.
140
+ */
141
+ readonly origins?: readonly string[];
142
+ }
120
143
  /**
121
144
  * Answers an RPC HTTP request, or returns `null` for any other request.
122
145
  *
123
146
  * @remarks
124
147
  * Internal: exported only from `@loozo/angular-launch/_server` for the generated
125
148
  * `handleRequest` in `server.generated.ts`; call that instead.
126
- * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
127
- * with an `application/json` content type and no query string, otherwise the reply is
128
- * `INVALID_INPUT` and no context is created. A fresh context is then created before the
129
- * body is parsed; if that fails the reply is `INTERNAL`, even when the body isn't JSON.
130
- * Otherwise a body that isn't JSON gives `INVALID_INPUT`. Responses are JSON with
131
- * `Cache-Control: private, no-store` and `Vary: Cookie`.
149
+ * Any path starting with `/_rpc/` is treated as an RPC request. Its URL's hostname must
150
+ * be in `allowedHosts`, otherwise the reply is a plain-text 400 `Host not allowed`. It
151
+ * must then be a `POST` with an `application/json` content type and no query string,
152
+ * otherwise the reply is `INVALID_INPUT` with no issues. It must then come from the
153
+ * app's own origin, otherwise the reply is `FORBIDDEN`: an `Origin` listed in `origins`
154
+ * passes; otherwise `Sec-Fetch-Site`, when sent, must be `same-origin`; otherwise
155
+ * `Origin`, when sent, must equal the request URL's origin; a request with neither
156
+ * header is refused. No context is created for any of these refusals. A fresh context
157
+ * is then created before the body is parsed; if that fails the reply is `INTERNAL`, even
158
+ * when the body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with
159
+ * no issues.
160
+ * JSON responses carry `Cache-Control: private, no-store`, `Vary: Cookie` and
161
+ * `X-Content-Type-Options: nosniff`.
132
162
  *
133
163
  * @typeParam Definition - The application's context definition.
134
164
  * @param registry - The application's RPC groups.
135
165
  * @param application - The application binding.
136
166
  * @param request - The incoming server request.
167
+ * @param options - The allowed hosts and further allowed origins.
137
168
  * @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
138
169
  */
139
- export declare function handleRpc<Definition extends ContextDefinition<unknown>>(registry: Registry, application: ApplicationBinding<Definition>, request: Request): Promise<Response | null>;
170
+ export declare function handleRpc<Definition extends ContextDefinition<unknown>>(registry: Registry, application: ApplicationBinding<Definition>, request: Request, { allowedHosts, origins }: HandleOptions): Promise<Response | null>;
140
171
  export {};