mirror of
https://github.com/nestriness/nestri.git
synced 2026-09-19 09:15:19 +03:00
feat(deploy): drop the IaC layer, and make both apps runnable as containers
Moving the issuer's state into Postgres removed the last thing that tied either app to one hosting provider. What was left was a deployment tool describing resources that no longer existed — so this replaces it with `wrangler`, which is what actually deploys a Worker, and adds a second way to run each app that involves no provider at all. Each app now has a `wrangler.jsonc` with an environment per stage, and a `Dockerfile` beside it. The handler is the same one in both cases; what differs is only where its settings come from. Two of them gained a second spelling so that nothing has to branch on the runtime: Postgres arrives as a pooled binding or as `DATABASE_URL`, and the route to the issuer is a service binding or `AUTH_INTERNAL_URL`. That last one is new, and it is a split the binding was already making without saying so. `AUTH_ISSUER_URL` has to be the issuer's public name, because it is compared literally against every token's `iss` claim — but the public name is often not routable from inside a deployment. So the name and the route are two settings now rather than one that cannot be both. DNS moves out of code and into `docs/dns.md`, which lists every hostname and what it is for. Six records that change roughly never did not need a tool, and the table outlives whatever is answering the names — which is the point, since some of them will stop being Workers. The sandbox hostnames are hyphenated rather than nested for the same reason: a certificate covering `*.nestri.io` covers one label and not two, so `api-sandbox.nestri.io` can become an ordinary origin later without a certificate having to be ordered for it first. Also drops `EMAIL_DEV_LOG` from committed configuration into `.dev.vars`, which `wrangler deploy` cannot upload. Printing a live sign-in code to a log should not be one forgotten override away from production.
This commit is contained in:
64
apps/api/Dockerfile
Normal file
64
apps/api/Dockerfile
Normal file
@@ -0,0 +1,64 @@
|
||||
# The API as a container.
|
||||
#
|
||||
# Build from the repository root — the workspace lockfile and two shared
|
||||
# packages live there, so a context rooted at this directory could not resolve
|
||||
# them:
|
||||
#
|
||||
# docker build -f apps/api/Dockerfile -t nestri-api .
|
||||
#
|
||||
# The repository-wide `.dockerignore` is what this build excludes. It used to
|
||||
# exclude the whole TypeScript half, because the guest rootfs build was the
|
||||
# only Dockerfile here — that part now lives in `build/Dockerfile.dockerignore`,
|
||||
# beside the build it belongs to.
|
||||
FROM oven/bun:1.3.11-alpine AS deps
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Manifests first, source second. Dependencies change far less often than code
|
||||
# does, so this layer survives most rebuilds. Every workspace member's manifest
|
||||
# has to be here even if this image does not import it: the lockfile describes
|
||||
# the whole workspace, and resolving it against a partial one is not frozen.
|
||||
COPY package.json bun.lock ./
|
||||
COPY apps/api/package.json apps/api/
|
||||
COPY apps/auth/package.json apps/auth/
|
||||
COPY packages/core/package.json packages/core/
|
||||
COPY packages/auth/package.json packages/auth/
|
||||
|
||||
# No dev dependencies. Bun runs TypeScript without a build step, so nothing in
|
||||
# them is reachable at runtime — they are the type definitions, the linter and
|
||||
# the deployment CLI.
|
||||
RUN bun install --frozen-lockfile --production
|
||||
|
||||
|
||||
FROM oven/bun:1.3.11-alpine AS runtime
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=deps /app/node_modules node_modules
|
||||
COPY tsconfig.json ./
|
||||
COPY package.json bun.lock ./
|
||||
COPY apps/api apps/api
|
||||
COPY packages/core packages/core
|
||||
COPY packages/auth packages/auth
|
||||
|
||||
# The image ships no configuration. Every setting arrives from the environment,
|
||||
# which is what makes one image good for a self-hoster and for us:
|
||||
#
|
||||
# DATABASE_URL postgres://… required
|
||||
# AUTH_ISSUER_URL the issuer's public URL required
|
||||
# STEAM_API_KEY for linking an account
|
||||
# ADMIN_SHARED_SECRET operator access
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
EXPOSE 3000
|
||||
|
||||
# `bun` is a non-root user the base image already provides.
|
||||
USER bun
|
||||
|
||||
# `/` answers without touching the database, which is the right shape for a
|
||||
# liveness probe: it says this process is serving, and leaves "can it reach
|
||||
# Postgres" to a readiness check that is allowed to fail loudly.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD wget -q -O /dev/null http://127.0.0.1:${PORT}/ || exit 1
|
||||
|
||||
CMD ["bun", "run", "apps/api/app/server.ts"]
|
||||
@@ -1,6 +1,7 @@
|
||||
# apps/api
|
||||
|
||||
The public HTTP API for Nestri — a [Hono](https://hono.dev) app deployed as a Cloudflare Worker.
|
||||
The public HTTP API for Nestri — a [Hono](https://hono.dev) app. One handler, run either as a
|
||||
Cloudflare Worker or as an ordinary HTTP server.
|
||||
|
||||
## What it does
|
||||
|
||||
@@ -26,19 +27,32 @@ Routes:
|
||||
|
||||
```text
|
||||
app/
|
||||
index.ts # Hono entrypoint: middleware, routes, error handler, /doc
|
||||
index.ts # The handler: middleware, routes, error handler, /doc
|
||||
server.ts # The same handler behind a listening socket
|
||||
middleware/auth.ts # Bearer JWT + admin shared-secret auth → Actor
|
||||
routes/*.ts # Thin route namespaces (UserApi, SteamApi, ...)
|
||||
utils/ # ErrorResponses, Result(), validator wrapping
|
||||
test/ # Route tests (Vitest/Bun)
|
||||
wrangler.jsonc # Worker configuration, one environment per stage
|
||||
Dockerfile # The container, built from the repository root
|
||||
test/ # Route tests
|
||||
```
|
||||
|
||||
## Key details
|
||||
|
||||
- Auth: `Authorization: Bearer <JWT>` verified against `@nestri/auth`; or the `x-nestri-admin-token` header (see `ADMIN_SHARED_SECRET`).
|
||||
- Errors: centralized `VisibleError` → typed JSON responses.
|
||||
- The API worker receives its bindings (`AUTH`, `HYPERDRIVE`, `STEAM_API_KEY`, `ADMIN_SHARED_SECRET`) from Alchemy — see `alchemy.run.ts` at the repo root.
|
||||
- Settings arrive as bindings or as environment variables, and two of them have one spelling of
|
||||
each: Postgres is `HYPERDRIVE` or `DATABASE_URL`, and the route to the issuer is an `AUTH`
|
||||
service binding or `AUTH_INTERNAL_URL`. Nothing here branches on which it got.
|
||||
- `AUTH_ISSUER_URL` is the issuer's **public** URL and never the internal one, because it is
|
||||
compared literally against the `iss` claim on every token.
|
||||
|
||||
## Running
|
||||
|
||||
Run via the root Alchemy setup (`bun alchemy.run.ts --dev`). Needs a Postgres database and an auth worker; see the root README for full dev setup.
|
||||
```sh
|
||||
bun run dev # under the Workers runtime, on :3000
|
||||
bun run serve # as a plain process, on $PORT (default 3000)
|
||||
```
|
||||
|
||||
Needs a Postgres database and a reachable issuer. Full list and deployment steps:
|
||||
[`docs/deploy.md`](../../docs/deploy.md).
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Hyperdrive } from '@cloudflare/workers-types';
|
||||
import { Env } from '@nestri/core/env';
|
||||
import { ErrorCodes, VisibleError } from '@nestri/core/error';
|
||||
import type { InferEnv } from 'alchemy/Cloudflare';
|
||||
import { Hono } from 'hono';
|
||||
import { openAPISpecs } from 'hono-openapi';
|
||||
import { cors } from 'hono/cors';
|
||||
@@ -8,7 +8,6 @@ import { HTTPException } from 'hono/http-exception';
|
||||
import { logger } from 'hono/logger';
|
||||
import { type ContentfulStatusCode } from 'hono/utils/http-status';
|
||||
|
||||
import type { Api } from '../../../alchemy.run.ts';
|
||||
import { auth } from './middleware/auth.js';
|
||||
import { AccessTokenApi } from './routes/access-token.js';
|
||||
import { GameApi } from './routes/game.js';
|
||||
@@ -103,8 +102,33 @@ app.get(
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* Everything this app is handed, from a binding or from the environment.
|
||||
*
|
||||
* Two things here arrive one of two ways, and neither is a special case.
|
||||
* `HYPERDRIVE` carries a connection string on a platform that pools
|
||||
* connections for us, and `DATABASE_URL` says the same thing where nothing
|
||||
* does. An `AUTH` binding is a route to the issuer that skips the internet,
|
||||
* and `AUTH_INTERNAL_URL` is that route written out. Each pair is two
|
||||
* spellings of one fact rather than two deployments, which is why nothing
|
||||
* below branches on the runtime it is under.
|
||||
*
|
||||
* `AUTH_ISSUER_URL` is not part of either pair. It is the issuer's public
|
||||
* *name*, it is required, and it is the same value however the issuer is
|
||||
* reached — because it is what every token's `iss` claim is checked against.
|
||||
*/
|
||||
export type ApiEnv = {
|
||||
AUTH?: { fetch: typeof fetch };
|
||||
AUTH_ISSUER_URL?: string;
|
||||
AUTH_INTERNAL_URL?: string;
|
||||
HYPERDRIVE?: Hyperdrive;
|
||||
DATABASE_URL?: string;
|
||||
STEAM_API_KEY?: string;
|
||||
ADMIN_SHARED_SECRET?: string;
|
||||
};
|
||||
|
||||
export default {
|
||||
fetch(request: Request, env: InferEnv<typeof Api>, ctx: ExecutionContext) {
|
||||
fetch(request: Request, env: ApiEnv, ctx?: ExecutionContext) {
|
||||
Env.init(env as unknown as Record<string, unknown>);
|
||||
return app.fetch(request, env, ctx);
|
||||
}
|
||||
|
||||
@@ -9,30 +9,55 @@ import { Member } from '@nestri/core/team/member';
|
||||
import type { MiddlewareHandler } from 'hono';
|
||||
|
||||
/**
|
||||
* Reaches the auth worker over its service binding.
|
||||
* Reaches the issuer, over a binding where the platform offers one.
|
||||
*
|
||||
* The origin has to survive. A binding routes by binding rather than by
|
||||
* hostname, so the host is arbitrary — but `new Request` still demands an
|
||||
* absolute URL, and stripping down to a bare path threw `Invalid URL` before
|
||||
* the token was even looked at.
|
||||
* A binding routes by binding rather than by hostname, which saves a trip out
|
||||
* to the internet and back for a call this middleware makes on nearly every
|
||||
* request. The host in the URL is then arbitrary — but `new Request` still
|
||||
* demands an absolute URL, and stripping down to a bare path threw
|
||||
* `Invalid URL` before the token was even looked at.
|
||||
*
|
||||
* Where there is no such binding the issuer is an ordinary HTTP origin at
|
||||
* `AUTH_ISSUER_URL` and plain `fetch` is the whole of it. Nothing else here
|
||||
* changes, because the URL being fetched is the same one either way.
|
||||
*/
|
||||
function bindingFetch(env: Record<string, unknown>) {
|
||||
function issuerFetch(env: Record<string, unknown>, issuer: string) {
|
||||
const binding = env?.AUTH as { fetch: typeof fetch } | undefined;
|
||||
if (typeof binding?.fetch === 'function') {
|
||||
return (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = asUrl(input);
|
||||
return binding.fetch(new Request(url, init));
|
||||
};
|
||||
}
|
||||
|
||||
// The same split the binding makes, spelled out: `AUTH_INTERNAL_URL` is
|
||||
// the route and `issuer` stays the name. The client builds its URLs from
|
||||
// the name, so the swap happens here, on the way out, and every claim
|
||||
// checked afterwards is still checked against the name.
|
||||
const internal = Env.get().AUTH_INTERNAL_URL?.replace(/\/+$/, '');
|
||||
if (!internal || internal === issuer) {
|
||||
return (input: RequestInfo | URL, init?: RequestInit) => fetch(asUrl(input), init);
|
||||
}
|
||||
return (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
return (env.AUTH as { fetch: typeof fetch }).fetch(new Request(url, init));
|
||||
const url = asUrl(input);
|
||||
return fetch(url.startsWith(issuer) ? internal + url.slice(issuer.length) : url, init);
|
||||
};
|
||||
}
|
||||
|
||||
function asUrl(input: RequestInfo | URL): string {
|
||||
return typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
}
|
||||
|
||||
/**
|
||||
* The issuer must be the auth worker's **public** URL.
|
||||
* The issuer must be its **public** URL.
|
||||
*
|
||||
* `verify` checks a token's `iss` claim against the issuer the client was
|
||||
* built with, and the auth worker derives what it advertises from the URL it
|
||||
* was reached on. Tokens are minted through the public URL, so they carry it.
|
||||
* A placeholder like `https://auth.internal` addresses the binding perfectly
|
||||
* well — the hostname is ignored there — and then disagrees with every real
|
||||
* token. Discovery through the binding does not help: it answers with the
|
||||
* placeholder too, because that is the host it was asked on.
|
||||
* built with, and the issuer derives what it advertises from the URL it was
|
||||
* reached on. Tokens are minted through the public URL, so they carry it. A
|
||||
* placeholder like `https://auth.internal` addresses a binding perfectly well
|
||||
* — the hostname is ignored there — and then disagrees with every real token.
|
||||
* Discovery through the binding does not help: it answers with the placeholder
|
||||
* too, because that is the host it was asked on.
|
||||
*
|
||||
* The failure is silent by nature. A rejected claim is reported as `err`,
|
||||
* which is indistinguishable from an expired or forged token, so the whole
|
||||
@@ -55,7 +80,7 @@ function getClient(env: Record<string, unknown>) {
|
||||
return createClient({
|
||||
issuer,
|
||||
clientID: 'api',
|
||||
fetch: bindingFetch(env)
|
||||
fetch: issuerFetch(env, issuer)
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
40
apps/api/app/server.ts
Normal file
40
apps/api/app/server.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* The API as an ordinary HTTP server.
|
||||
*
|
||||
* `index.ts` exports a handler taking `(request, env)` — the shape a Worker is
|
||||
* invoked with, and also the shape of a plain function from a request to a
|
||||
* response. So there is nothing here but the loop that calls it: the process
|
||||
* environment stands in for the bindings, and a port stands in for the route.
|
||||
*
|
||||
* With no `AUTH` binding in that environment the middleware reaches the issuer
|
||||
* over plain HTTP at `AUTH_ISSUER_URL`, which is a setting this deployment has
|
||||
* either way. Nothing else differs.
|
||||
*/
|
||||
import handler, { type ApiEnv } from './index.js';
|
||||
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
|
||||
Bun.serve({
|
||||
port,
|
||||
hostname: '0.0.0.0',
|
||||
// A Worker runtime hands the handler a context whose `waitUntil` keeps the
|
||||
// invocation alive past the response. A process does not need convincing to
|
||||
// stay alive, so the equivalent is to let the promise run — with a catch,
|
||||
// because an unobserved rejection here would take the server down rather
|
||||
// than the request that caused it.
|
||||
fetch: (request) =>
|
||||
handler.fetch(
|
||||
request,
|
||||
process.env as unknown as ApiEnv,
|
||||
{
|
||||
waitUntil: (promise: Promise<unknown>) => {
|
||||
void Promise.resolve(promise).catch((error: unknown) => {
|
||||
console.error('[api] background task failed:', error);
|
||||
});
|
||||
},
|
||||
passThroughOnException: () => {}
|
||||
} as unknown as ExecutionContext
|
||||
)
|
||||
});
|
||||
|
||||
console.log(`[api] listening on http://0.0.0.0:${port}`);
|
||||
@@ -1,6 +1,11 @@
|
||||
{
|
||||
"name": "api",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "wrangler dev",
|
||||
"serve": "bun run app/server.ts",
|
||||
"deploy": "wrangler deploy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hono/zod-validator": "^0.9.0",
|
||||
"@nestri/auth": "workspace:",
|
||||
|
||||
63
apps/api/wrangler.jsonc
Normal file
63
apps/api/wrangler.jsonc
Normal file
@@ -0,0 +1,63 @@
|
||||
// The public API, deployed as a Cloudflare Worker.
|
||||
//
|
||||
// The same `app/index.ts` also runs as an ordinary HTTP server — see
|
||||
// `app/server.ts` and the `Dockerfile` beside it.
|
||||
//
|
||||
// Hostnames and the reasoning behind their shape: `docs/dns.md`.
|
||||
// Secrets, the Hyperdrive id, and how to deploy: `docs/deploy.md`.
|
||||
{
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
"name": "nestri-api",
|
||||
"main": "app/index.ts",
|
||||
"compatibility_date": "2026-09-05",
|
||||
"compatibility_flags": ["nodejs_compat"],
|
||||
"workers_dev": false,
|
||||
"dev": {
|
||||
"port": 3000
|
||||
},
|
||||
|
||||
// `AUTH` routes by binding rather than by hostname, so it is one hop
|
||||
// shorter than a request over the internet and needs no public address.
|
||||
// It is an optimisation and not a requirement: with no such binding the
|
||||
// middleware reaches the issuer over plain HTTP at `AUTH_ISSUER_URL`,
|
||||
// which is what the container path does.
|
||||
//
|
||||
// `wrangler dev` discovers a sibling session serving the same script name,
|
||||
// so running both dev servers wires this up locally.
|
||||
"services": [{ "binding": "AUTH", "service": "nestri-auth" }],
|
||||
"hyperdrive": [
|
||||
{
|
||||
"binding": "HYPERDRIVE",
|
||||
"id": "0000000000000000000000000000dev0",
|
||||
"localConnectionString": "postgres://postgres:postgres@localhost:5432/nestri"
|
||||
}
|
||||
],
|
||||
"vars": {
|
||||
// The issuer's **public** URL, always. A token's `iss` claim carries
|
||||
// the address it was minted through, and verification compares the two
|
||||
// literally — so naming the binding here instead would reject every
|
||||
// real token, and report it as an ordinary 401.
|
||||
"AUTH_ISSUER_URL": "http://localhost:1337"
|
||||
},
|
||||
|
||||
"env": {
|
||||
"sandbox": {
|
||||
"name": "nestri-api-sandbox",
|
||||
"workers_dev": false,
|
||||
"routes": [{ "pattern": "api-sandbox.nestri.io", "custom_domain": true }],
|
||||
"observability": { "enabled": true },
|
||||
"services": [{ "binding": "AUTH", "service": "nestri-auth-sandbox" }],
|
||||
"hyperdrive": [{ "binding": "HYPERDRIVE", "id": "<sandbox-hyperdrive-id>" }],
|
||||
"vars": { "AUTH_ISSUER_URL": "https://auth-sandbox.nestri.io" }
|
||||
},
|
||||
"production": {
|
||||
"name": "nestri-api",
|
||||
"workers_dev": false,
|
||||
"routes": [{ "pattern": "api.nestri.io", "custom_domain": true }],
|
||||
"observability": { "enabled": true },
|
||||
"services": [{ "binding": "AUTH", "service": "nestri-auth" }],
|
||||
"hyperdrive": [{ "binding": "HYPERDRIVE", "id": "<production-hyperdrive-id>" }],
|
||||
"vars": { "AUTH_ISSUER_URL": "https://auth.nestri.io" }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user