@alxia/create 0.3.4 → 0.4.0
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 +2 -2
- package/docs/guide.md +109 -15
- package/docs/roadmap.md +11 -0
- package/docs/troubleshooting.md +38 -0
- package/package.json +5 -5
- package/templates/api/.env.example +5 -0
- package/templates/api/README.md +30 -1
- package/templates/api/src/context.ts +15 -2
- package/templates/api/src/env.spec.ts +30 -0
- package/templates/api/src/env.ts +25 -1
- package/templates/api/src/proxy.spec.ts +59 -0
- package/templates/graphql/.env.example +5 -0
- package/templates/graphql/README.md +29 -1
- package/templates/graphql/src/context.ts +15 -2
- package/templates/graphql/src/env.spec.ts +30 -0
- package/templates/graphql/src/env.ts +25 -1
- package/templates/graphql/src/proxy.spec.ts +59 -0
package/README.md
CHANGED
|
@@ -36,8 +36,8 @@ bun create @alxia my-site --template react-router
|
|
|
36
36
|
| template | what it writes |
|
|
37
37
|
| --- | --- |
|
|
38
38
|
| `minimal` | the smallest alxia app: `src/index.ts` exports `app = alxia().get("/", …)` and listens on `PORT` only when it is the entry file, `src/index.spec.ts` calls it with `app.request()`; `bun dev` (`NODE_ENV=development bun --hot`), `build`, `start`, `typecheck`, a strict `tsconfig.json`, Biome and `verify` (`check:ci`, `typecheck`, then `test`), a `Dockerfile` running on `oven/bun:1-alpine`, `.dockerignore`, `.gitignore`, `.vscode/` and a README. One dependency, `@alxia/core`: no OpenAPI, no code generation, no validator, no env file |
|
|
39
|
-
| `api` | an `@alxia/core` app with Zod, OpenAPI spec first: `openapi.yaml` declares `GET /todos`, `POST /todos` and `GET /todos/{id}`; `bun run generate` writes `src/generated/` from it with [`@nxgt/openapi-codegen`](https://www.npmjs.com/package/@nxgt/openapi-codegen) (`openapi-codegen.config.ts`), committed, so nothing is generated at install or build; `src/env.ts` reads `PORT`, `API_KEY` and `
|
|
40
|
-
| `graphql` | a GraphQL API with [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server) through [`@alxia/graphql`](https://www.npmjs.com/package/@alxia/graphql), schema first: `schema.graphql` is the contract (`Query`, `Mutation`, `Subscription`); `bun run generate` writes `src/generated/resolvers.ts` from it with [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) (`codegen.ts`), committed, typing `Resolvers` with the app's context; `src/context.ts` holds the base and `viewerOf`, a middleware reading `Authorization: Bearer <token>` so every resolver reads a typed `viewer`; `src/loaders.ts`, `createLoaders()`, the [DataLoader](https://github.com/graphql/dataloader)s of one request, built per request by the `context` option of `graphql()` in `src/app.ts` so `Note.author` loads the authors of a list of notes in one batch (`findUsers`) instead of one call per note; `src/resolvers.ts`; `src/schema.ts` and `src/app.ts` mounting `health()` and `graphql(app, { schema, context })`, GraphiQL on in dev alone; `src/env.ts` (`PORT`) with `defineEnv`; `src/store.ts`, in memory, with the pub/sub of the `noteAdded` subscription (server-sent events); a `bun test` spec posting to `/graphql` through `app.request()
|
|
39
|
+
| `api` | an `@alxia/core` app with Zod, OpenAPI spec first: `openapi.yaml` declares `GET /todos`, `POST /todos` and `GET /todos/{id}`; `bun run generate` writes `src/generated/` from it with [`@nxgt/openapi-codegen`](https://www.npmjs.com/package/@nxgt/openapi-codegen) (`openapi-codegen.config.ts`), committed, so nothing is generated at install or build; `src/env.ts` reads `PORT`, `API_KEY`, `API_DOCS` and an optional `TRUSTED_PROXIES` (CIDR ranges, which adds `trustProxy({ trusted, untrusted: "refuse" })` to the base when set: `ctx.ip` from a trusted proxy's `X-Forwarded-For`, a forwarding header from any other connection refused, health probes untouched) with `defineEnv` from [`@alxia/env`](https://www.npmjs.com/package/@alxia/env), `API_KEY` a secret defaulting to `dev-key` under `NODE_ENV` `development` and `test` alone, required anywhere else; `src/context.ts` holds the base the routes read, `alxia({ errors: "problem" })` so alxia's own errors are RFC 9457 problems as `openapi.yaml` declares them, and registers it with `@alxia/core`'s `Register`; `src/routes/todos.ts`, made with `defineRoutes()`, reads that context with no import of the app and binds each operation with `route(operation, …middlewares, handler)`, as `route(operations.createTodo, requireKey, handler)`, where `requireKey`, made with `defineMiddleware`, answers 401 without an API key, and the operation's schemas validate the request and check the handler's reply; `src/app.ts` mounts `health()` (`GET /health`, `GET /ready`), `apiDocs` from `@alxia/openapi` (the API reference at `/docs`, from `openapi.yaml` imported into the bundle; on in development, else with `API_DOCS=true`) and the routes on the base; a `bun test` spec, `src/proxy.spec.ts`, building the base behind `TRUSTED_PROXIES` and calling `app.fetch` with a peer, `src/env.spec.ts`, checking that a malformed `TRUSTED_PROXIES` stops the app, and a `bun test` spec calling the app through the typed [openapi-fetch](https://openapi-ts.dev/openapi-fetch/) client over the generated `paths.ts`, its `fetch` being `app.fetch` (in process, no server), keeping one `app.request()` test, and asserting `matchesSpec` from [`@alxia/openapi`](https://www.npmjs.com/package/@alxia/openapi): every operation has its route, and `strict: true` also fails on a route outside the spec; `bun dev` (`NODE_ENV=development`) restarting on change, `typecheck`, `build`, a strict `tsconfig.json`, Biome (`biome.json`, `lint`, `format`, `check`, `check:ci`), `verify`, starting with `generate --check`, a `Dockerfile` running on `oven/bun:1-alpine`, `.dockerignore`, `.gitignore`, `.env.example`, `.vscode/` and a README. `@alxia/openapi` is a dependency; `openapi-fetch` and `@nxgt/openapi-codegen` are devDependencies |
|
|
40
|
+
| `graphql` | a GraphQL API with [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server) through [`@alxia/graphql`](https://www.npmjs.com/package/@alxia/graphql), schema first: `schema.graphql` is the contract (`Query`, `Mutation`, `Subscription`); `bun run generate` writes `src/generated/resolvers.ts` from it with [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) (`codegen.ts`), committed, typing `Resolvers` with the app's context; `src/context.ts` holds the base and `viewerOf`, a middleware reading `Authorization: Bearer <token>` so every resolver reads a typed `viewer`; `src/loaders.ts`, `createLoaders()`, the [DataLoader](https://github.com/graphql/dataloader)s of one request, built per request by the `context` option of `graphql()` in `src/app.ts` so `Note.author` loads the authors of a list of notes in one batch (`findUsers`) instead of one call per note; `src/resolvers.ts`; `src/schema.ts` and `src/app.ts` mounting `health()` and `graphql(app, { schema, context })`, GraphiQL on in dev alone; `src/env.ts` (`PORT` and the optional `TRUSTED_PROXIES`, as `api`) with `defineEnv`; `src/store.ts`, in memory, with the pub/sub of the `noteAdded` subscription (server-sent events); a `bun test` spec posting to `/graphql` through `app.request()`, `src/proxy.spec.ts`, the base behind `TRUSTED_PROXIES`, and `src/env.spec.ts`, a malformed one refused; the same scripts, `Dockerfile`, Biome and `.vscode/` as `api`, `verify` starting with `generate --check`, and a `.env.example`. `@alxia/graphql`, `@alxia/env`, `dataloader`, `graphql` and `graphql-yoga` are dependencies; the code generator is a devDependency |
|
|
41
41
|
| `react-router` | React Router's official template, as `create-react-router` writes it, shipped in this package and copied, with [`@alxia/react-router`](https://www.npmjs.com/package/@alxia/react-router) added as its README says: `alxia()` in `vite.config.ts`'s plugins, `dev` under `NODE_ENV=development`, `start` running `NODE_ENV=production bun build/server/index.js`, a `bunfig.toml` starting React Router's CLI on Bun, a `Dockerfile` running on `oven/bun:1-alpine` in place of React Router's Node one, and Biome as the `api` project has it, the scaffold formatted by it once. No server file: the default one serves the pages; `bunx alxia-react-router reveal` writes it out to customise |
|
|
42
42
|
|
|
43
43
|
The heart of the `api` project, its middleware and a route bound to an
|
package/docs/guide.md
CHANGED
|
@@ -152,11 +152,13 @@ my-api/
|
|
|
152
152
|
├── openapi-codegen.config.ts how `bun run generate` reads it
|
|
153
153
|
├── src/
|
|
154
154
|
│ ├── generated/ what `bun run generate` writes: committed, never edited
|
|
155
|
-
│ ├── env.ts defineEnv from @alxia/env: PORT, API_KEY
|
|
155
|
+
│ ├── env.ts defineEnv from @alxia/env: PORT, API_KEY, API_DOCS, TRUSTED_PROXIES
|
|
156
156
|
│ ├── context.ts the base: what every route reads, and its Register
|
|
157
157
|
│ ├── routes/todos.ts defineRoutes(): one route per operation
|
|
158
158
|
│ ├── app.ts the app: the base, health(), apiDocs, the routes, and its type
|
|
159
159
|
│ ├── app.spec.ts bun test: the typed client over app.fetch, and matchesSpec
|
|
160
|
+
│ ├── proxy.spec.ts bun test: the base behind TRUSTED_PROXIES, with a peer
|
|
161
|
+
│ ├── env.spec.ts bun test: a malformed TRUSTED_PROXIES stops the app
|
|
160
162
|
│ └── server.ts app.listen on env.PORT, which stops on SIGINT and SIGTERM
|
|
161
163
|
├── package.json
|
|
162
164
|
├── tsconfig.json
|
|
@@ -164,7 +166,7 @@ my-api/
|
|
|
164
166
|
├── .vscode/ Biome's extension recommended, format on save
|
|
165
167
|
├── Dockerfile bun run build, then dist/ alone, on oven/bun:1-alpine
|
|
166
168
|
├── .dockerignore
|
|
167
|
-
├── .env.example PORT, API_KEY and
|
|
169
|
+
├── .env.example PORT, API_KEY, API_DOCS and TRUSTED_PROXIES, for a .env Bun loads
|
|
168
170
|
├── .gitignore
|
|
169
171
|
└── README.md
|
|
170
172
|
```
|
|
@@ -326,6 +328,7 @@ instead:
|
|
|
326
328
|
### `src/env.ts`
|
|
327
329
|
|
|
328
330
|
```ts
|
|
331
|
+
import { trustProxy } from "@alxia/core";
|
|
329
332
|
import { defineEnv } from "@alxia/env";
|
|
330
333
|
import { z } from "zod";
|
|
331
334
|
|
|
@@ -333,11 +336,32 @@ import { z } from "zod";
|
|
|
333
336
|
// production included, is a deployment.
|
|
334
337
|
const local = ["development", "test"].includes(Bun.env.NODE_ENV ?? "");
|
|
335
338
|
|
|
339
|
+
// A range or an address trustProxy accepts: it throws on any other.
|
|
340
|
+
const isRange = (range: string) => {
|
|
341
|
+
try {
|
|
342
|
+
trustProxy({ trusted: [range], untrusted: "refuse" });
|
|
343
|
+
return true;
|
|
344
|
+
} catch {
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
|
|
336
349
|
export const env = defineEnv(
|
|
337
350
|
{
|
|
338
351
|
PORT: z.coerce.number().default(3000),
|
|
339
352
|
API_KEY: local ? z.string().min(1).default("dev-key") : z.string().min(1),
|
|
340
353
|
API_DOCS: z.stringbool().default(Bun.env.NODE_ENV === "development"),
|
|
354
|
+
TRUSTED_PROXIES: z
|
|
355
|
+
.string()
|
|
356
|
+
.transform((list) =>
|
|
357
|
+
list
|
|
358
|
+
.split(",")
|
|
359
|
+
.map((range) => range.trim())
|
|
360
|
+
.filter(Boolean),
|
|
361
|
+
)
|
|
362
|
+
.pipe(z.array(z.string().refine(isRange, "not a CIDR range or address")))
|
|
363
|
+
.transform((ranges) => (ranges.length > 0 ? ranges : undefined))
|
|
364
|
+
.optional(),
|
|
341
365
|
},
|
|
342
366
|
{ secret: ["API_KEY"] },
|
|
343
367
|
);
|
|
@@ -350,15 +374,20 @@ or malformed variable stops the process with every issue, before it listens.
|
|
|
350
374
|
under `NODE_ENV=development` and `test` alone: anywhere else — `bun start`,
|
|
351
375
|
the image — it is required, and the app does not start without it.
|
|
352
376
|
`API_DOCS` turns the API reference at `/docs` on: by default in
|
|
353
|
-
development alone. `
|
|
354
|
-
|
|
355
|
-
|
|
377
|
+
development alone. `TRUSTED_PROXIES` is optional and unset by default: the
|
|
378
|
+
proxies in front of the app as comma-separated CIDR ranges or addresses,
|
|
379
|
+
each checked by `trustProxy` itself, so a malformed one stops the process
|
|
380
|
+
with the others' issues ([Behind a proxy](#behind-a-proxy)). The mode is
|
|
381
|
+
read from `Bun.env`, not `process.env.NODE_ENV`, which `bun build` would
|
|
382
|
+
replace with the mode of the build. `src/server.ts` listens on `env.PORT`
|
|
383
|
+
and `src/routes/todos.ts` compares the `x-api-key` header with `env.API_KEY`.
|
|
356
384
|
`@alxia/env` and `zod` are dependencies.
|
|
357
385
|
|
|
358
386
|
### `src/context.ts`
|
|
359
387
|
|
|
360
388
|
```ts
|
|
361
|
-
import { alxia } from "@alxia/core";
|
|
389
|
+
import { alxia, trustProxy } from "@alxia/core";
|
|
390
|
+
import { env } from "./env";
|
|
362
391
|
import type { Todo } from "./generated/types";
|
|
363
392
|
|
|
364
393
|
const todos: Todo[] = [];
|
|
@@ -367,7 +396,19 @@ const todos: Todo[] = [];
|
|
|
367
396
|
// registered below, so a route file reads it with no import of the app.
|
|
368
397
|
// alxia's own errors — a 400 the schemas refuse, a 404 no route matches, a
|
|
369
398
|
// 500 — are RFC 9457 problems, as openapi.yaml declares them.
|
|
370
|
-
|
|
399
|
+
//
|
|
400
|
+
// Behind a load balancer, set TRUSTED_PROXIES to its range: its
|
|
401
|
+
// X-Forwarded-For then sets ctx.ip, and a forwarding header from any other
|
|
402
|
+
// connection is refused with a 403. A request that carries none, a health
|
|
403
|
+
// probe's, passes from anywhere. Unset, no forwarding header is read.
|
|
404
|
+
export function createBase(trusted: string[] | undefined) {
|
|
405
|
+
return alxia({
|
|
406
|
+
errors: "problem",
|
|
407
|
+
...(trusted && { proxy: trustProxy({ trusted, untrusted: "refuse" }) }),
|
|
408
|
+
}).decorate({ todos });
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export const base = createBase(env.TRUSTED_PROXIES);
|
|
371
412
|
|
|
372
413
|
// Register the base, never the app: the app mounts the route files, whose
|
|
373
414
|
// type reads this, and would then be typed by itself.
|
|
@@ -650,7 +691,7 @@ my-graphql-api/
|
|
|
650
691
|
├── codegen.ts how `bun run generate` reads it
|
|
651
692
|
├── src/
|
|
652
693
|
│ ├── generated/resolvers.ts what `bun run generate` writes: committed, never edited
|
|
653
|
-
│ ├── env.ts defineEnv: PORT
|
|
694
|
+
│ ├── env.ts defineEnv: PORT, TRUSTED_PROXIES
|
|
654
695
|
│ ├── store.ts in-memory users, tokens and notes, and the pub/sub
|
|
655
696
|
│ ├── loaders.ts createLoaders(): the DataLoaders of one request
|
|
656
697
|
│ ├── context.ts the base, the viewerOf middleware, and Context
|
|
@@ -659,6 +700,8 @@ my-graphql-api/
|
|
|
659
700
|
│ ├── app.ts health() and graphql(app, { schema, context }) mounted on the base
|
|
660
701
|
│ ├── graphql.d.ts declares the *.graphql module
|
|
661
702
|
│ ├── app.spec.ts bun test: POST /graphql through app.request()
|
|
703
|
+
│ ├── proxy.spec.ts bun test: the base behind TRUSTED_PROXIES, with a peer
|
|
704
|
+
│ ├── env.spec.ts bun test: a malformed TRUSTED_PROXIES stops the app
|
|
662
705
|
│ └── server.ts app.listen on env.PORT, which stops on SIGINT and SIGTERM
|
|
663
706
|
├── package.json
|
|
664
707
|
├── tsconfig.json
|
|
@@ -666,7 +709,7 @@ my-graphql-api/
|
|
|
666
709
|
├── .vscode/
|
|
667
710
|
├── Dockerfile bun run build, then dist/ alone, on oven/bun:1-alpine
|
|
668
711
|
├── .dockerignore
|
|
669
|
-
├── .env.example PORT, for a .env Bun loads
|
|
712
|
+
├── .env.example PORT and TRUSTED_PROXIES, for a .env Bun loads
|
|
670
713
|
├── .gitignore
|
|
671
714
|
└── README.md
|
|
672
715
|
```
|
|
@@ -720,7 +763,7 @@ not resolvers, and Pothos is code first.
|
|
|
720
763
|
|
|
721
764
|
```ts
|
|
722
765
|
// src/context.ts
|
|
723
|
-
import { alxia, defineMiddleware } from "@alxia/core";
|
|
766
|
+
import { alxia, defineMiddleware, trustProxy } from "@alxia/core";
|
|
724
767
|
import type { GraphQLContext } from "@alxia/graphql";
|
|
725
768
|
import { env } from "./env";
|
|
726
769
|
import type { Loaders } from "./loaders";
|
|
@@ -736,7 +779,19 @@ const viewerOf = defineMiddleware(({ request }, next) => {
|
|
|
736
779
|
});
|
|
737
780
|
});
|
|
738
781
|
|
|
739
|
-
|
|
782
|
+
// Behind a load balancer, TRUSTED_PROXIES (src/env.ts) declares its range:
|
|
783
|
+
// X-Forwarded-For from it sets ctx.ip, a forwarding header from any other
|
|
784
|
+
// connection is refused with a 403, and a request with none passes. Unset,
|
|
785
|
+
// no forwarding header is read.
|
|
786
|
+
export function createBase(trusted: string[] | undefined) {
|
|
787
|
+
return alxia({
|
|
788
|
+
...(trusted && { proxy: trustProxy({ trusted, untrusted: "refuse" }) }),
|
|
789
|
+
})
|
|
790
|
+
.decorate({ env, db })
|
|
791
|
+
.use(viewerOf);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
export const base = createBase(env.TRUSTED_PROXIES);
|
|
740
795
|
export type Context = GraphQLContext<typeof base, { loaders: Loaders }>;
|
|
741
796
|
```
|
|
742
797
|
|
|
@@ -825,10 +880,11 @@ That pub/sub lives in one process: across several, back it with a broker.
|
|
|
825
880
|
|
|
826
881
|
### `src/env.ts`
|
|
827
882
|
|
|
828
|
-
`defineEnv` from `@alxia/env` reads `PORT` (3000 by default)
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
`.env` to
|
|
883
|
+
`defineEnv` from `@alxia/env` reads `PORT` (3000 by default) and
|
|
884
|
+
`TRUSTED_PROXIES` (optional, as the `api` template's), checked once, when
|
|
885
|
+
the module is first imported: a malformed one stops the process with every
|
|
886
|
+
issue, before it listens. Bun loads `.env`; copy `.env.example` to `.env`
|
|
887
|
+
to set them.
|
|
832
888
|
|
|
833
889
|
### Adding a field
|
|
834
890
|
|
|
@@ -955,6 +1011,44 @@ bunx alxia-react-router reveal
|
|
|
955
1011
|
The [`@alxia/react-router` guide](https://github.com/softistx/alxia/blob/develop/packages/react-router/docs/guide.md)
|
|
956
1012
|
goes from there.
|
|
957
1013
|
|
|
1014
|
+
## Behind a proxy
|
|
1015
|
+
|
|
1016
|
+
The `api` and `graphql` templates are deployed behind a load balancer, and
|
|
1017
|
+
declare it with one optional variable, so a project that is not behind one
|
|
1018
|
+
changes nothing. `TRUSTED_PROXIES` is the proxies' CIDR ranges or addresses,
|
|
1019
|
+
comma-separated, validated when the app starts; `src/context.ts`'s
|
|
1020
|
+
`createBase` adds `proxy: trustProxy({ trusted, untrusted: 'refuse' })` to
|
|
1021
|
+
the base only when it is set:
|
|
1022
|
+
|
|
1023
|
+
```sh
|
|
1024
|
+
TRUSTED_PROXIES=10.0.0.0/8,172.16.0.0/12 bun start
|
|
1025
|
+
```
|
|
1026
|
+
|
|
1027
|
+
- **From a trusted proxy**, `X-Forwarded-For` sets `ctx.ip`, read from the
|
|
1028
|
+
right, and `X-Forwarded-Proto` and `X-Forwarded-Host` give
|
|
1029
|
+
`originalUrl(ctx)`.
|
|
1030
|
+
- **From any other connection**, a request carrying a forwarding header is
|
|
1031
|
+
answered 403 (a problem under `api`'s `errors: 'problem'`), before any
|
|
1032
|
+
middleware: a client cannot claim an address.
|
|
1033
|
+
- **A request with no forwarding header passes from anywhere**: that is why
|
|
1034
|
+
the templates choose `'refuse'` over `'refuse-all'`. A Docker
|
|
1035
|
+
`HEALTHCHECK`, a Kubernetes probe or a load balancer's check sends none,
|
|
1036
|
+
so `/health` and `/ready` (from `health()`) answer as they did. With
|
|
1037
|
+
`'refuse-all'`, a probe from the node would be refused unless `allow`
|
|
1038
|
+
names its range or its paths
|
|
1039
|
+
([Only the proxies](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/serving.md#only-the-proxies-refuse-all)).
|
|
1040
|
+
- **Unset**, nothing changes: no forwarding header is read, `ctx.ip` is the
|
|
1041
|
+
connection's.
|
|
1042
|
+
|
|
1043
|
+
`src/proxy.spec.ts` proves each: `app.request` has no connection, so it
|
|
1044
|
+
builds the base with `createBase(['10.0.0.0/8'])` and calls `app.fetch(request,
|
|
1045
|
+
server)` with a stub whose `requestIP()` names the peer. The proxy must
|
|
1046
|
+
overwrite `X-Forwarded-*` itself; core's guide says how
|
|
1047
|
+
([Serving](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/serving.md#behind-a-proxy-proxy)),
|
|
1048
|
+
and the [deploying recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/deploying.md#on-a-platform)
|
|
1049
|
+
shows the whole path. `src/env.spec.ts` imports `src/env.ts` under a
|
|
1050
|
+
malformed `TRUSTED_PROXIES` and checks that it throws, naming the entry.
|
|
1051
|
+
|
|
958
1052
|
## Lint and format
|
|
959
1053
|
|
|
960
1054
|
Every project lints and formats with [Biome](https://biomejs.dev), in one
|
package/docs/roadmap.md
CHANGED
|
@@ -64,6 +64,17 @@ Nothing scheduled yet.
|
|
|
64
64
|
|
|
65
65
|
## Shipped
|
|
66
66
|
|
|
67
|
+
### 0.4.0
|
|
68
|
+
|
|
69
|
+
- **`TRUSTED_PROXIES` in the `api` and `graphql` templates.** Optional and
|
|
70
|
+
unset by default, so a new project behaves as before; set to the load
|
|
71
|
+
balancer's CIDR ranges, the base declares `trustProxy({ trusted,
|
|
72
|
+
untrusted: 'refuse' })`: `ctx.ip` from a trusted proxy's
|
|
73
|
+
`X-Forwarded-For`, a forwarding header from any other connection refused,
|
|
74
|
+
health probes passing. Each template tests it with a peer.
|
|
75
|
+
- **A core with `app.all`.** New projects install `@alxia/core` 0.11, which
|
|
76
|
+
declares one route for every method at a path.
|
|
77
|
+
|
|
67
78
|
### 0.1.6
|
|
68
79
|
|
|
69
80
|
- **The `api` project is OpenAPI spec first.** `openapi.yaml` declares
|
package/docs/troubleshooting.md
CHANGED
|
@@ -58,6 +58,7 @@ print, or — for a trap that prints nothing — the symptom.
|
|
|
58
58
|
**The environment**
|
|
59
59
|
|
|
60
60
|
- [`EnvError: The environment is invalid:`](#enverror-the-environment-is-invalid)
|
|
61
|
+
- [`403 {"error":"untrusted_proxy"}` behind a load balancer](#403-erroruntrusted_proxy-behind-a-load-balancer)
|
|
61
62
|
|
|
62
63
|
**Biome**
|
|
63
64
|
|
|
@@ -646,6 +647,12 @@ later. A secret's value is never printed: `API_KEY` shows as `***`.
|
|
|
646
647
|
PORT=3000 bun dev
|
|
647
648
|
```
|
|
648
649
|
|
|
650
|
+
A malformed `TRUSTED_PROXIES` stops the app the same way, with
|
|
651
|
+
`TRUSTED_PROXIES.1: not a CIDR range or address`, the number being the
|
|
652
|
+
position of the bad entry, from 0: it is comma-separated CIDR
|
|
653
|
+
ranges or addresses (`10.0.0.0/8,172.16.0.0/12`), and unset or empty it
|
|
654
|
+
declares no proxy.
|
|
655
|
+
|
|
649
656
|
A variable the schema gives a default (`PORT`, the `api` project's
|
|
650
657
|
`API_DOCS`) is fine unset. The `api` project's `API_KEY` defaults to
|
|
651
658
|
`dev-key` under `NODE_ENV=development` (`bun dev`) and `test` (`bun test`)
|
|
@@ -653,6 +660,37 @@ alone: `bun start`, the image and any other `NODE_ENV` require it, so set
|
|
|
653
660
|
it there (`docker run -e API_KEY=…`). `bun test` sets `NODE_ENV=test`: a
|
|
654
661
|
`.env` that sets `NODE_ENV` to another value overrides it.
|
|
655
662
|
|
|
663
|
+
### `403 {"error":"untrusted_proxy"}` behind a load balancer
|
|
664
|
+
|
|
665
|
+
**Symptom:** with `TRUSTED_PROXIES` set, a request is answered 403
|
|
666
|
+
`{"error":"untrusted_proxy"}`: in the `api` project, an
|
|
667
|
+
`application/problem+json` problem with status 403 and the `detail`
|
|
668
|
+
`Forwarding headers from a connection that is no trusted proxy`. The app's
|
|
669
|
+
logger writes no line for it.
|
|
670
|
+
|
|
671
|
+
**Why:** the request carries `X-Forwarded-For`, `X-Forwarded-Proto`,
|
|
672
|
+
`X-Forwarded-Host` or `Forwarded`, from a connection `TRUSTED_PROXIES` does
|
|
673
|
+
not name. That is either a client going around the proxy, claiming an
|
|
674
|
+
address, or the proxy itself, whose range is missing from the list: behind
|
|
675
|
+
Docker, Kubernetes or a cloud load balancer, the connection's address is the
|
|
676
|
+
proxy's *private* one, not the one the clients see. A request with no
|
|
677
|
+
forwarding header is never refused, so a health probe passes and the symptom
|
|
678
|
+
can look intermittent.
|
|
679
|
+
|
|
680
|
+
**Fix:** list the range the proxy connects from, which is the address the
|
|
681
|
+
app sees as its peer, not the public one:
|
|
682
|
+
|
|
683
|
+
```sh
|
|
684
|
+
TRUSTED_PROXIES=10.0.0.0/8,172.16.0.0/12 bun start
|
|
685
|
+
```
|
|
686
|
+
|
|
687
|
+
If the request should not come through a proxy at all (a local `curl` with
|
|
688
|
+
a copied `X-Forwarded-For`), drop the header. In a spec, `app.request` has
|
|
689
|
+
no connection: give `fetch` a server whose `requestIP` names a proxy, as
|
|
690
|
+
`src/proxy.spec.ts` does. See
|
|
691
|
+
[Behind a proxy](guide.md#behind-a-proxy) and `@alxia/core`'s
|
|
692
|
+
[`403 {"error":"untrusted_proxy"}`](https://github.com/softistx/alxia/blob/develop/packages/core/docs/troubleshooting.md#403-erroruntrusted_proxy).
|
|
693
|
+
|
|
656
694
|
## Biome
|
|
657
695
|
|
|
658
696
|
### `bun ci` installs, and checks nothing
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxia/create",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Start an alxia app: `bun create @alxia` writes a minimal API, a spec-first one, a GraphQL one, or React Router's official template served by alxia",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -41,11 +41,11 @@
|
|
|
41
41
|
]
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@alxia/core": "^0.
|
|
44
|
+
"@alxia/core": "^0.11.0",
|
|
45
45
|
"@alxia/env": "^0.2.0",
|
|
46
|
-
"@alxia/graphql": "^0.6.
|
|
47
|
-
"@alxia/openapi": "^0.6.
|
|
48
|
-
"@alxia/react-router": "^0.7.
|
|
46
|
+
"@alxia/graphql": "^0.6.3",
|
|
47
|
+
"@alxia/openapi": "^0.6.5",
|
|
48
|
+
"@alxia/react-router": "^0.7.2",
|
|
49
49
|
"@graphql-codegen/cli": "7.4.3",
|
|
50
50
|
"@graphql-codegen/typescript": "6.1.0",
|
|
51
51
|
"@graphql-codegen/typescript-resolvers": "6.1.0",
|
|
@@ -9,3 +9,8 @@
|
|
|
9
9
|
|
|
10
10
|
# number, optional, default 3000
|
|
11
11
|
PORT=3000
|
|
12
|
+
|
|
13
|
+
# comma-separated CIDR ranges or addresses, optional, unset by default: the proxies in front of
|
|
14
|
+
# the app, a load balancer's. Set, X-Forwarded-For from one of them sets ctx.ip, and a forwarding
|
|
15
|
+
# header from any other connection is refused with a 403. Unset, no forwarding header is read.
|
|
16
|
+
# TRUSTED_PROXIES=10.0.0.0/8,172.16.0.0/12
|
package/templates/api/README.md
CHANGED
|
@@ -71,7 +71,8 @@ Zod validators and the operations a typed client reads.
|
|
|
71
71
|
## Environment
|
|
72
72
|
|
|
73
73
|
Bun loads `.env` on every command, and `src/env.ts` checks what it finds.
|
|
74
|
-
Copy `.env.example` to `.env` to set `PORT`, `API_KEY` and
|
|
74
|
+
Copy `.env.example` to `.env` to set `PORT`, `API_KEY`, `API_DOCS` and
|
|
75
|
+
`TRUSTED_PROXIES`.
|
|
75
76
|
`API_KEY` defaults to `dev-key` under `NODE_ENV=development` (`bun dev`)
|
|
76
77
|
and `test` (`bun test`) alone: anywhere else, `bun start` and the image
|
|
77
78
|
included, it is required, and the app does not start without it.
|
|
@@ -84,6 +85,34 @@ never the secret's value.
|
|
|
84
85
|
cp .env.example .env
|
|
85
86
|
```
|
|
86
87
|
|
|
88
|
+
## Behind a proxy
|
|
89
|
+
|
|
90
|
+
Behind a load balancer or a reverse proxy, every connection comes from
|
|
91
|
+
the proxy, and `ctx.ip` is its address. Set `TRUSTED_PROXIES` to the
|
|
92
|
+
proxies' CIDR ranges (or addresses), comma-separated, and `src/context.ts`
|
|
93
|
+
declares them with `trustProxy`:
|
|
94
|
+
|
|
95
|
+
```sh
|
|
96
|
+
TRUSTED_PROXIES=10.0.0.0/8,172.16.0.0/12 bun start
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
- A request from one of them has its `ctx.ip` read from `X-Forwarded-For`,
|
|
100
|
+
from the right: the entries the client wrote are never believed.
|
|
101
|
+
- A request that carries `X-Forwarded-For`, `X-Forwarded-Proto`,
|
|
102
|
+
`X-Forwarded-Host` or `Forwarded` from any other connection is answered
|
|
103
|
+
403 (`untrusted: 'refuse'`), so nothing reads what it claims.
|
|
104
|
+
- A request that carries none passes from anywhere, so the Docker and
|
|
105
|
+
orchestrator health probes reach `/health` and `/ready` as before.
|
|
106
|
+
- Unset, the default, no forwarding header is read: the app behaves as
|
|
107
|
+
though the variable did not exist. Your proxy must overwrite
|
|
108
|
+
`X-Forwarded-*` (an AWS load balancer does; nginx needs
|
|
109
|
+
`proxy_set_header`), and the ranges must name the proxies alone.
|
|
110
|
+
|
|
111
|
+
To refuse every connection but the proxies', probes included, use
|
|
112
|
+
`untrusted: 'refuse-all'` with `allow`: see
|
|
113
|
+
[Serving](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/serving.md#only-the-proxies-refuse-all).
|
|
114
|
+
`src/proxy.spec.ts` shows both answers with `app.fetch` given a peer.
|
|
115
|
+
|
|
87
116
|
## Develop
|
|
88
117
|
|
|
89
118
|
```sh
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { alxia } from "@alxia/core";
|
|
1
|
+
import { alxia, trustProxy } from "@alxia/core";
|
|
2
|
+
import { env } from "./env";
|
|
2
3
|
import type { Todo } from "./generated/types";
|
|
3
4
|
|
|
4
5
|
const todos: Todo[] = [];
|
|
@@ -7,7 +8,19 @@ const todos: Todo[] = [];
|
|
|
7
8
|
// registered below, so a route file reads it with no import of the app.
|
|
8
9
|
// alxia's own errors — a 400 the schemas refuse, a 404 no route matches, a
|
|
9
10
|
// 500 — are RFC 9457 problems, as openapi.yaml declares them.
|
|
10
|
-
|
|
11
|
+
//
|
|
12
|
+
// Behind a load balancer, set TRUSTED_PROXIES to its range: its
|
|
13
|
+
// X-Forwarded-For then sets ctx.ip, and a forwarding header from any other
|
|
14
|
+
// connection is refused with a 403. A request that carries none, a health
|
|
15
|
+
// probe's, passes from anywhere. Unset, no forwarding header is read.
|
|
16
|
+
export function createBase(trusted: string[] | undefined) {
|
|
17
|
+
return alxia({
|
|
18
|
+
errors: "problem",
|
|
19
|
+
...(trusted && { proxy: trustProxy({ trusted, untrusted: "refuse" }) }),
|
|
20
|
+
}).decorate({ todos });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const base = createBase(env.TRUSTED_PROXIES);
|
|
11
24
|
|
|
12
25
|
// Register the base, never the app: the app mounts the route files, whose
|
|
13
26
|
// type reads this, and would then be typed by itself.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
|
|
3
|
+
// src/env.ts checks Bun.env once, when it is first imported: a spec gives it
|
|
4
|
+
// a fresh copy (a query string makes a new module, so the import names its
|
|
5
|
+
// extension) under the value it tests.
|
|
6
|
+
const key = "TRUSTED_PROXIES";
|
|
7
|
+
const load = async (trustedProxies: string) => {
|
|
8
|
+
const before = Bun.env[key];
|
|
9
|
+
Bun.env[key] = trustedProxies;
|
|
10
|
+
try {
|
|
11
|
+
return await import(
|
|
12
|
+
`./env.ts?trusted=${encodeURIComponent(trustedProxies)}`
|
|
13
|
+
);
|
|
14
|
+
} finally {
|
|
15
|
+
if (before === undefined) delete Bun.env[key];
|
|
16
|
+
else Bun.env[key] = before;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
test("a malformed TRUSTED_PROXIES stops the app, naming the variable", async () => {
|
|
21
|
+
await expect(load("10.0.0.0/8, not-a-range")).rejects.toThrow(
|
|
22
|
+
"TRUSTED_PROXIES.1: not a CIDR range or address",
|
|
23
|
+
);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("comma-separated ranges are trimmed, and an empty list declares no proxy", async () => {
|
|
27
|
+
const { env } = await load("10.0.0.0/8, 172.16.0.0/12");
|
|
28
|
+
expect(env.TRUSTED_PROXIES).toEqual(["10.0.0.0/8", "172.16.0.0/12"]);
|
|
29
|
+
expect((await load("")).env.TRUSTED_PROXIES).toBeUndefined();
|
|
30
|
+
});
|
package/templates/api/src/env.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { trustProxy } from "@alxia/core";
|
|
1
2
|
import { defineEnv } from "@alxia/env";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
|
|
@@ -5,16 +6,39 @@ import { z } from "zod";
|
|
|
5
6
|
// production included, is a deployment.
|
|
6
7
|
const local = ["development", "test"].includes(Bun.env.NODE_ENV ?? "");
|
|
7
8
|
|
|
9
|
+
// A range or an address trustProxy accepts: it throws on any other.
|
|
10
|
+
const isRange = (range: string) => {
|
|
11
|
+
try {
|
|
12
|
+
trustProxy({ trusted: [range], untrusted: "refuse" });
|
|
13
|
+
return true;
|
|
14
|
+
} catch {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
|
|
8
19
|
// Checked once, when this module is first imported: a missing or malformed
|
|
9
20
|
// variable stops the process, with every issue, before it listens. Secrets
|
|
10
21
|
// print as `***`. API_KEY defaults to `dev-key` in development and test
|
|
11
22
|
// alone: deployed, it is required. API_DOCS serves the API reference at
|
|
12
|
-
// /docs: on in development, off unless set elsewhere.
|
|
23
|
+
// /docs: on in development, off unless set elsewhere. TRUSTED_PROXIES is
|
|
24
|
+
// unset by default: the app then reads no forwarding header. Set it behind a
|
|
25
|
+
// load balancer (src/context.ts).
|
|
13
26
|
export const env = defineEnv(
|
|
14
27
|
{
|
|
15
28
|
PORT: z.coerce.number().default(3000),
|
|
16
29
|
API_KEY: local ? z.string().min(1).default("dev-key") : z.string().min(1),
|
|
17
30
|
API_DOCS: z.stringbool().default(Bun.env.NODE_ENV === "development"),
|
|
31
|
+
TRUSTED_PROXIES: z
|
|
32
|
+
.string()
|
|
33
|
+
.transform((list) =>
|
|
34
|
+
list
|
|
35
|
+
.split(",")
|
|
36
|
+
.map((range) => range.trim())
|
|
37
|
+
.filter(Boolean),
|
|
38
|
+
)
|
|
39
|
+
.pipe(z.array(z.string().refine(isRange, "not a CIDR range or address")))
|
|
40
|
+
.transform((ranges) => (ranges.length > 0 ? ranges : undefined))
|
|
41
|
+
.optional(),
|
|
18
42
|
},
|
|
19
43
|
{ secret: ["API_KEY"] },
|
|
20
44
|
);
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { health } from "@alxia/core";
|
|
3
|
+
import { createBase } from "./context";
|
|
4
|
+
|
|
5
|
+
// A server whose every connection comes from `peer`: app.request has none, so
|
|
6
|
+
// a spec that names a peer gives app.fetch one.
|
|
7
|
+
const from = (peer: string) =>
|
|
8
|
+
({ requestIP: () => ({ address: peer }) }) as unknown as Bun.Server<unknown>;
|
|
9
|
+
|
|
10
|
+
// The base as TRUSTED_PROXIES builds it, with a route that shows ctx.ip.
|
|
11
|
+
const behind = createBase(["10.0.0.0/8"])
|
|
12
|
+
.plugin(health())
|
|
13
|
+
.get("/ip", (ctx) => ctx.reply(200, { ip: ctx.ip ?? null }));
|
|
14
|
+
|
|
15
|
+
const get = (
|
|
16
|
+
path: string,
|
|
17
|
+
peer: string,
|
|
18
|
+
headers: Record<string, string> = {},
|
|
19
|
+
) =>
|
|
20
|
+
behind.fetch(
|
|
21
|
+
new Request(`http://alxia.test${path}`, { headers }),
|
|
22
|
+
from(peer),
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
test("a trusted proxy's X-Forwarded-For sets ctx.ip", async () => {
|
|
26
|
+
const response = await get("/ip", "10.0.0.7", {
|
|
27
|
+
"x-forwarded-for": "203.0.113.9",
|
|
28
|
+
});
|
|
29
|
+
expect(await response.json()).toEqual({ ip: "203.0.113.9" });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("a spoofed X-Forwarded-For from any other connection is refused", async () => {
|
|
33
|
+
const response = await get("/ip", "198.51.100.4", {
|
|
34
|
+
"x-forwarded-for": "203.0.113.9",
|
|
35
|
+
});
|
|
36
|
+
expect(response.status).toBe(403);
|
|
37
|
+
expect(response.headers.get("content-type")).toBe("application/problem+json");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("a request with no forwarding header passes, so a health probe does", async () => {
|
|
41
|
+
expect((await get("/health", "198.51.100.4")).status).toBe(200);
|
|
42
|
+
expect((await get("/ready", "127.0.0.1")).status).toBe(200);
|
|
43
|
+
expect(await (await get("/ip", "198.51.100.4")).json()).toEqual({
|
|
44
|
+
ip: "198.51.100.4",
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("unset, the base reads no forwarding header", async () => {
|
|
49
|
+
const plain = createBase(undefined).get("/ip", (ctx) =>
|
|
50
|
+
ctx.reply(200, { ip: ctx.ip ?? null }),
|
|
51
|
+
);
|
|
52
|
+
const response = await plain.fetch(
|
|
53
|
+
new Request("http://alxia.test/ip", {
|
|
54
|
+
headers: { "x-forwarded-for": "203.0.113.9" },
|
|
55
|
+
}),
|
|
56
|
+
from("198.51.100.4"),
|
|
57
|
+
);
|
|
58
|
+
expect(await response.json()).toEqual({ ip: "198.51.100.4" });
|
|
59
|
+
});
|
|
@@ -1,3 +1,8 @@
|
|
|
1
1
|
# Copy to .env, which Bun loads on every command: bun dev, bun test, bun start.
|
|
2
2
|
# number, optional, default 3000
|
|
3
3
|
PORT=3000
|
|
4
|
+
|
|
5
|
+
# comma-separated CIDR ranges or addresses, optional, unset by default: the proxies in front of
|
|
6
|
+
# the app, a load balancer's. Set, X-Forwarded-For from one of them sets ctx.ip, and a forwarding
|
|
7
|
+
# header from any other connection is refused with a 403. Unset, no forwarding header is read.
|
|
8
|
+
# TRUSTED_PROXIES=10.0.0.0/8,172.16.0.0/12
|
|
@@ -105,7 +105,7 @@ describes.
|
|
|
105
105
|
## Environment
|
|
106
106
|
|
|
107
107
|
Bun loads `.env` on every command, and `src/env.ts` checks what it finds. Copy
|
|
108
|
-
`.env.example` to `.env` to set `PORT`. GraphiQL follows alxia's dev
|
|
108
|
+
`.env.example` to `.env` to set `PORT` and `TRUSTED_PROXIES`. GraphiQL follows alxia's dev
|
|
109
109
|
switch: on under `bun dev`, which sets `NODE_ENV=development`, off
|
|
110
110
|
otherwise — `bun start` and the image run with `NODE_ENV=production`.
|
|
111
111
|
|
|
@@ -113,6 +113,34 @@ otherwise — `bun start` and the image run with `NODE_ENV=production`.
|
|
|
113
113
|
cp .env.example .env
|
|
114
114
|
```
|
|
115
115
|
|
|
116
|
+
## Behind a proxy
|
|
117
|
+
|
|
118
|
+
Behind a load balancer or a reverse proxy, every connection comes from
|
|
119
|
+
the proxy, and `ctx.ip` is its address. Set `TRUSTED_PROXIES` to the
|
|
120
|
+
proxies' CIDR ranges (or addresses), comma-separated, and `src/context.ts`
|
|
121
|
+
declares them with `trustProxy`:
|
|
122
|
+
|
|
123
|
+
```sh
|
|
124
|
+
TRUSTED_PROXIES=10.0.0.0/8,172.16.0.0/12 bun start
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
- A request from one of them has its `ctx.ip` read from `X-Forwarded-For`,
|
|
128
|
+
from the right: the entries the client wrote are never believed.
|
|
129
|
+
- A request that carries `X-Forwarded-For`, `X-Forwarded-Proto`,
|
|
130
|
+
`X-Forwarded-Host` or `Forwarded` from any other connection is answered
|
|
131
|
+
403 (`untrusted: 'refuse'`), so nothing reads what it claims.
|
|
132
|
+
- A request that carries none passes from anywhere, so the Docker and
|
|
133
|
+
orchestrator health probes reach `/health` and `/ready` as before.
|
|
134
|
+
- Unset, the default, no forwarding header is read: the app behaves as
|
|
135
|
+
though the variable did not exist. Your proxy must overwrite
|
|
136
|
+
`X-Forwarded-*` (an AWS load balancer does; nginx needs
|
|
137
|
+
`proxy_set_header`), and the ranges must name the proxies alone.
|
|
138
|
+
|
|
139
|
+
To refuse every connection but the proxies', probes included, use
|
|
140
|
+
`untrusted: 'refuse-all'` with `allow`: see
|
|
141
|
+
[Serving](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/serving.md#only-the-proxies-refuse-all).
|
|
142
|
+
`src/proxy.spec.ts` shows both answers with `app.fetch` given a peer.
|
|
143
|
+
|
|
116
144
|
## Test
|
|
117
145
|
|
|
118
146
|
```sh
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { alxia, defineMiddleware } from "@alxia/core";
|
|
1
|
+
import { alxia, defineMiddleware, trustProxy } from "@alxia/core";
|
|
2
2
|
import type { GraphQLContext } from "@alxia/graphql";
|
|
3
3
|
import { env } from "./env";
|
|
4
4
|
import type { Loaders } from "./loaders";
|
|
@@ -18,7 +18,20 @@ const viewerOf = defineMiddleware(({ request }, next) => {
|
|
|
18
18
|
});
|
|
19
19
|
|
|
20
20
|
// The base: what every resolver reads, decorated or derived here.
|
|
21
|
-
|
|
21
|
+
//
|
|
22
|
+
// Behind a load balancer, set TRUSTED_PROXIES to its range: its
|
|
23
|
+
// X-Forwarded-For then sets ctx.ip, and a forwarding header from any other
|
|
24
|
+
// connection is refused with a 403. A request that carries none, a health
|
|
25
|
+
// probe's, passes from anywhere. Unset, no forwarding header is read.
|
|
26
|
+
export function createBase(trusted: string[] | undefined) {
|
|
27
|
+
return alxia({
|
|
28
|
+
...(trusted && { proxy: trustProxy({ trusted, untrusted: "refuse" }) }),
|
|
29
|
+
})
|
|
30
|
+
.decorate({ env, db })
|
|
31
|
+
.use(viewerOf);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const base = createBase(env.TRUSTED_PROXIES);
|
|
22
35
|
|
|
23
36
|
// A resolver's context: Yoga's, the base's (`env`, `db`, `viewer`) and the
|
|
24
37
|
// per-request `loaders` that src/app.ts's `context` option builds. The
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
|
|
3
|
+
// src/env.ts checks Bun.env once, when it is first imported: a spec gives it
|
|
4
|
+
// a fresh copy (a query string makes a new module, so the import names its
|
|
5
|
+
// extension) under the value it tests.
|
|
6
|
+
const key = "TRUSTED_PROXIES";
|
|
7
|
+
const load = async (trustedProxies: string) => {
|
|
8
|
+
const before = Bun.env[key];
|
|
9
|
+
Bun.env[key] = trustedProxies;
|
|
10
|
+
try {
|
|
11
|
+
return await import(
|
|
12
|
+
`./env.ts?trusted=${encodeURIComponent(trustedProxies)}`
|
|
13
|
+
);
|
|
14
|
+
} finally {
|
|
15
|
+
if (before === undefined) delete Bun.env[key];
|
|
16
|
+
else Bun.env[key] = before;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
test("a malformed TRUSTED_PROXIES stops the app, naming the variable", async () => {
|
|
21
|
+
await expect(load("10.0.0.0/8, not-a-range")).rejects.toThrow(
|
|
22
|
+
"TRUSTED_PROXIES.1: not a CIDR range or address",
|
|
23
|
+
);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("comma-separated ranges are trimmed, and an empty list declares no proxy", async () => {
|
|
27
|
+
const { env } = await load("10.0.0.0/8, 172.16.0.0/12");
|
|
28
|
+
expect(env.TRUSTED_PROXIES).toEqual(["10.0.0.0/8", "172.16.0.0/12"]);
|
|
29
|
+
expect((await load("")).env.TRUSTED_PROXIES).toBeUndefined();
|
|
30
|
+
});
|
|
@@ -1,8 +1,32 @@
|
|
|
1
|
+
import { trustProxy } from "@alxia/core";
|
|
1
2
|
import { defineEnv } from "@alxia/env";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
|
|
5
|
+
// A range or an address trustProxy accepts: it throws on any other.
|
|
6
|
+
const isRange = (range: string) => {
|
|
7
|
+
try {
|
|
8
|
+
trustProxy({ trusted: [range], untrusted: "refuse" });
|
|
9
|
+
return true;
|
|
10
|
+
} catch {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
|
|
4
15
|
// Checked once, when this module is first imported: a malformed variable
|
|
5
|
-
// stops the process, with every issue, before it listens.
|
|
16
|
+
// stops the process, with every issue, before it listens. TRUSTED_PROXIES is
|
|
17
|
+
// unset by default: the app then reads no forwarding header. Set it behind a
|
|
18
|
+
// load balancer (src/context.ts).
|
|
6
19
|
export const env = defineEnv({
|
|
7
20
|
PORT: z.coerce.number().default(3000),
|
|
21
|
+
TRUSTED_PROXIES: z
|
|
22
|
+
.string()
|
|
23
|
+
.transform((list) =>
|
|
24
|
+
list
|
|
25
|
+
.split(",")
|
|
26
|
+
.map((range) => range.trim())
|
|
27
|
+
.filter(Boolean),
|
|
28
|
+
)
|
|
29
|
+
.pipe(z.array(z.string().refine(isRange, "not a CIDR range or address")))
|
|
30
|
+
.transform((ranges) => (ranges.length > 0 ? ranges : undefined))
|
|
31
|
+
.optional(),
|
|
8
32
|
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { health } from "@alxia/core";
|
|
3
|
+
import { createBase } from "./context";
|
|
4
|
+
|
|
5
|
+
// A server whose every connection comes from `peer`: app.request has none, so
|
|
6
|
+
// a spec that names a peer gives app.fetch one.
|
|
7
|
+
const from = (peer: string) =>
|
|
8
|
+
({ requestIP: () => ({ address: peer }) }) as unknown as Bun.Server<unknown>;
|
|
9
|
+
|
|
10
|
+
// The base as TRUSTED_PROXIES builds it, with a route that shows ctx.ip.
|
|
11
|
+
const behind = createBase(["10.0.0.0/8"])
|
|
12
|
+
.plugin(health())
|
|
13
|
+
.get("/ip", (ctx) => ctx.reply(200, { ip: ctx.ip ?? null }));
|
|
14
|
+
|
|
15
|
+
const get = (
|
|
16
|
+
path: string,
|
|
17
|
+
peer: string,
|
|
18
|
+
headers: Record<string, string> = {},
|
|
19
|
+
) =>
|
|
20
|
+
behind.fetch(
|
|
21
|
+
new Request(`http://alxia.test${path}`, { headers }),
|
|
22
|
+
from(peer),
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
test("a trusted proxy's X-Forwarded-For sets ctx.ip", async () => {
|
|
26
|
+
const response = await get("/ip", "10.0.0.7", {
|
|
27
|
+
"x-forwarded-for": "203.0.113.9",
|
|
28
|
+
});
|
|
29
|
+
expect(await response.json()).toEqual({ ip: "203.0.113.9" });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("a spoofed X-Forwarded-For from any other connection is refused", async () => {
|
|
33
|
+
const response = await get("/ip", "198.51.100.4", {
|
|
34
|
+
"x-forwarded-for": "203.0.113.9",
|
|
35
|
+
});
|
|
36
|
+
expect(response.status).toBe(403);
|
|
37
|
+
expect(response.headers.get("content-type")).toBe("application/json");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("a request with no forwarding header passes, so a health probe does", async () => {
|
|
41
|
+
expect((await get("/health", "198.51.100.4")).status).toBe(200);
|
|
42
|
+
expect((await get("/ready", "127.0.0.1")).status).toBe(200);
|
|
43
|
+
expect(await (await get("/ip", "198.51.100.4")).json()).toEqual({
|
|
44
|
+
ip: "198.51.100.4",
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("unset, the base reads no forwarding header", async () => {
|
|
49
|
+
const plain = createBase(undefined).get("/ip", (ctx) =>
|
|
50
|
+
ctx.reply(200, { ip: ctx.ip ?? null }),
|
|
51
|
+
);
|
|
52
|
+
const response = await plain.fetch(
|
|
53
|
+
new Request("http://alxia.test/ip", {
|
|
54
|
+
headers: { "x-forwarded-for": "203.0.113.9" },
|
|
55
|
+
}),
|
|
56
|
+
from("198.51.100.4"),
|
|
57
|
+
);
|
|
58
|
+
expect(await response.json()).toEqual({ ip: "198.51.100.4" });
|
|
59
|
+
});
|