mirror of
https://github.com/nestriness/nestri.git
synced 2026-09-22 18:55:22 +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:
9
apps/auth/.dev.vars
Normal file
9
apps/auth/.dev.vars
Normal file
@@ -0,0 +1,9 @@
|
||||
# Local-only settings, read by `wrangler dev` and never uploaded by
|
||||
# `wrangler deploy`. Committed because it holds no secret and because a
|
||||
# checkout should be able to sign in without a mail provider.
|
||||
#
|
||||
# Printing a live sign-in code to the log is a thing you ask for by name. The
|
||||
# issuer refuses to send with its mail settings absent rather than falling back
|
||||
# to this, so a deployment that forgot them fails loudly instead of quietly
|
||||
# logging usable codes.
|
||||
EMAIL_DEV_LOG=true
|
||||
68
apps/auth/Dockerfile
Normal file
68
apps/auth/Dockerfile
Normal file
@@ -0,0 +1,68 @@
|
||||
# The issuer 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/auth/Dockerfile -t nestri-auth .
|
||||
#
|
||||
# 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/auth apps/auth
|
||||
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
|
||||
# EMAIL_SEND_URL where a code is posted \
|
||||
# EMAIL_API_KEY credential for it > all three together, or none
|
||||
# EMAIL_FROM the sender address /
|
||||
# EMAIL_DEV_LOG `true` prints codes to the log instead of sending them
|
||||
#
|
||||
# With none of the three set and no `EMAIL_DEV_LOG`, the issuer refuses to send
|
||||
# rather than falling back — a deployment that forgot its mail settings is
|
||||
# exactly the one with nothing marking it as a real one.
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=1337
|
||||
EXPOSE 1337
|
||||
|
||||
# `bun` is a non-root user the base image already provides.
|
||||
USER bun
|
||||
|
||||
# The discovery document is served from memory and reaches no database, which
|
||||
# is the right shape for a liveness probe.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD wget -q -O /dev/null http://127.0.0.1:${PORT}/.well-known/oauth-authorization-server || exit 1
|
||||
|
||||
CMD ["bun", "run", "apps/auth/src/server.ts"]
|
||||
@@ -1,7 +1,8 @@
|
||||
# apps/auth
|
||||
|
||||
The authentication worker for Nestri — a Cloudflare Worker built on
|
||||
[`@nestri/auth`](../../packages/auth/README.md) (OpenAuth-style issuer).
|
||||
The authentication service for Nestri, built on
|
||||
[`@nestri/auth`](../../packages/auth/README.md) (OpenAuth-style issuer). One
|
||||
handler, run either as a Cloudflare Worker or as an ordinary HTTP server.
|
||||
|
||||
## What it does
|
||||
|
||||
@@ -26,17 +27,28 @@ Hosts the OAuth issuer and the sign-in UI:
|
||||
- Authorization codes, refresh tokens and device codes are stored as hashes. Each is a bearer
|
||||
credential, so what is kept is enough to recognise one and not enough to present it.
|
||||
- JWT subjects are defined in `@nestri/core/auth/subjects`.
|
||||
- The API worker verifies tokens against this issuer through `AUTH_ISSUER_URL`.
|
||||
- The API verifies tokens against this issuer through `AUTH_ISSUER_URL`, which must be this
|
||||
service's **public** URL: a token carries the address it was minted through and the check is
|
||||
literal.
|
||||
|
||||
## Structure
|
||||
|
||||
```text
|
||||
src/index.ts # Worker entrypoint: issuer config, stores, success callback
|
||||
src/index.ts # The handler: issuer config, stores, success callback
|
||||
src/server.ts # The same handler behind a listening socket
|
||||
src/email.ts # Verification code delivery
|
||||
test/ # Worker tests
|
||||
wrangler.jsonc # Worker configuration, one environment per stage
|
||||
Dockerfile # The container, built from the repository root
|
||||
test/
|
||||
```
|
||||
|
||||
## Running
|
||||
|
||||
Deployed through Alchemy (`apps/auth` worker in `alchemy.run.ts` at the repo root). Its only
|
||||
stateful binding is `HYPERDRIVE` (Postgres), alongside the mail settings.
|
||||
```sh
|
||||
bun run dev # under the Workers runtime, on :1337
|
||||
bun run serve # as a plain process, on $PORT (default 1337)
|
||||
```
|
||||
|
||||
Its only stateful dependency is Postgres — as a `HYPERDRIVE` binding on Workers, or as
|
||||
`DATABASE_URL` anywhere else — alongside the mail settings. Full list and deployment steps:
|
||||
[`docs/deploy.md`](../../docs/deploy.md).
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
"name": "auth",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite"
|
||||
"dev": "wrangler dev",
|
||||
"serve": "bun run src/server.ts",
|
||||
"deploy": "wrangler deploy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestri/auth": "workspace:",
|
||||
|
||||
@@ -16,8 +16,18 @@ import { LinkedAccount } from '@nestri/core/user/linked-account';
|
||||
|
||||
import { sendVerificationCode } from './email.js';
|
||||
|
||||
/**
|
||||
* Everything this issuer is handed, from a binding or from the environment.
|
||||
*
|
||||
* The database arrives one of two ways and neither is a special case:
|
||||
* `HYPERDRIVE` carries a connection string on a platform that pools
|
||||
* connections for us, `DATABASE_URL` says the same thing where nothing does.
|
||||
* Both are optional here so that a deployment is free to supply either, and
|
||||
* `@nestri/core`'s `Env` resolves the pair into one.
|
||||
*/
|
||||
type Env = {
|
||||
HYPERDRIVE: Hyperdrive;
|
||||
HYPERDRIVE?: Hyperdrive;
|
||||
DATABASE_URL?: string;
|
||||
EMAIL_SEND_URL?: string;
|
||||
EMAIL_API_KEY?: string;
|
||||
EMAIL_FROM?: string;
|
||||
@@ -59,7 +69,7 @@ async function firstSteamLink(userID: string): Promise<string> {
|
||||
}
|
||||
|
||||
export default {
|
||||
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
||||
async fetch(request: Request, env: Env, ctx?: ExecutionContext) {
|
||||
Env.init(env as unknown as Record<string, unknown>);
|
||||
const inner = issuer({
|
||||
subjects,
|
||||
|
||||
42
apps/auth/src/server.ts
Normal file
42
apps/auth/src/server.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* The issuer 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.
|
||||
*
|
||||
* This is the path a self-hoster takes, and the one this deployment takes when
|
||||
* it stops being a Worker. Keeping it in the tree rather than writing it on
|
||||
* that day is what stops the handler from quietly growing a dependency on a
|
||||
* platform it will not always be on — the difference shows up as a type error
|
||||
* here rather than as a discovery during a migration.
|
||||
*/
|
||||
import handler from './index.js';
|
||||
|
||||
const port = Number(process.env.PORT ?? 1337);
|
||||
|
||||
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 Parameters<typeof handler.fetch>[1],
|
||||
{
|
||||
waitUntil: (promise: Promise<unknown>) => {
|
||||
void Promise.resolve(promise).catch((error: unknown) => {
|
||||
console.error('[auth] background task failed:', error);
|
||||
});
|
||||
},
|
||||
passThroughOnException: () => {}
|
||||
} as unknown as ExecutionContext
|
||||
)
|
||||
});
|
||||
|
||||
console.log(`[auth] listening on http://0.0.0.0:${port}`);
|
||||
59
apps/auth/wrangler.jsonc
Normal file
59
apps/auth/wrangler.jsonc
Normal file
@@ -0,0 +1,59 @@
|
||||
// The issuer, deployed as a Cloudflare Worker.
|
||||
//
|
||||
// The same `src/index.ts` also runs as an ordinary HTTP server — see
|
||||
// `src/server.ts` and the `Dockerfile` beside it. Nothing in the handler is
|
||||
// Workers-specific; what differs between the two is only where the settings
|
||||
// below come from, so this file and the container's environment are two
|
||||
// spellings of one list.
|
||||
//
|
||||
// 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-auth",
|
||||
"main": "src/index.ts",
|
||||
"compatibility_date": "2026-09-05",
|
||||
"compatibility_flags": ["nodejs_compat"],
|
||||
// No `*.workers.dev` hostname. A second address that mints tokens is a
|
||||
// second issuer as far as a token's `iss` claim is concerned, and every
|
||||
// token minted through it is rejected by the API.
|
||||
"workers_dev": false,
|
||||
"dev": {
|
||||
"port": 1337
|
||||
},
|
||||
|
||||
// Local-only settings live in `.dev.vars` beside this file rather than in
|
||||
// `vars` here. `wrangler dev` reads that file and `wrangler deploy` cannot
|
||||
// upload it — which is the guarantee wanted for the one setting in it:
|
||||
// printing a live sign-in code to the log is a thing you ask for by name,
|
||||
// and no stage anybody else can reach may have it. Written as a `vars`
|
||||
// entry it would be one forgotten override away from being deployed.
|
||||
|
||||
// The default environment is the local one. `localConnectionString` is what
|
||||
// `wrangler dev` uses, so a checkout with `docker compose up postgres`
|
||||
// running needs nothing else; `id` is only read on deploy, and the two
|
||||
// named environments below carry their own.
|
||||
"hyperdrive": [
|
||||
{
|
||||
"binding": "HYPERDRIVE",
|
||||
"id": "0000000000000000000000000000dev0",
|
||||
"localConnectionString": "postgres://postgres:postgres@localhost:5432/nestri"
|
||||
}
|
||||
],
|
||||
"env": {
|
||||
"sandbox": {
|
||||
"name": "nestri-auth-sandbox",
|
||||
"workers_dev": false,
|
||||
"routes": [{ "pattern": "auth-sandbox.nestri.io", "custom_domain": true }],
|
||||
"observability": { "enabled": true },
|
||||
"hyperdrive": [{ "binding": "HYPERDRIVE", "id": "<sandbox-hyperdrive-id>" }]
|
||||
},
|
||||
"production": {
|
||||
"name": "nestri-auth",
|
||||
"workers_dev": false,
|
||||
"routes": [{ "pattern": "auth.nestri.io", "custom_domain": true }],
|
||||
"observability": { "enabled": true },
|
||||
"hyperdrive": [{ "binding": "HYPERDRIVE", "id": "<production-hyperdrive-id>" }]
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user