@zukhruf/nx 0.8.34 → 0.8.36

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 CHANGED
@@ -946,8 +946,8 @@ type InitOptions = Record<string, never>;
946
946
  | `.gitignore` | `gitignore` in [`files.ts`](./src/generators/init/files.ts) | add lines | replaces the file of `nx new` |
947
947
  | `.prettierrc` | single quotes, the sort-imports plugin, `importOrder` with `./env` and `./startup` first and `^@<scope>/(.*)$`, and no Tailwind plugin | create | — |
948
948
  | `.prettierignore` | `prettierignore` in [`files.ts`](./src/generators/init/files.ts) | add lines | — |
949
- | `eslint.config.mjs` | `flat/base`, `flat/typescript` and `flat/javascript` of `@nx/eslint-plugin`; the build-output `ignores`; `@nx/enforce-module-boundaries`; the `base`, `tests`, `diagnostics`, `env` and `nx-project-json` configs of `@zukhruf/eslint`; `manifest.configs.recommended`; Modern Node for the config files and `.husky/*.ts`; `allowDefaultProject` for `*.config.ts` and `.husky/*.ts` | create | — |
950
- | `.husky/pre-commit.ts`, `pre-push.ts`, `commit-msg.ts` | `Sync`, `Format`, `NoNumericPins`, `NpmrcPolicy`, `LockfileSync`, `DockerfileInstallsFromLockfile` and `DependencyChecks` on pre-commit, `Build` with `NODE_ENV=production` on pre-push, `NxReleaseScope` on commit-msg; mode `755` | create | — |
949
+ | `eslint.config.mjs` | `flat/base`, `flat/typescript` and `flat/javascript` of `@nx/eslint-plugin`; the build-output `ignores`; `@nx/enforce-module-boundaries`; the `base`, `tests`, `diagnostics`, `env`, `nx-project-json` and `github-actions` configs of `@zukhruf/eslint`; `manifest.configs.recommended`; Modern Node for the config files and `.husky/*.ts`; `allowDefaultProject` for `*.config.ts` and `.husky/*.ts` | create | — |
950
+ | `.husky/pre-commit.ts`, `pre-push.ts`, `commit-msg.ts` | `Sync`, `Format`, `NoNumericPins`, `NpmrcPolicy`, `LockfileSync`, `OneRuntimeCopy`, `InstallScriptsReviewed`, `DockerfileInstallsFromLockfile`, `DependencyChecks` and `WorkflowChecks` on pre-commit, `Build` with `NODE_ENV=production` on pre-push, `NxReleaseScope` on commit-msg; mode `755` | create | — |
951
951
  | `.husky/pre-commit`, `pre-push`, `commit-msg` | a link to the `.ts` file of the same name | create | — |
952
952
  | `.vscode/settings.json` | file nesting, watcher and search excludes for `node_modules`, `.nx`, `tmp` | create | — |
953
953
  | `.vscode/extensions.json` | `nrwl.angular-console`, `esbenp.prettier-vscode`, `dbaeumer.vscode-eslint` | create | replaces the file of `nx new` |
@@ -1240,9 +1240,150 @@ After the steps of [Test the preset before a release](#test-the-preset-before-a-
1240
1240
 
1241
1241
  The decisions are in [ADR 0012](./docs/adr/0012-the-prisma-generator-writes-a-postgres-db-package-and-wires-a-backend.md). The backlog item is #4604.
1242
1242
 
1243
+ ## auth generator
1244
+
1245
+ `auth` adds better-auth 1.7.26 to a node-app and to the db package that the prisma generator wired into it. meddit needs sign-in, and text2sql, thing and blackboard each set better-auth up by hand (#4719).
1246
+
1247
+ ### Add sign-in to a backend
1248
+
1249
+ ```sh
1250
+ npx nx g @zukhruf/nx:auth --backend apps/backend --db packages/db
1251
+ ```
1252
+
1253
+ After the install, the generator runs `nx run @acme/backend:auth:generate`, which writes the models of better-auth into `packages/db/models/auth.prisma`. Then write the first migration (see [Migrations](#migrations)) and run `npx nx run @acme/backend:auth:check`.
1254
+
1255
+ ### Add sign-in to a paired web app
1256
+
1257
+ ```sh
1258
+ npx nx g @zukhruf/nx:auth --backend apps/backend --db packages/db --web apps/web
1259
+ ```
1260
+
1261
+ Pair the web with the backend first. `apps/web/src/auth-client.ts` then exports `authClient`, which calls `/api/auth` on the page origin: the Vite proxy in development, the backend in production. The backend trusts the two origins that the browser sends in development: `http://localhost:5173` (`nx run @acme/web:dev`) and `https://web.acme.localhost` (`nx run @acme/web:portless`). If your portless proxy uses another TLD or a prefix, add that origin to `ALLOWED_ORIGINS` in `apps/backend/.env`; better-auth answers any other origin with 403 `INVALID_ORIGIN`.
1262
+
1263
+ In development, better-auth builds its links (email verification, password reset) on the host of the page that asked for them when that host is in `ALLOWED_ORIGINS`, so a link opened from the Vite dev server or from portless signs in that same page. A request from any other host, and production, get `BETTER_AUTH_URL`.
1264
+
1265
+ ### Require a session
1266
+
1267
+ The generator protects no route; your route modules and router choose. On the backend, list `signedIn` from `src/session.ts`. A request without a session gets 401 (`UnauthenticatedError` of [`@zukhruf/authentication`](../authentication/README.md)), and the route reads the session on `c.var.session`:
1268
+
1269
+ ```ts
1270
+ // apps/backend/src/routes/me.route.ts, added to the route list of app.ts
1271
+ import type { Hono } from 'hono';
1272
+
1273
+ import { signedIn } from '../session.ts';
1274
+
1275
+ export default function (app: Hono): void {
1276
+ app.get('/me', signedIn, (c) => c.json(c.var.session.user));
1277
+ }
1278
+ ```
1279
+
1280
+ `signedIn` loads `startup.ts` on the first request, so `app.test.ts` still runs without a database. In the web, give each page behind sign-in the loader from `src/session.ts`, with the path of your sign-in page:
1281
+
1282
+ ```ts
1283
+ // apps/web/src/main.tsx
1284
+ import { signedInLoader } from './session.ts';
1285
+
1286
+ const router = createBrowserRouter([
1287
+ {
1288
+ path: '/cases',
1289
+ loader: signedInLoader({ signIn: '/sign-in' }),
1290
+ Component: Cases,
1291
+ },
1292
+ ]);
1293
+ ```
1294
+
1295
+ A visitor without a session lands on `/sign-in?redirectTo=%2Fcases`. After you add better-auth's two-factor plugin, pass `{ twoFactor: true }` to `requireSession` in the backend's `src/session.ts`, and `twoFactorSetup` to `signedInLoader`; both are type errors before the plugin is there.
1296
+
1297
+ ### Signature of the auth generator
1298
+
1299
+ ```ts
1300
+ // @zukhruf/nx:auth
1301
+ interface AuthOptions {
1302
+ backend: string; // the project root of a node-app, for example apps/backend
1303
+ db: string; // the project root of a db package, for example packages/db
1304
+ web?: string; // the project root of a react-app, for example apps/web
1305
+ }
1306
+ ```
1307
+
1308
+ ### What the auth generator writes
1309
+
1310
+ | File | Content |
1311
+ | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1312
+ | `<backend>/src/auth.ts` | `createAuth({ prisma, secret, baseURL, trustedOrigins })`: better-auth on `prismaAdapter` with `emailAndPassword`; `baseURL` is a URL or `{ fallback, allowedHosts }`; it reads no environment; only when missing |
1313
+ | `<backend>/src/session.ts` | `export const signedIn = requireSession(sessions)` from `@zukhruf/authentication/hono`; `sessions` loads `startup.ts` on the first request and has the type of the app's session; only when missing |
1314
+ | `<backend>/src/auth.cli.ts` | `export const auth` for the better-auth CLI, on `createPrisma` with no connection and placeholder secret and URL; it imports no `env.ts` and no `startup.ts`; only when missing |
1315
+ | `<backend>/src/routes/auth.route.ts` | `GET` and `POST` `/api/auth/*` to `auth.handler`; the handler loads `startup.ts` on the first request, so `app.test.ts` needs no database; only when missing |
1316
+ | `<backend>/src/app.ts` | the mount of the auth route, before the UI mount of pair and before `notFound` |
1317
+ | `<backend>/src/startup.ts` | `export const auth = createAuth(...)` on the app's client, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL` and `ALLOWED_ORIGINS`; in development, `baseURL` is the host of an allowed origin, else `BETTER_AUTH_URL` |
1318
+ | `<backend>/src/env.ts` | `BETTER_AUTH_SECRET: z.string().min(32)` and `BETTER_AUTH_URL: z.url()` |
1319
+ | `<backend>/.env.example`, `.env` | `BETTER_AUTH_SECRET=` and `BETTER_AUTH_URL=http://localhost:<PORT>`; `.env` gets a random 43-character secret; a key that is there keeps its value |
1320
+ | `<backend>/package.json` | `better-auth` and `@zukhruf/authentication` in `dependencies`; the `auth:generate` and `auth:check` targets |
1321
+ | `<web>/src/auth-client.ts` | with `--web`: `export const authClient = createAuthClient()` from `better-auth/react`, with no `baseURL`; only when missing |
1322
+ | `<web>/src/session.ts` | with `--web`: `signedInLoader(options)`, a loader that calls `requireSession(authClient, request, options)` of `@zukhruf/authentication/react-router`; only when missing |
1323
+ | `<web>/package.json` | with `--web`: `better-auth` and `@zukhruf/authentication` in `dependencies`; a `react-router` below 8.5.2 becomes 8.5.2, the peer range of `@zukhruf/authentication` |
1324
+ | `<backend>/.env.example`, `.env` | with `--web`: `http://localhost:5173` and `https://<portless name>.localhost` added to `ALLOWED_ORIGINS`, after the origins that are there |
1325
+ | `<db>/models/auth.prisma` | a one-line placeholder, which the CLI fills; without it the CLI writes a second generator and datasource, and `prisma generate` fails with P1012; only when missing |
1326
+ | `infra/src/environments/production/main.tf` | when the dokploy generator wrote the infra: `BETTER_AUTH_SECRET = random_password.better_auth.result` and `BETTER_AUTH_URL = "https://${local.host}"` above the marker of the `env` map of `module "stack"`; only when `BETTER_AUTH_SECRET` is not there |
1327
+ | `infra/src/environments/production/auth.tf` | when the dokploy generator wrote the infra: `random_password.better_auth`, 64 characters, no special characters, with `prevent_destroy`, because a new secret signs every user out; only when missing |
1328
+
1329
+ At the root: the CLI `auth` in `devDependencies`. The generator writes no migration. A second run adds nothing twice. A repo without `module "stack"` in `infra/src/environments/production/main.tf` gets no file in `infra/`.
1330
+
1331
+ ### What the auth targets run
1332
+
1333
+ Both run in the backend root with `NODE_OPTIONS=--conditions=development`, so jiti loads the source of the db package, and with `NODE_ENV=development`, because the CLI refuses the placeholder secret in production, and both depend on `^generate`, because that source imports the generated client.
1334
+
1335
+ - `auth:generate`: `npx auth generate --adapter prisma --config src/auth.cli.ts --output <db>/models/auth.prisma --yes`, then `nx run <db>:generate`. Run it after you add a plugin to `createAuth`.
1336
+ - `auth:check`: `npx auth check schema --config src/auth.cli.ts`. It only reads. It exits 1 when the generated client misses a table or column of the plugins, and 2 when it cannot load the config.
1337
+
1338
+ ### Versions that the auth generator writes
1339
+
1340
+ `better-auth` and `auth` have one exact version, 1.7.26, in `appPackageVersions`, and a test checks that they are equal. `@zukhruf/authentication` gets the version of this package, as every zukhruf package has the same version.
1341
+
1342
+ ### Errors of the auth generator
1343
+
1344
+ | Error | When |
1345
+ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
1346
+ | `apps/api has no sdk-it.config.ts, so it is not a node-app. Run …` | `--backend` names a project that `node-app` did not write |
1347
+ | `packages/db has no prisma.config.ts and createPrisma, so it is not a db package. Run …` | `--db` names a project that `prisma` did not write |
1348
+ | `apps/backend/src/startup.ts does not create the client of @acme/db. Run @zukhruf/nx:prisma …` | the prisma generator did not wire the db into this backend |
1349
+ | `apps/web has no vite.config.ts, so it is not a react-app. Run …` | `--web` names a project that `react-app` did not write |
1350
+ | `infra/src/environments/production/main.tf calls module "stack" but its env has no "# Generators add env keys above this line.", so the generator cannot add BETTER_AUTH_SECRET = … and BETTER_AUTH_URL = …. Add the two lines to env, or put the marker back as the last line of env.` | the repo removed the marker from the `env` map of the module call, and the two keys are not there |
1351
+
1352
+ ### Test the auth generator before a release
1353
+
1354
+ After the steps of [Test the prisma generator before a release](#test-the-prisma-generator-before-a-release) up to `run-many`: run `auth --backend apps/backend --db packages/db`, then check that `auth:check` exits 0, that `run-many -t typecheck lint build test` passes, and that a second run changes no file. On 2026-11-19 each step passed. The production bundle on a `postgres:18-alpine`, with the schema from `prisma migrate diff`, answered `POST /api/auth/sign-up/email` with 200.
1355
+
1356
+ For `--web`, also run `react-app apps/web` and `pair` before prisma, and `auth` with `--web apps/web`. Start `serve` of the backend and `dev` of the web, then send `POST http://localhost:5173/api/auth/sign-up/email` with `Origin: http://localhost:5173`: it answers 200, and with another origin 403. Repeat on `https://web.acme.localhost` under the `portless` target. On 2026-11-19 each step passed, and `authClient.signUp.email` in Chromium answered 200.
1357
+
1358
+ For the guards, add a route that lists `signedIn`: `GET` it without a cookie (401), then after sign-in (200). Until `@zukhruf/authentication` is on npm, install it from a tarball with an `overrides` entry (`file:<tgz>`), not with `npm link`: a link brings a second `hono`, and the app answers the refusal with 500. On 2026-11-19 both answers were right, through the Vite dev server, and a verification link opened through the Vite dev server and through portless signed in the page on that origin.
1359
+
1360
+ The decisions are in [ADR 0014](./docs/adr/0014-the-auth-generator-adds-better-auth-to-a-backend-and-its-db-package.md). The backlog item is #4719.
1361
+
1243
1362
  ## dokploy generator
1244
1363
 
1245
- `dokploy` writes the GitOps delivery of a node-app on Dokploy: an OpenTofu project in `infra/` that stores the compose in Dokploy, and the workflows that build the images, apply the stack and roll it out. text2sql (v2, authx) and whatisgoingon hold copies, and meddit is the third repo, so the shape moves here (#4603). The workflows call zukhruf's kit at `@main`: the reusable `tofu-apply.yml`, and the `dokploy-deploy` and `wait-for-health` actions.
1364
+ `dokploy` writes the GitOps delivery of a node-app on Dokploy: an OpenTofu project in `infra/` whose `main.tf` calls zukhruf's [`dokploy-stack` module](./opentofu/dokploy-stack/README.md) to store the compose in Dokploy, and the workflows that build the images, apply the stack and roll it out. text2sql (v2, authx) and whatisgoingon hold copies, and meddit is the third repo, so the shape moves here (#4603). The workflows call zukhruf's kit at `@main`: the reusable `tofu-apply.yml`, and the `dokploy-deploy` and `wait-for-health` actions. The module call follows `main` too.
1365
+
1366
+ The generator writes each file only when it is missing, and never deletes one: after the first run, every file is the repo's (ADR 0015). A rerun adds the lines of `.prettierignore`, `.nxignore` and the `nx.json` plugin entry that are missing, and changes nothing else.
1367
+
1368
+ ```hcl
1369
+ module "stack" {
1370
+ source = "git::https://github.com/JanuaryLabs/zukhruf.git//packages/nx/opentofu/dokploy-stack?ref=main"
1371
+
1372
+ name = "acme"
1373
+ description = "acme at acme.<server ipv4>.sslip.io - managed by OpenTofu"
1374
+ app = "backend"
1375
+ compose_file = file("${path.module}/../../../compose.dokploy.yml")
1376
+ database = { role = "acme" }
1377
+ registry = { username = "octocat", password = var.ghcr_pull_token }
1378
+
1379
+ env = {
1380
+ PUBLIC_HOST = local.host
1381
+ # Generators add env keys above this line.
1382
+ }
1383
+ }
1384
+ ```
1385
+
1386
+ A key that the app needs goes into `env`; the app reads it through `env_file: .env`. A secret is a sensitive variable in `variables.tf`, fed by `TF_ENV` in `deploy.yml` and by `infra/.env` for a local preview.
1246
1387
 
1247
1388
  ### Deliver a backend
1248
1389
 
@@ -1279,19 +1420,19 @@ interface DokployOptions {
1279
1420
 
1280
1421
  ### What the dokploy generator writes
1281
1422
 
1282
- | File | What it holds |
1283
- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1284
- | `infra/project.json` | `@<scope>/infra`; `@zukhruf/nx/opentofu` gives its targets, and the generator lists that plugin after `@zukhruf/nx/format` in `nx.json` |
1285
- | `infra/compose.dokploy.yml` | the app image on `dokploy-network` with the Traefik labels (`web` redirects, `websecure` with Let's Encrypt); with `database`, `postgres:18-alpine` and the one-shot `migrate`, which the app waits for |
1286
- | `infra/.env.example`, `infra/.gitignore` | the secrets of a local run, `TF_VAR_dokploy_api_key=${DOKPLOY_API_KEY}` (and `TF_VAR_ghcr_pull_token`); the plaintext backups, `.terraform/` and `tfplan` |
1287
- | `src/environments/production/*.tf` | `versions`, `backend` (local, the encrypted state committed), `encryption` (pbkdf2 and aes_gcm, enforced), `providers`, `dns`, `main`, `outputs` (`dokploy_api`, `compose_id`, `host`), `variables`, `registry` |
1288
- | `.terraform.lock.hcl` | the providers for `linux_amd64` and `darwin_arm64`, so `typecheck` (`-lockfile=readonly`) passes on CI and a Mac |
1289
- | `.prettierignore`, `.nxignore` | lines added when missing: `.terraform`, `tfplan` and the state for Prettier; the state for Nx, so the state commit of an apply makes no project affected |
1290
- | `.github/workflows/deploy.yml` | only when missing: gate (`tested-commit`, `affected-range` since the last deploy, `affected-projects`), image (`ghcr-image`, a matrix: the app and `migrate`), promote to `:latest` (`ghcr-promote`), infra (`tofu-apply.yml`), release (`dokploy-deploy`, `wait-for-health`) |
1291
- | `.github/workflows/ci.yml` | only when missing: setup-workspace, OpenTofu in the background, `affected-range`, then `nx affected -t lint typecheck test build` beside `sync:check`, `prettier --check` and zizmor |
1292
- | `.github/zizmor.yml` | only when missing: tags and `@main` allowed (`ref-pin`), and the `workflow_run` of `deploy.yml` |
1423
+ | File | What it holds |
1424
+ | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1425
+ | `infra/project.json` | `@<scope>/infra`; `@zukhruf/nx/opentofu` gives its targets, and the generator lists that plugin after `@zukhruf/nx/format` in `nx.json` |
1426
+ | `infra/compose.dokploy.yml` | the app image with `env_file: .env` on `dokploy-network` with the Traefik labels (`web` redirects, `websecure` with Let's Encrypt); with `database`, `postgres:18-alpine` and the one-shot `migrate`, which the app waits for |
1427
+ | `infra/.env.example`, `infra/.gitignore` | the secrets of a local run, `TF_VAR_dokploy_api_key=${DOKPLOY_API_KEY}` (and `TF_VAR_ghcr_pull_token`); the plaintext backups, `.terraform/` and `tfplan` |
1428
+ | `src/environments/production/*.tf` | `versions`, `backend` (local, the encrypted state committed), `encryption` (pbkdf2 and aes_gcm, enforced), `providers`, `dns`, `main` (the module call; `registry` is its input), `outputs` (`dokploy_api`, `compose_id`, `host`), `variables` |
1429
+ | `.terraform.lock.hcl` | the providers for `linux_amd64` and `darwin_arm64`, `hashicorp/random` always, because the module requires it, so `typecheck` (`-lockfile=readonly`) passes on CI and a Mac |
1430
+ | `.prettierignore`, `.nxignore` | lines added when missing: `.terraform`, `tfplan` and the state for Prettier; the state for Nx, so the state commit of an apply makes no project affected |
1431
+ | `.github/workflows/deploy.yml` | gate (`tested-commit`, `affected-range` since the last deploy, `affected-projects`), image (`ghcr-image`, a matrix: the app and `migrate`), promote to `:latest` (`ghcr-promote`), infra (`tofu-apply.yml`), release (`dokploy-deploy`, `wait-for-health`) |
1432
+ | `.github/workflows/ci.yml` | setup-workspace, OpenTofu in the background, `affected-range`, then `nx affected -t lint typecheck test build` beside `sync:check`, `prettier --check` and zizmor |
1433
+ | `.github/zizmor.yml` | tags and `@main` allowed (`ref-pin`), and the `workflow_run` of `deploy.yml` |
1293
1434
 
1294
- The compose reads `PUBLIC_HOST`, and with `database` `POSTGRES_PASSWORD` and `CONNECTION_STRING`, from the env that `main.tf` stores with it. Postgres 18 keeps its data under `/var/lib/postgresql/18/docker`, so the volume is mounted at `/var/lib/postgresql`. Each variable refuses an empty value, because CI renders an unset secret as `""`. The stack has no `terraform_data` deployment: the release job deploys after a new image, after an apply that changed the stack, and while the infra project is affected since the last successful deploy, and it checks the build sha only after a new image. `.prettierignore` gets `.terraform`, `tfplan` and the state.
1435
+ The compose reads `PUBLIC_HOST` in its labels, Postgres reads `POSTGRES_PASSWORD` and `migrate` reads `CONNECTION_STRING`, from the env that the module stores with it; a plan refuses a `${NAME}` that the env does not have. Postgres 18 keeps its data under `/var/lib/postgresql/18/docker`, so the volume is mounted at `/var/lib/postgresql`. Each variable refuses an empty value, because CI renders an unset secret as `""`. The stack has no `terraform_data` deployment: the release job deploys after a new image, after an apply that changed the stack, and while the infra project is affected since the last successful deploy, and it checks the build sha only after a new image. `.prettierignore` gets `.terraform`, `tfplan` and the state.
1295
1436
 
1296
1437
  ### Errors of the dokploy generator
1297
1438
 
@@ -1305,6 +1446,6 @@ The compose reads `PUBLIC_HOST`, and with `database` `POSTGRES_PASSWORD` and `CO
1305
1446
 
1306
1447
  ### Test the dokploy generator before a release
1307
1448
 
1308
- After the steps of [Test the app generators before a release](#test-the-app-generators-before-a-release), run `prisma` and then `dokploy` with `--database`, `--registryUser` and no `--host`, then `npm install`, `npx nx sync`, `npx nx run @acme/infra:typecheck`, `actionlint .github/workflows/*.yml`, `npx nx run-many -t typecheck lint`, `npx prettier --check .`, and `docker compose -f infra/compose.dokploy.yml config`. actionlint 1.7.12 does not know the `parallel:` step of `ci.yml`, which GitHub runs. On 2026-11-18 each passed, also after a run with `--host` and no `--database` or `--registryUser`; after that, two runs with the first options passed again, and the second of them changed no file.
1449
+ After the steps of [Test the app generators before a release](#test-the-app-generators-before-a-release), run `prisma` and then `dokploy` with `--database`, `--registryUser` and no `--host`, then `npm install`, `npx nx sync`, `npx nx run @acme/infra:typecheck`, `actionlint .github/workflows/*.yml`, `npx nx run-many -t typecheck lint`, `npx prettier --check .`, and `docker compose -f infra/compose.dokploy.yml config` (with an `infra/.env`, which the app's `env_file` names). actionlint 1.7.12 does not know the `parallel:` step of `ci.yml`, which GitHub runs. On 2026-11-18 each passed, also after a run with `--host` and no `--database` or `--registryUser`; after that, two runs with the first options passed again, and the second of them changed no file.
1309
1450
 
1310
- The decisions are in [ADR 0011](./docs/adr/0011-the-dokploy-generator-writes-the-gitops-delivery-of-a-node-app.md). The backlog item of the dokploy generator is #4603.
1451
+ The decisions are in [ADR 0011](./docs/adr/0011-the-dokploy-generator-writes-the-gitops-delivery-of-a-node-app.md) and [ADR 0015](./docs/adr/0015-an-opentofu-module-of-zukhruf-holds-the-dokploy-delivery-and-the-dokploy-generator-writes-infra-once.md). The backlog items of the dokploy generator are #4603 and #4733.
@@ -0,0 +1,47 @@
1
+ /** The factory of the backend's auth. It reads no environment, so the app and the CLI config build the same auth. */
2
+ export declare function authTs(dbPackageName: string): string;
3
+ /** The module that the better-auth CLI loads, with c12 and jiti. */
4
+ export declare function authCliTs(dbPackageName: string): string;
5
+ export declare const authRouteTs = "import type { Hono } from 'hono';\n\n// better-auth answers each request under /api/auth. The handler loads\n// startup.ts at the first request, not at import: server.ts has loaded it\n// already, and a test that imports app.ts needs no database and no auth\n// environment.\nexport default function (app: Hono): void {\n app.on(['POST', 'GET'], '/api/auth/*', async (c) => {\n const { auth } = await import('../startup.ts');\n return auth.handler(c.req.raw);\n });\n}\n";
6
+ /** The line of app.ts that mounts the auth routes. */
7
+ export declare const authMount = "(await import('./routes/auth.route.ts')).default(app);";
8
+ /** The lines of env.ts that declare the environment of better-auth. */
9
+ export declare const authEnvTs = " // better-auth signs the session cookies with the secret, and builds its\n // links on the URL of this server.\n BETTER_AUTH_SECRET: z.string().min(32),\n BETTER_AUTH_URL: z.url(),\n";
10
+ /** The lines that startup.ts gets: the auth, on the app's client and validated environment. */
11
+ export declare const startupAuthTs = "\n// The auth of the app, on the client above. src/routes/auth.route.ts serves it.\nconst allowedOrigins = process.env.ALLOWED_ORIGINS.split(',')\n .map((origin) => origin.trim())\n .filter((origin) => origin !== '');\nexport const auth = createAuth({\n prisma,\n secret: process.env.BETTER_AUTH_SECRET,\n // In development, a link of better-auth (email verification, password\n // reset) opens on the host of the page that asked for it, when that is the\n // host of an allowed origin: the Vite dev server and portless proxy /api to\n // this server, so the cookie that the link sets reaches the page. Any other\n // host, and production, get BETTER_AUTH_URL.\n baseURL:\n process.env.NODE_ENV === 'development'\n ? {\n fallback: process.env.BETTER_AUTH_URL,\n allowedHosts: allowedOrigins.map((origin) => new URL(origin).host),\n }\n : process.env.BETTER_AUTH_URL,\n trustedOrigins: allowedOrigins,\n});\n";
12
+ /**
13
+ * The placeholder of the models of better-auth. The CLI writes its own
14
+ * generator and datasource blocks into a missing file, and prisma generate
15
+ * then fails with P1012, so the file is there before the CLI runs.
16
+ */
17
+ export declare const authPrisma = "// The models of better-auth. The auth:generate target of the backend writes them.\n";
18
+ /**
19
+ * The better-auth client of the web app. It has no baseURL: a paired web app
20
+ * reaches the API on its own origin, through the Vite proxy of `/api` in
21
+ * development, so the client's default, the page origin plus `/api/auth`, is
22
+ * the backend's auth.
23
+ */
24
+ export declare const authClientTs = "import { createAuthClient } from 'better-auth/react';\n\n// better-auth in the browser. It calls /api/auth on the page origin: the Vite\n// dev server proxies /api to the backend, and in production the backend serves\n// this app from its own origin (pair).\nexport const authClient = createAuthClient();\n";
25
+ /**
26
+ * The middleware that a route module of the backend lists to require a
27
+ * session. Its session source loads startup.ts on the first request, as
28
+ * auth.route.ts does, so app.test.ts still needs no database, and it takes its
29
+ * type from the app's auth, so `c.var.session.user` has the app's own fields.
30
+ */
31
+ export declare const backendSessionTs = "import { requireSession } from '@zukhruf/authentication/hono';\n\nimport type { auth } from './startup.ts';\n\n// The session source of requireSession. It loads startup.ts on the first\n// request, not at import, as routes/auth.route.ts does: a test that imports\n// app.ts needs no database and no auth environment.\nconst sessions = {\n api: {\n async getSession(context: {\n headers: Headers;\n }): Promise<typeof auth.$Infer.Session | null> {\n const startup = await import('./startup.ts');\n return startup.auth.api.getSession(context);\n },\n },\n};\n\n/**\n * Refuses a request without a session with 401. A route that lists it reads\n * the session, with the app's own user fields, on c.var.session.\n */\nexport const signedIn = requireSession(sessions);\n";
32
+ /**
33
+ * The loader guard of the web app, on its better-auth client. The host's
34
+ * router passes the paths of its own pages; the generator writes no page.
35
+ */
36
+ export declare const webSessionTs = "import {\n type RequireSessionOptions,\n requireSession,\n} from '@zukhruf/authentication/react-router';\nimport type { LoaderFunctionArgs } from 'react-router';\n\nimport { authClient } from './auth-client.ts';\n\n/**\n * The loader of a page behind sign-in. A visitor without a session goes to\n * `signIn`, with the page as the return path. The loader data is the session.\n */\nexport function signedInLoader(\n options: RequireSessionOptions<typeof authClient.$Infer.Session>,\n) {\n return ({ request }: LoaderFunctionArgs) =>\n requireSession(authClient, request, options);\n}\n";
37
+ /** The comment that auth puts above ALLOWED_ORIGINS when it adds the origins of the web app. */
38
+ export declare const allowedOriginsComment = "# better-auth trusts these origins in every environment. In development they\n# are the origins of the web app: the Vite dev server and portless.\n";
39
+ /**
40
+ * The lines that the env map of module "stack" in the main.tf of the dokploy
41
+ * generator gets above its marker. The comment line keeps tofu fmt from
42
+ * aligning them with the host's own keys.
43
+ */
44
+ export declare const authStackEnv = "# better-auth signs the session cookies with the secret, and builds its links on the URL.\n BETTER_AUTH_SECRET = random_password.better_auth.result\n BETTER_AUTH_URL = \"https://${local.host}\"\n ";
45
+ /** The secret of better-auth in production, next to the main.tf of the dokploy generator. */
46
+ export declare const authTf = "# BETTER_AUTH_SECRET of the env of module \"stack\" in main.tf. better-auth signs\n# the session cookies and encrypts its stored data with it, so a new value signs\n# every user out and leaves that data unreadable (text2sql #398): the secret is\n# never replaced.\nresource \"random_password\" \"better_auth\" {\n length = 64\n special = false\n\n lifecycle {\n prevent_destroy = true\n }\n}\n";
47
+ //# sourceMappingURL=files.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../../../src/generators/auth/files.ts"],"names":[],"mappings":"AAGA,qHAAqH;AACrH,wBAAgB,MAAM,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAsCpD;AAED,oEAAoE;AACpE,wBAAgB,SAAS,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAoBvD;AAED,eAAO,MAAM,WAAW,meAYvB,CAAC;AAEF,sDAAsD;AACtD,eAAO,MAAM,SAAS,2DAA2D,CAAC;AAElF,uEAAuE;AACvE,eAAO,MAAM,SAAS,gMAIrB,CAAC;AAEF,+FAA+F;AAC/F,eAAO,MAAM,aAAa,i8BAsBzB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,UAAU,yFACtB,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,YAAY,uTAMxB,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,4xBAuB5B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,YAAY,qlBAkBxB,CAAC;AAEF,gGAAgG;AAChG,eAAO,MAAM,qBAAqB,wJAEjC,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,YAAY,qNAGpB,CAAC;AAEN,6FAA6F;AAC7F,eAAO,MAAM,MAAM,sZAYlB,CAAC"}
@@ -0,0 +1,210 @@
1
+ // The content of each file that auth writes. Each is a string in a .ts
2
+ // module, so tsc puts it in dist with no copy step (ADR 0009).
3
+ /** The factory of the backend's auth. It reads no environment, so the app and the CLI config build the same auth. */
4
+ export function authTs(dbPackageName) {
5
+ return `import { betterAuth } from 'better-auth';
6
+ import { prismaAdapter } from 'better-auth/adapters/prisma';
7
+
8
+ import type { PrismaClient } from '${dbPackageName}';
9
+
10
+ export interface AuthOptions {
11
+ prisma: PrismaClient;
12
+ /** Signs the session cookies; 32 characters or more. */
13
+ secret: string;
14
+ /**
15
+ * Where better-auth builds its links: the URL of this server, or, in
16
+ * development, the host of the request when it is one of \`allowedHosts\`.
17
+ */
18
+ baseURL: string | { fallback: string; allowedHosts: string[] };
19
+ /** The browser origins that may call the auth routes. */
20
+ trustedOrigins: string[];
21
+ }
22
+
23
+ /**
24
+ * The auth of the app. It reads no environment and imports no env.ts or
25
+ * startup.ts: startup.ts calls it with the app's client and validated
26
+ * environment, and auth.cli.ts calls it for the better-auth CLI, so both have
27
+ * the same plugins.
28
+ */
29
+ export function createAuth(options: AuthOptions) {
30
+ return betterAuth({
31
+ database: prismaAdapter(options.prisma, { provider: 'postgresql' }),
32
+ secret: options.secret,
33
+ baseURL: options.baseURL,
34
+ // A baseURL from the request takes the protocol of the page from
35
+ // x-forwarded-proto, which portless sends.
36
+ advanced: { trustedProxyHeaders: typeof options.baseURL !== 'string' },
37
+ trustedOrigins: options.trustedOrigins,
38
+ emailAndPassword: { enabled: true },
39
+ });
40
+ }
41
+ `;
42
+ }
43
+ /** The module that the better-auth CLI loads, with c12 and jiti. */
44
+ export function authCliTs(dbPackageName) {
45
+ return `import { createPrisma } from '${dbPackageName}';
46
+
47
+ import { createAuth } from './auth.ts';
48
+
49
+ // The config of the better-auth CLI (the auth:generate and auth:check
50
+ // targets). The CLI imports this module and each module it imports, so it must
51
+ // have no side effect: no env.ts, no startup.ts, no query. createPrisma opens
52
+ // no connection until a query, and the CLI reads only the plugins and the
53
+ // adapter, so the secret and the URL are placeholders. The export must be
54
+ // named auth.
55
+ export const auth = createAuth({
56
+ prisma: createPrisma({
57
+ connectionString: process.env.CONNECTION_STRING ?? '',
58
+ }),
59
+ secret: 'the-better-auth-cli-reads-no-secret-from-here',
60
+ baseURL: 'http://localhost',
61
+ trustedOrigins: [],
62
+ });
63
+ `;
64
+ }
65
+ export const authRouteTs = `import type { Hono } from 'hono';
66
+
67
+ // better-auth answers each request under /api/auth. The handler loads
68
+ // startup.ts at the first request, not at import: server.ts has loaded it
69
+ // already, and a test that imports app.ts needs no database and no auth
70
+ // environment.
71
+ export default function (app: Hono): void {
72
+ app.on(['POST', 'GET'], '/api/auth/*', async (c) => {
73
+ const { auth } = await import('../startup.ts');
74
+ return auth.handler(c.req.raw);
75
+ });
76
+ }
77
+ `;
78
+ /** The line of app.ts that mounts the auth routes. */
79
+ export const authMount = `(await import('./routes/auth.route.ts')).default(app);`;
80
+ /** The lines of env.ts that declare the environment of better-auth. */
81
+ export const authEnvTs = ` // better-auth signs the session cookies with the secret, and builds its
82
+ // links on the URL of this server.
83
+ BETTER_AUTH_SECRET: z.string().min(32),
84
+ BETTER_AUTH_URL: z.url(),
85
+ `;
86
+ /** The lines that startup.ts gets: the auth, on the app's client and validated environment. */
87
+ export const startupAuthTs = `
88
+ // The auth of the app, on the client above. src/routes/auth.route.ts serves it.
89
+ const allowedOrigins = process.env.ALLOWED_ORIGINS.split(',')
90
+ .map((origin) => origin.trim())
91
+ .filter((origin) => origin !== '');
92
+ export const auth = createAuth({
93
+ prisma,
94
+ secret: process.env.BETTER_AUTH_SECRET,
95
+ // In development, a link of better-auth (email verification, password
96
+ // reset) opens on the host of the page that asked for it, when that is the
97
+ // host of an allowed origin: the Vite dev server and portless proxy /api to
98
+ // this server, so the cookie that the link sets reaches the page. Any other
99
+ // host, and production, get BETTER_AUTH_URL.
100
+ baseURL:
101
+ process.env.NODE_ENV === 'development'
102
+ ? {
103
+ fallback: process.env.BETTER_AUTH_URL,
104
+ allowedHosts: allowedOrigins.map((origin) => new URL(origin).host),
105
+ }
106
+ : process.env.BETTER_AUTH_URL,
107
+ trustedOrigins: allowedOrigins,
108
+ });
109
+ `;
110
+ /**
111
+ * The placeholder of the models of better-auth. The CLI writes its own
112
+ * generator and datasource blocks into a missing file, and prisma generate
113
+ * then fails with P1012, so the file is there before the CLI runs.
114
+ */
115
+ export const authPrisma = `// The models of better-auth. The auth:generate target of the backend writes them.
116
+ `;
117
+ /**
118
+ * The better-auth client of the web app. It has no baseURL: a paired web app
119
+ * reaches the API on its own origin, through the Vite proxy of `/api` in
120
+ * development, so the client's default, the page origin plus `/api/auth`, is
121
+ * the backend's auth.
122
+ */
123
+ export const authClientTs = `import { createAuthClient } from 'better-auth/react';
124
+
125
+ // better-auth in the browser. It calls /api/auth on the page origin: the Vite
126
+ // dev server proxies /api to the backend, and in production the backend serves
127
+ // this app from its own origin (pair).
128
+ export const authClient = createAuthClient();
129
+ `;
130
+ /**
131
+ * The middleware that a route module of the backend lists to require a
132
+ * session. Its session source loads startup.ts on the first request, as
133
+ * auth.route.ts does, so app.test.ts still needs no database, and it takes its
134
+ * type from the app's auth, so `c.var.session.user` has the app's own fields.
135
+ */
136
+ export const backendSessionTs = `import { requireSession } from '@zukhruf/authentication/hono';
137
+
138
+ import type { auth } from './startup.ts';
139
+
140
+ // The session source of requireSession. It loads startup.ts on the first
141
+ // request, not at import, as routes/auth.route.ts does: a test that imports
142
+ // app.ts needs no database and no auth environment.
143
+ const sessions = {
144
+ api: {
145
+ async getSession(context: {
146
+ headers: Headers;
147
+ }): Promise<typeof auth.$Infer.Session | null> {
148
+ const startup = await import('./startup.ts');
149
+ return startup.auth.api.getSession(context);
150
+ },
151
+ },
152
+ };
153
+
154
+ /**
155
+ * Refuses a request without a session with 401. A route that lists it reads
156
+ * the session, with the app's own user fields, on c.var.session.
157
+ */
158
+ export const signedIn = requireSession(sessions);
159
+ `;
160
+ /**
161
+ * The loader guard of the web app, on its better-auth client. The host's
162
+ * router passes the paths of its own pages; the generator writes no page.
163
+ */
164
+ export const webSessionTs = `import {
165
+ type RequireSessionOptions,
166
+ requireSession,
167
+ } from '@zukhruf/authentication/react-router';
168
+ import type { LoaderFunctionArgs } from 'react-router';
169
+
170
+ import { authClient } from './auth-client.ts';
171
+
172
+ /**
173
+ * The loader of a page behind sign-in. A visitor without a session goes to
174
+ * \`signIn\`, with the page as the return path. The loader data is the session.
175
+ */
176
+ export function signedInLoader(
177
+ options: RequireSessionOptions<typeof authClient.$Infer.Session>,
178
+ ) {
179
+ return ({ request }: LoaderFunctionArgs) =>
180
+ requireSession(authClient, request, options);
181
+ }
182
+ `;
183
+ /** The comment that auth puts above ALLOWED_ORIGINS when it adds the origins of the web app. */
184
+ export const allowedOriginsComment = `# better-auth trusts these origins in every environment. In development they
185
+ # are the origins of the web app: the Vite dev server and portless.
186
+ `;
187
+ /**
188
+ * The lines that the env map of module "stack" in the main.tf of the dokploy
189
+ * generator gets above its marker. The comment line keeps tofu fmt from
190
+ * aligning them with the host's own keys.
191
+ */
192
+ export const authStackEnv = `# better-auth signs the session cookies with the secret, and builds its links on the URL.
193
+ BETTER_AUTH_SECRET = random_password.better_auth.result
194
+ BETTER_AUTH_URL = "https://\${local.host}"
195
+ `;
196
+ /** The secret of better-auth in production, next to the main.tf of the dokploy generator. */
197
+ export const authTf = `# BETTER_AUTH_SECRET of the env of module "stack" in main.tf. better-auth signs
198
+ # the session cookies and encrypts its stored data with it, so a new value signs
199
+ # every user out and leaves that data unreadable (text2sql #398): the secret is
200
+ # never replaced.
201
+ resource "random_password" "better_auth" {
202
+ length = 64
203
+ special = false
204
+
205
+ lifecycle {
206
+ prevent_destroy = true
207
+ }
208
+ }
209
+ `;
210
+ //# sourceMappingURL=files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files.js","sourceRoot":"","sources":["../../../src/generators/auth/files.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,+DAA+D;AAE/D,qHAAqH;AACrH,MAAM,UAAU,MAAM,CAAC,aAAqB;IAC1C,OAAO;;;qCAG4B,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCjD,CAAC;AACF,CAAC;AAED,oEAAoE;AACpE,MAAM,UAAU,SAAS,CAAC,aAAqB;IAC7C,OAAO,iCAAiC,aAAa;;;;;;;;;;;;;;;;;;CAkBtD,CAAC;AACF,CAAC;AAED,MAAM,CAAC,MAAM,WAAW,GAAG;;;;;;;;;;;;CAY1B,CAAC;AAEF,sDAAsD;AACtD,MAAM,CAAC,MAAM,SAAS,GAAG,wDAAwD,CAAC;AAElF,uEAAuE;AACvE,MAAM,CAAC,MAAM,SAAS,GAAG;;;;CAIxB,CAAC;AAEF,+FAA+F;AAC/F,MAAM,CAAC,MAAM,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;CAsB5B,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG;CACzB,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;;;;;;CAM3B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG;;;;;;;;;;;;;;;;;;;;;;;CAuB/B,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;;;;;;;;;;;;;;;;;;CAkB3B,CAAC;AAEF,gGAAgG;AAChG,MAAM,CAAC,MAAM,qBAAqB,GAAG;;CAEpC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;;;KAGvB,CAAC;AAEN,6FAA6F;AAC7F,MAAM,CAAC,MAAM,MAAM,GAAG;;;;;;;;;;;;CAYrB,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { type GeneratorCallback, type Tree } from '@nx/devkit';
2
+ export interface AuthOptions {
3
+ /** The project root of a node-app that a db package is wired into, for example `apps/backend`. */
4
+ backend: string;
5
+ /** The project root of the db package of the prisma generator, for example `packages/db`. */
6
+ db: string;
7
+ /** The project root of a react-app that reaches this backend through `/api`, for example `apps/web`. */
8
+ web?: string;
9
+ }
10
+ /**
11
+ * better-auth on a node-app and the db package that it is wired to: the auth
12
+ * factory, the CLI config, the routes under /api/auth, the environment, the
13
+ * models of better-auth in the db package, and the auth:generate and
14
+ * auth:check targets. It runs `init` first. After the install, a task runs
15
+ * auth:generate, which writes the models. A second run keeps the files it
16
+ * wrote and adds nothing twice. It writes no migration (ADR 0012).
17
+ */
18
+ export default function authGenerator(tree: Tree, options: AuthOptions): Promise<GeneratorCallback>;
19
+ //# sourceMappingURL=generator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../../src/generators/auth/generator.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,IAAI,EAMV,MAAM,YAAY,CAAC;AA2BpB,MAAM,WAAW,WAAW;IAC1B,kGAAkG;IAClG,OAAO,EAAE,MAAM,CAAC;IAChB,6FAA6F;IAC7F,EAAE,EAAE,MAAM,CAAC;IACX,wGAAwG;IACxG,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAcD;;;;;;;GAOG;AACH,wBAA8B,aAAa,CACzC,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,WAAW,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAuF5B"}