@axiumine/qpanel-db-setup 0.0.0-stage → 0.9.0-rc.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/LICENSE +661 -0
  3. package/README.md +289 -2
  4. package/dist/migrations/20261127000000-create-enums-and-set-updated-at.mjs +25 -0
  5. package/dist/migrations/20261127000100-revoke-app-access-to-migration-tables.mjs +39 -0
  6. package/dist/migrations/20261127000200-create-admin.mjs +24 -0
  7. package/dist/migrations/20261127000300-create-secret.mjs +37 -0
  8. package/dist/migrations/20261127000400-create-audit-event.mjs +35 -0
  9. package/dist/migrations/20261127000500-create-registrar.mjs +27 -0
  10. package/dist/migrations/20261127000600-create-client.mjs +47 -0
  11. package/dist/migrations/20261127000700-create-client-note.mjs +22 -0
  12. package/dist/migrations/20261127000800-create-domain.mjs +37 -0
  13. package/dist/migrations/20261127000900-create-subdomain.mjs +24 -0
  14. package/dist/migrations/20261127001000-create-service.mjs +25 -0
  15. package/dist/migrations/20261127001100-create-datacenter.mjs +22 -0
  16. package/dist/migrations/20261127001200-create-db-instance.mjs +30 -0
  17. package/dist/migrations/20261127001300-create-db-instance-node.mjs +30 -0
  18. package/dist/migrations/20261127001400-create-db-account.mjs +34 -0
  19. package/dist/migrations/20261127001500-create-app-database.mjs +23 -0
  20. package/dist/migrations/20261127001600-create-app-database-user.mjs +31 -0
  21. package/dist/migrations/20261127001700-create-subdomain-app-database.mjs +25 -0
  22. package/dist/migrations/20261127001800-billing-fields.mjs +52 -0
  23. package/dist/migrations/20261128000000-secret-value-changed-at.mjs +25 -0
  24. package/dist/migrations/20261130000000-db-instance-environments.mjs +56 -0
  25. package/dist/migrations/20261130120000-create-server.mjs +50 -0
  26. package/dist/migrations/20261130200000-create-server-ssh-access.mjs +147 -0
  27. package/dist/migrations/20261201000000-ssh-login-per-way.mjs +129 -0
  28. package/dist/src/arguments.mjs +124 -0
  29. package/dist/src/bin.mjs +26 -0
  30. package/dist/src/cli.mjs +139 -0
  31. package/dist/src/create.mjs +40 -0
  32. package/dist/src/database.mjs +41 -0
  33. package/dist/src/env.mjs +49 -0
  34. package/dist/src/infisical.mjs +37 -0
  35. package/dist/src/keygrip.mjs +48 -0
  36. package/dist/src/masterKey.mjs +80 -0
  37. package/dist/src/masterKeyFile.mjs +66 -0
  38. package/dist/src/migrator.mjs +64 -0
  39. package/dist/src/redis.mjs +23 -0
  40. package/dist/src/secrets.mjs +96 -0
  41. package/dist/src/target.mjs +22 -0
  42. package/package.json +83 -4
  43. package/redis/bootstrap-acl.sh +130 -0
  44. package/sql/bootstrap.sql +218 -0
package/README.md CHANGED
@@ -1,3 +1,290 @@
1
- # Temporary Holding Version
1
+ # qpanel-db-setup
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/Axiumine/qpanel-db-setup/badge)](https://scorecard.dev/viewer/?uri=github.com/Axiumine/qpanel-db-setup)
4
+
5
+ qPanel's PostgreSQL schema and the runner that applies it, plus the commands that mint and rotate the master key and seed the
6
+ cookie-signing key set. Published as the public npm package `@axiumine/qpanel-db-setup` (ADR-022, ADR-048), so that a
7
+ service's CI can build the real schema: see [Use from a service's CI](#use-from-a-services-ci). Three things live here:
8
+
9
+ - **`sql/bootstrap.sql`** and **`redis/bootstrap-acl.sh`**: the one-time setup of an environment's database, roles and Redis ACL
10
+ user, run by a superuser. Guides: [`docs/postgres.md`](./docs/postgres.md), [`docs/redis.md`](./docs/redis.md).
11
+ - **`migrations/`** and **`src/`**: the tables, and the [Kysely](https://kysely.dev) migrator that creates them, run by the
12
+ environment's `qpanel_<env>_migrator` role.
13
+ - **`master-key` and `keygrip` commands** (`src/masterKey*.mts`, `src/secrets.mts`, `src/keygrip.mts`): the key ceremonies of an
14
+ environment, built on the published `@axiumine/qpanel-common`. See [Master key and Keygrip](#master-key-and-keygrip).
15
+
16
+ Not a service and not a library: nothing listens on a port and no code imports this package. It is a tool, installed for its bin
17
+ (`qpanel-db-setup`) and for the files it carries. Read the workspace [`../../CLAUDE.md`](../../CLAUDE.md) first, then
18
+ [`CLAUDE.md`](./CLAUDE.md) here, and [`docs/traps.md`](./docs/traps.md) for the traps of this repo, by task.
19
+
20
+ ## Run the migrations
21
+
22
+ Needs Node 26.13.1, Yarn 4 (`corepack enable`), the environment's database and roles from `sql/bootstrap.sql`, and
23
+ **PostgreSQL 18** (the tables use the built-in `uuidv7()`).
24
+
25
+ ```bash
26
+ yarn install
27
+ cp env.example .env # then fill in DATABASE_MIGRATOR_URL (never commit it)
28
+ yarn migrate:status # every migration, applied or pending; changes nothing
29
+ yarn migrate:up # apply every pending migration, all in one transaction
30
+ yarn migrate:down # revert the last applied migration
31
+ yarn migrate:create add-client-index # a new migration file, ready to fill in
32
+ ```
33
+
34
+ `--test` on `up`, `down` or `status` targets `qpanel_test` through `DATABASE_MIGRATOR_URL_TEST` instead. The installed package's bin spells
35
+ the same commands `qpanel-db-setup migrate up|down|status [--test]`, and a checkout takes that spelling too.
36
+
37
+ The runner connects only as a role named `*_migrator` and stops before doing anything otherwise. It never prints a connection
38
+ URL or a password. The bookkeeping tables are `qpanel.kysely_migration` and `qpanel.kysely_migration_lock`.
39
+
40
+ ### Infisical
41
+
42
+ With the five `INFISICAL_*` settings of the workspace's `env.shared.example`, the commands that read a variable
43
+ (`migrate`, `keygrip`, `master-key rewrap` and `retire`) first fill what is still unset from the self-hosted Infisical:
44
+ `DATABASE_MIGRATOR_URL`, `DATABASE_URL`, `KEYGRIP_KEK` and the `REDIS_*` names, from the folder `/shared`
45
+ (`INFISICAL_SECRET_PATHS` names others). What is already set wins, the command prints the names it took, and a load that
46
+ fails ends it before anything is touched. For `create`, `master-key mint` and `add-version` Infisical is never asked
47
+ (parent ADR-040).
48
+
49
+ With `--test` a command asks only when the one `*_TEST` URL it reads has no value, and for that URL alone, from the folders
50
+ `/shared` and `/qpanel-db-setup` (parent ADR-041). The gates do the same: what the tests need, and `QODANA_TOKEN`, may live
51
+ in those two folders instead of an env file. `.githooks/gate-env.mjs` fetches only the names that have no value, and prints
52
+ names only. Both folders must exist. CI has no `INFISICAL_*` setting and never asks.
53
+
54
+ ⚠️ The migrator's URL goes in a project of its own, never in one a service's identity can read: set that project's
55
+ settings, and `INFISICAL_SECRET_PATHS=/`, for the migrating run only.
56
+
57
+ ## Use from a service's CI
58
+
59
+ A service's integration tests need the `qpanel` schema in a throwaway PostgreSQL 18.7 container. The runners hold no GitHub
60
+ credential for another repo, and the package is public, so the service installs it without any npm token
61
+ instead of cloning this repo, and builds the same schema the repo's own CI and production build: `sql/bootstrap.sql`, then every
62
+ migration. No hand copy of a table.
63
+
64
+ 1. **A dev dependency** of the service: `"@axiumine/qpanel-db-setup": "^0.9.0"`. It pulls in
65
+ `@axiumine/qpanel-common`, which a service has anyway. A new migration reaches a service's CI only after a release of
66
+ this package and a range bump, like `qpanel-common`.
67
+ 2. **The job** has a PostgreSQL 18.7 `services:` container and throwaway passwords (the superuser's, the migrator's, the app's), then,
68
+ after `yarn install --immutable`:
69
+
70
+ ```yaml
71
+ - name: Bootstrap PostgreSQL (sql/bootstrap.sql -v env=test)
72
+ run: >-
73
+ docker exec -i ${{ job.services.postgres.id }}
74
+ psql -U postgres -v ON_ERROR_STOP=1 -v env=test
75
+ -v migrator_password="$CI_MIGRATOR_PASSWORD" -v app_password="$CI_APP_PASSWORD"
76
+ -f - < node_modules/@axiumine/qpanel-db-setup/sql/bootstrap.sql
77
+
78
+ - name: Point the service at the throwaway PostgreSQL
79
+ env:
80
+ PG_PORT: ${{ job.services.postgres.ports['5432'] }}
81
+ run: |
82
+ {
83
+ echo "DATABASE_MIGRATOR_URL_TEST=postgresql://qpanel_test_migrator:${CI_MIGRATOR_PASSWORD}@127.0.0.1:${PG_PORT}/qpanel_test?sslmode=disable"
84
+ echo "DATABASE_URL_TEST=postgresql://qpanel_test_app:${CI_APP_PASSWORD}@127.0.0.1:${PG_PORT}/qpanel_test?sslmode=disable"
85
+ } >> "$GITHUB_ENV"
86
+
87
+ - name: Apply the migrations
88
+ run: yarn qpanel-db-setup migrate up --test
89
+ ```
90
+
91
+ `bootstrap.sql` also creates the read-only role the dumps are made with, `qpanel_test_backup`. A service needs no password
92
+ for it: a run that passes `migrator_password` or `app_password` is never asked for `backup_password`, and without
93
+ `-v backup_password=…` the role has none and cannot log in with one. A job written before the role existed works unchanged.
94
+
95
+ `bootstrap.sql` runs as the container's superuser, the one place a superuser is used, and is idempotent (a second run creates
96
+ nothing). It goes through `docker exec` and `-f -` because the runner hosts may lack `psql`; with one, the same file is the
97
+ `-f node_modules/@axiumine/qpanel-db-setup/sql/bootstrap.sql` of a plain `psql -h 127.0.0.1 -p <port> -U postgres`.
98
+ The migrations run as `qpanel_test_migrator` through `DATABASE_MIGRATOR_URL_TEST`; the service and its tests use
99
+ `DATABASE_URL_TEST`, the app role, which has no DDL. `migrate status --test` lists what is applied.
100
+ 3. **Nothing else is needed**: the compiled migrations are inside the package and the bin finds them there, not under the
101
+ service's working directory. `redis/bootstrap-acl.sh` is in the package too (`node_modules/@axiumine/qpanel-db-setup/redis/`),
102
+ for a job that builds its Redis ACL user the same way.
103
+
104
+ The package ships compiled JavaScript (`dist/src`, `dist/migrations`) because Node refuses to strip types from a file under
105
+ `node_modules`; `yarn build` (`tsc -p tsconfig.build.json`) makes it and `prepack` runs it, so a tarball cannot go out without it.
106
+ `test/integration/package.test.mts` packs the real tarball, extracts it under a `node_modules` folder and runs the installed bin
107
+ against `qpanel_test`, as a service does.
108
+
109
+ ## Releasing
110
+
111
+ **Releases go by tag only** (parent ADR-027, as `qpanel-common`): bump `version`, update `CHANGELOG.md`, merge into `main`, push
112
+ `main`, then push the tag `v<version>`. `.github/workflows/release.yml` publishes it:
113
+
114
+ 1. **gates**: `gates.yml`, called as a workflow, on the self-hosted runners;
115
+ 2. **pack**, self-hosted: refuses a tag that is not `v<version of package.json>` or a commit that is not on `main`, builds the
116
+ tarball, records its SHA-256 and uploads it as an artifact kept for one day;
117
+ 3. **publish**, on `ubuntu-24.04`, the only GitHub-hosted job: checks the SHA-256 and runs `npm publish` on the tarball with npm
118
+ trusted publishing (OIDC). It checks out nothing, installs nothing and holds no token.
119
+
120
+ The package's trusted publisher on npmjs.org names this repository and the file `release.yml` (set once by the owner). Never
121
+ publish by hand, with `npm publish`, `npm stage publish` or the leftover `yarn upload` script, which goes at the next release.
122
+ Registry and credentials: [`../../docs/packages-and-releases.md`](../../docs/packages-and-releases.md).
123
+
124
+ ## What the migrations create
125
+
126
+ Every table is in the `qpanel` schema. Each has a `uuidv7()` primary key, except `admin` (the constant 1), `audit_event` (an
127
+ identity number) and the junction table (its two foreign keys). Each but `audit_event` has `created_at` / `updated_at`, the
128
+ second kept by a `BEFORE UPDATE` trigger. The tables follow the workspace's
129
+ [`docs/data-model.md`](../../docs/data-model.md).
130
+
131
+ | Migration | Creates |
132
+ |---|---|
133
+ | `…000000-create-enums-and-set-updated-at` | the enums `environment`, `db_engine`, `db_topology`, and `set_updated_at()` |
134
+ | `…000100-revoke-app-access-to-migration-tables` | takes Kysely's two bookkeeping tables away from the app role |
135
+ | `…000200-create-admin` | `admin`, a singleton: one row, enforced by `CHECK (id = 1)` |
136
+ | `…000300-create-secret` | `secret`, the credential vault (ciphertext, IV, tag, wrapped key, `key_version`) |
137
+ | `…000400-create-audit-event` | `audit_event`, append-only: the app role may only `INSERT` and `SELECT` |
138
+ | `…000500-create-registrar` … `…001000-create-service` | `registrar`, `client`, `client_note`, `domain`, `subdomain`, `service` |
139
+ | `…001100-create-datacenter` … `…001300-create-db-instance-node` | `datacenter`, `db_instance`, `db_instance_node` |
140
+ | `…001400-create-db-account` … `…001700-create-subdomain-app-database` | `db_account`, `app_database`, `app_database_user`, `subdomain_app_database` |
141
+ | `…001800-billing-fields` | the enum `invoice_frequency`; `domain` loses `currency` (EUR only), `annual_fee_cents` becomes `price_cents`, and it gains `invoice_frequency` and `payment_terms_days`; `service` gains an optional price, frequency and payment terms, all or none (ADR-019) |
142
+ | `…20261128000000-secret-value-changed-at` | `secret.value_changed_at`, when the value last changed (default `now()`, backfilled from `updated_at`); `master-key rewrap` never writes it |
143
+ | `…20261130000000-db-instance-environments` | `db_instance.environment` becomes `environments text[]`: at least one of the four environments, none twice, no NULL (ADR-033); a shared instance gets all four |
144
+ | `…20261130120000-create-server` | `server` (a machine of a datacenter, its name unique there ignoring case); `service` gains an optional `id_server` and `host` (`localhost`, IPv4 or IPv6, only with a server); server, host and port are unique together, `localhost` counting as `127.0.0.1` |
145
+ | `…20261130200000-create-server-ssh-access` | `ssh_access` (where a server's SSH daemon answers: host, port, knock sequences, pause, open time, the SSH user of another server it is reached through), `ssh_user` (accounts, with the ways to log in) and `ssh_key` (keys, FIDO2 security keys and certified keys); their passwords, one-time seeds, private keys, passphrases and PINs are `secret` rows deleted with them |
146
+ | `…20261201000000-ssh-login-per-way` | `ssh_login` (a way to log in of an SSH user: its place, its methods, and a password, a one-time code secret and notes of its own, ADR-043), filled from `ssh_user`, which loses `logins`, its two secrets and `notes`; the `secret` rows are not touched. Going back refuses while a user keeps two passwords or two one-time code secrets |
147
+
148
+ A table that owns a secret (`db_account`, `app_database_user`) has an `AFTER DELETE` trigger that deletes its `secret` row, so a
149
+ deleted account leaves no ciphertext behind. Foreign keys that point at a parent that owns its children cascade; every other one
150
+ restricts.
151
+
152
+ ## Master key and Keygrip
153
+
154
+ Every `secret` row is encrypted in the application (ADR-007): AES-256-GCM per value, a data key per secret, that key wrapped by
155
+ the **master key file** (`QPANEL_MASTER_KEY_PATH`, a ring of versions) and stamped with its `key_version`. These commands create
156
+ the file, rotate it, and seed the Keygrip key set that signs the refresh cookie. They use `@axiumine/qpanel-common`
157
+ for every cryptographic step (`^0.11.0`, installed from the registry like any consumer would); nothing here implements crypto.
158
+
159
+ ```bash
160
+ yarn master-key mint --path <file> # a new ring: version 1, current. Refuses an existing file
161
+ yarn master-key add-version --path <file> # add the next version and make it current (rotation, step 1)
162
+ yarn master-key rewrap [--test] --path <file> # re-wrap every secret not on the current version (step 2)
163
+ yarn master-key retire <version> [--test] --path <file> # drop a version nothing uses (step 3)
164
+
165
+ yarn keygrip seed # first deploy: create the key set in Redis. Refuses when one exists
166
+ yarn keygrip rotate # a new signing key in front, the old ones behind it
167
+ yarn keygrip retire <id> # drop one key that no longer signs, e.g. k1
168
+ ```
169
+
170
+ Exit codes as the migration commands: `0` done, `1` the command failed, `2` a usage error. No command prints a key, a KEK, a
171
+ password, a connection URL or a token, and no error message quotes one: messages are fixed text, and a driver's message goes
172
+ through the same redaction as the migrator's (`src/cli.mts`). They print no secret id either.
173
+
174
+ ### The master key file
175
+
176
+ - `mint` writes a new file with **mode 0600**, created exclusively (`wx`): an existing file, or a symbolic link, is refused and
177
+ never touched. It also refuses a directory the group or the others can write to (`0o022`), `/tmp` included. It prints the
178
+ path and the version only.
179
+ - `add-version` rewrites the file **atomically**: a temporary file in the same directory (`.<name>.<uuid>.tmp`, mode 0600),
180
+ written, `fsync`ed, renamed over the file. A crash leaves the old file whole or the new one whole. It prints the versions in
181
+ the file, never a key. Run it from a single shell: two concurrent `add-version` runs would each add the same next number and
182
+ one would win silently.
183
+ - The file is read the way the services read it (`readMasterKeyRing`): a symbolic link, a file that is not a regular file, or
184
+ any group/other permission bit is refused.
185
+ - Keep the file out of the repo and out of backups that other people can read. **Losing it destroys every secret** (parent
186
+ [`docs/secrets-and-auth-rules.md`](../../docs/secrets-and-auth-rules.md)): its backup procedure belongs to the production phase.
187
+
188
+ ### Which database role `rewrap` and `retire` use
189
+
190
+ **The app role** (`qpanel_<env>_app`): `DATABASE_URL`, or `DATABASE_URL_TEST` with `--test`. Not the migrator, which the runner
191
+ above reserves for DDL. The reasons:
192
+
193
+ - **Least privilege.** The job is DML on `secret` (read the wrap, write `wrapped_dek`, `key_version`, `rotated_at`) and one
194
+ `INSERT` into `audit_event`. It needs no DDL and no ownership. The app role already does exactly that in normal operation:
195
+ the services write secrets and audit events as that role.
196
+ - **The audit log stays append-only.** `audit_event` is append-only only because the app role owns nothing and has `UPDATE`,
197
+ `DELETE` and `TRUNCATE` revoked (migration `…000400`). A command running as the owner could rewrite the trail it is writing
198
+ to; this one cannot.
199
+ - **The migrator stays a one-purpose role** ([`../../docs/environments.md`](../../docs/environments.md): used only by `qpanel-db-setup`, never by a
200
+ service). A key ceremony has no use for its URL, which also lives only in this repo's env file.
201
+ - The command **refuses any other role**: after connecting it reads `current_user` and stops unless the name ends in `_app`
202
+ (`Refusing to run as "…": the master-key commands run only as a qpanel_<env>_app role.`), so a migrator or a superuser URL
203
+ in `DATABASE_URL` does nothing. `mint`, `add-version` and the Keygrip commands touch no database.
204
+
205
+ ### Rotating the master key, step by step
206
+
207
+ 1. **`master-key add-version --path <file>`** on the host that holds the file. Version N+1 becomes the current one; the old
208
+ versions stay in the file, so every existing secret still opens.
209
+ 2. **Deploy.** Give every service that reads the master key the new file and restart it. From now on new and changed secrets
210
+ are written under N+1. ⚠️ **Do not go on until every instance runs the new file**: a service with the old file cannot open a
211
+ secret wrapped under N+1.
212
+ 3. **`master-key rewrap --path <file>`** (add `--test` for `qpanel_test`). It re-wraps every secret whose `key_version` is not the
213
+ current one. Only the wrapped data key, `key_version` and `rotated_at` change: the ciphertext, IV and tag of the value are
214
+ untouched, so the cost is one unwrap and one wrap per secret, not a re-encryption of every value. `value_changed_at` is never
215
+ written: a re-wrap is not a new value, so the age of a secret survives it (`updated_at` moves, by its trigger).
216
+ 4. **`master-key retire <old version> --path <file>`** removes the old version from the file, **only if no secret still uses
217
+ it**: it counts the rows first and refuses, with the file unchanged, otherwise. The current version cannot be retired.
218
+ **Keep a copy of the old file until the oldest database backup you may restore has aged out**: a restore of an older dump
219
+ brings back rows wrapped under the old version, and the retired key is the only thing that opens them.
220
+ 5. Repeat step 4 for any older version still listed, then deploy the shortened file.
221
+
222
+ How `rewrap` works, and why it is safe to stop and repeat:
223
+
224
+ - **Batches.** Keyset pagination over `id`, **one transaction per 100 secrets**. Each batch reads the ids of the next rows that
225
+ are not on the current version, then **locks them (`FOR UPDATE`) and checks again** which of them still are not on it, so a
226
+ secret that a service writes while the run is going (always under the current version) is left alone and never overwritten
227
+ with a wrap that no longer fits its ciphertext.
228
+ - **Verified before written.** Each new wrap is opened again with the ring before the row is updated (as `rewrapSecret`'s
229
+ documentation advises). A row whose old key version is not in the ring, or that does not decrypt, is **counted, skipped and
230
+ left as it is**, not retried in this run, and does not stop the others. The command then exits `1` with the count and no id.
231
+ - **Idempotent and resumable.** A run that is interrupted has committed whole batches; the next one finds the rest by the
232
+ `key_version` column. A second run after a complete one re-wraps nothing and says so.
233
+ - **Audit.** One `audit_event` per run that did something: action `master_key_rewrapped`, entity type `secret`, `detail`
234
+ `{ "toKeyVersion": N, "rewrapped": n, "failed": f }`. Counts only, no secret id. It is written even when the run later fails, so
235
+ the batches that did commit are on record.
236
+ - **Output**: the ring's current version and versions, `Re-wrapped N secret(s) to key version C.`, and `Secrets by key version:
237
+ …`, so the operator sees when `retire` becomes possible.
238
+ - ⚠️ The plaintext of a secret exists in this process for the moment of the check and nowhere else: it is never stored,
239
+ printed, logged or put in an error. Run it from a host that is allowed to hold the master key file anyway.
240
+
241
+ ### The Keygrip key set (first deploy)
242
+
243
+ `keygrip seed` creates the record that signs the refresh-token cookie (the `<REDIS_KEY>keygrip` hash in the cluster): version 1
244
+ with one key, `k1`, wrapped under `KEYGRIP_KEK`. Run it **once per environment, at the first deploy, before any service starts**.
245
+ It refuses when a record exists. `rotate` puts a new key in front and keeps the old ones behind it (cookies signed by an old key
246
+ still verify); `retire <id>` drops a key that no longer signs, and refuses the one that does. After `rotate` and `retire`
247
+ **restart every service** so that it reads the new set (the commands say so).
248
+
249
+ They read the variables `@axiumine/koa-utils`' Redis client reads: `REDIS_IS_CLUSTER=1` (a cluster only), `REDIS_DB1..3_HOST` /
250
+ `_PORT`, `REDIS_USERNAME`, `REDIS_PASSWORD`, `REDIS_KEY` (the user plus a colon, `qpanel_dev:`), plus `KEYGRIP_KEK`. These come
251
+ from the workspace's shared env layer; none of them goes in this repo's own env file. Every command (`src/bin.mts`) loads that
252
+ shared file itself, found by walking up from this repo, then this repo's own, so no direnv is needed; an exported value always
253
+ wins. The output has only the namespace, the
254
+ version and a fingerprint. A wrong `KEYGRIP_KEK` is refused (`KEYGRIP_KEK is not base64 of 32 bytes, or is not the key the
255
+ Keygrip record was wrapped under.`) and changes nothing. The record has no TTL, by design: a service cannot sign without it.
256
+
257
+ `--test` is refused by `mint`, `add-version` and the Keygrip commands (there is no test target to switch to). The integration
258
+ tests of the Keygrip commands run as `qpanel_dev` under `qpanel_dev:test:<run id>:` and delete only the keys they wrote.
259
+
260
+ ## Tests and gates
261
+
262
+ ```bash
263
+ yarn lint:check && yarn typecheck
264
+ yarn test:cov # 100% statements, branches, functions and lines, plus the coverage audit
265
+ ```
266
+
267
+ `test/unit` needs no database. `test/integration` runs against `qpanel_test` (`DATABASE_MIGRATOR_URL_TEST` from `.env`,
268
+ `DATABASE_URL_TEST` from the workspace `.env.shared`, either of them from Infisical when no file holds it): it reverts and replays every migration, then proves each constraint,
269
+ foreign-key rule, trigger and privilege with a statement that must succeed or fail, and runs `master-key rewrap` and `retire`
270
+ over secrets that `qpanel-common` encrypted under rings of random keys made by the test. Never point those variables at another
271
+ database. `test/integration/package.test.mts` runs `npm pack` (which builds `dist/`), installs the tarball under a `node_modules` folder and
272
+ runs the installed bin's `migrate status|up|down` against `qpanel_test`, then compares the schema it left with the committed snapshot; it
273
+ needs `npm`, `yarn` and `tar` on the PATH. The Keygrip tests (`test/integration/keygrip.test.mts`) also need the Redis variables of the workspace's shared env
274
+ layer, as `qpanel_dev`: `test/support/redis.mts` refuses any other user, works under `qpanel_dev:test:<run id>:` and deletes only
275
+ the keys it saw (the ACL has no `SCAN`). `yarn test:mutation` (Stryker, break at 100) is run by `pre-push` and CI, never by hand.
276
+
277
+ The same gates run in the git hooks (`.githooks/`, armed by `yarn install`) and in `.github/workflows/gates.yml`, which also
278
+ proves `sql/bootstrap.sql` and `redis/bootstrap-acl.sh` against PostgreSQL 18.7 and a Redis cluster.
279
+
280
+ A documentation-only change (a root `*.md` or a `docs/**/*.md`, added or edited) skips the slow gates: `pre-push` and CI run semgrep,
281
+ trivy and lint only (workspace ADR-032, `.githooks/docs-only.sh`). Anything else runs every gate. ⚠️ Do not **add** a root `README*` or
282
+ `LICENSE*` file as a documentation-only change: npm packs it, and the package test fails at the next code change.
283
+
284
+ ## Security
285
+
286
+ Report a vulnerability in private: see [`SECURITY.md`](./SECURITY.md).
287
+
288
+ ## License
289
+
290
+ AGPL-3.0-or-later (parent ADR-047): the full text is in [`LICENSE`](./LICENSE).
@@ -0,0 +1,25 @@
1
+ import { sql } from 'kysely';
2
+ // The three enums, and the trigger function every table with `updated_at` shares. Values are fixed by
3
+ // docs/data-model.md (workspace root).
4
+ export async function up(db) {
5
+ await sql `
6
+ CREATE TYPE qpanel.environment AS ENUM ('development', 'testing', 'staging', 'production');
7
+ CREATE TYPE qpanel.db_engine AS ENUM ('mongodb', 'redis', 'postgres', 'mysql');
8
+ CREATE TYPE qpanel.db_topology AS ENUM ('standalone', 'replica_set', 'sharded', 'cluster', 'sentinel');
9
+
10
+ CREATE FUNCTION qpanel.set_updated_at() RETURNS trigger LANGUAGE plpgsql AS $$
11
+ BEGIN
12
+ NEW.updated_at := now();
13
+ RETURN NEW;
14
+ END
15
+ $$;
16
+ `.execute(db);
17
+ }
18
+ export async function down(db) {
19
+ await sql `
20
+ DROP FUNCTION qpanel.set_updated_at();
21
+ DROP TYPE qpanel.db_topology;
22
+ DROP TYPE qpanel.db_engine;
23
+ DROP TYPE qpanel.environment;
24
+ `.execute(db);
25
+ }
@@ -0,0 +1,39 @@
1
+ import { sql } from 'kysely';
2
+ // Kysely's two bookkeeping tables are created by the migrator, so the default privileges of bootstrap.sql
3
+ // hand the app role SELECT, INSERT, UPDATE and DELETE on them. A service that could rewrite them could make
4
+ // the next `migrate:up` run a migration twice, so the app role gets nothing on them. Not in
5
+ // docs/data-model.md, which lists the data tables only. The app role is derived from the role that runs
6
+ // the migration (qpanel_<env>_migrator gives qpanel_<env>_app), and anything else fails loudly.
7
+ export async function up(db) {
8
+ await sql `
9
+ DO $$
10
+ DECLARE
11
+ app_role text;
12
+ BEGIN
13
+ IF current_user !~ '^qpanel_(dev|test|staging|prod)_migrator$' THEN
14
+ RAISE EXCEPTION 'this migration must run as qpanel_<env>_migrator, not as %', current_user;
15
+ END IF;
16
+ app_role := regexp_replace(current_user, '_migrator$', '_app');
17
+ EXECUTE format('REVOKE ALL ON TABLE qpanel.kysely_migration, qpanel.kysely_migration_lock FROM %I', app_role);
18
+ END
19
+ $$;
20
+ `.execute(db);
21
+ }
22
+ export async function down(db) {
23
+ await sql `
24
+ DO $$
25
+ DECLARE
26
+ app_role text;
27
+ BEGIN
28
+ IF current_user !~ '^qpanel_(dev|test|staging|prod)_migrator$' THEN
29
+ RAISE EXCEPTION 'this migration must run as qpanel_<env>_migrator, not as %', current_user;
30
+ END IF;
31
+ app_role := regexp_replace(current_user, '_migrator$', '_app');
32
+ EXECUTE format(
33
+ 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE qpanel.kysely_migration, qpanel.kysely_migration_lock TO %I',
34
+ app_role
35
+ );
36
+ END
37
+ $$;
38
+ `.execute(db);
39
+ }
@@ -0,0 +1,24 @@
1
+ import { sql } from 'kysely';
2
+ // The singleton admin (ADR-008): `id` is the primary key and must be 1, so a second row cannot exist.
3
+ // `email` is citext from the qpanel schema, where bootstrap.sql installs it.
4
+ export async function up(db) {
5
+ await sql `
6
+ CREATE TABLE qpanel.admin (
7
+ id smallint PRIMARY KEY DEFAULT 1,
8
+ email qpanel.citext NOT NULL,
9
+ password_hash text NOT NULL,
10
+ password_changed_at timestamptz NOT NULL DEFAULT now(),
11
+ created_at timestamptz NOT NULL DEFAULT now(),
12
+ updated_at timestamptz NOT NULL DEFAULT now(),
13
+ CONSTRAINT admin_singleton CHECK (id = 1),
14
+ CONSTRAINT admin_email_unique UNIQUE (email)
15
+ );
16
+ CREATE TRIGGER admin_set_updated_at BEFORE UPDATE ON qpanel.admin
17
+ FOR EACH ROW EXECUTE FUNCTION qpanel.set_updated_at();
18
+ `.execute(db);
19
+ }
20
+ export async function down(db) {
21
+ await sql `
22
+ DROP TABLE qpanel.admin;
23
+ `.execute(db);
24
+ }
@@ -0,0 +1,37 @@
1
+ import { sql } from 'kysely';
2
+ // Ciphertext only (ADR-007): the application encrypts, the database never sees a key or a plaintext.
3
+ // `delete_owned_secret()` is the trigger function of every table that points at a secret with `id_secret`
4
+ // (db_account, app_database_user): when such a row is deleted, its secret goes with it, so no orphan
5
+ // ciphertext stays behind. It runs with the privileges of whoever deletes the row, which holds DELETE on
6
+ // `secret` like on every data table.
7
+ export async function up(db) {
8
+ await sql `
9
+ CREATE TABLE qpanel.secret (
10
+ id uuid PRIMARY KEY DEFAULT uuidv7(),
11
+ purpose text NOT NULL,
12
+ ciphertext bytea NOT NULL,
13
+ iv bytea NOT NULL,
14
+ auth_tag bytea NOT NULL,
15
+ wrapped_dek bytea NOT NULL,
16
+ key_version integer NOT NULL,
17
+ rotated_at timestamptz,
18
+ created_at timestamptz NOT NULL DEFAULT now(),
19
+ updated_at timestamptz NOT NULL DEFAULT now()
20
+ );
21
+ CREATE TRIGGER secret_set_updated_at BEFORE UPDATE ON qpanel.secret
22
+ FOR EACH ROW EXECUTE FUNCTION qpanel.set_updated_at();
23
+
24
+ CREATE FUNCTION qpanel.delete_owned_secret() RETURNS trigger LANGUAGE plpgsql AS $$
25
+ BEGIN
26
+ DELETE FROM qpanel.secret WHERE id = OLD.id_secret;
27
+ RETURN NULL;
28
+ END
29
+ $$;
30
+ `.execute(db);
31
+ }
32
+ export async function down(db) {
33
+ await sql `
34
+ DROP FUNCTION qpanel.delete_owned_secret();
35
+ DROP TABLE qpanel.secret;
36
+ `.execute(db);
37
+ }
@@ -0,0 +1,35 @@
1
+ import { sql } from 'kysely';
2
+ // Append-only for the app role: it is derived from the role that runs this migration
3
+ // (qpanel_<env>_migrator gives qpanel_<env>_app), anything else fails loudly, and the app role loses
4
+ // UPDATE, DELETE and TRUNCATE on this one table. It owns nothing, so it cannot grant them back.
5
+ export async function up(db) {
6
+ await sql `
7
+ CREATE TABLE qpanel.audit_event (
8
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
9
+ occurred_at timestamptz NOT NULL DEFAULT now(),
10
+ action text NOT NULL,
11
+ entity_type text,
12
+ entity_id text,
13
+ ip inet,
14
+ user_agent text,
15
+ detail jsonb NOT NULL DEFAULT '{}'::jsonb
16
+ );
17
+
18
+ DO $$
19
+ DECLARE
20
+ app_role text;
21
+ BEGIN
22
+ IF current_user !~ '^qpanel_(dev|test|staging|prod)_migrator$' THEN
23
+ RAISE EXCEPTION 'this migration must run as qpanel_<env>_migrator, not as %', current_user;
24
+ END IF;
25
+ app_role := regexp_replace(current_user, '_migrator$', '_app');
26
+ EXECUTE format('REVOKE UPDATE, DELETE, TRUNCATE ON TABLE qpanel.audit_event FROM %I', app_role);
27
+ END
28
+ $$;
29
+ `.execute(db);
30
+ }
31
+ export async function down(db) {
32
+ await sql `
33
+ DROP TABLE qpanel.audit_event;
34
+ `.execute(db);
35
+ }
@@ -0,0 +1,27 @@
1
+ import { sql } from 'kysely';
2
+ // The icon is optional, a PNG, JPEG or WebP of at most 128 KB, stored in the row (no SVG: script risk).
3
+ // Both icon columns are set, or neither.
4
+ export async function up(db) {
5
+ await sql `
6
+ CREATE TABLE qpanel.registrar (
7
+ id uuid PRIMARY KEY DEFAULT uuidv7(),
8
+ name text NOT NULL,
9
+ website_url text,
10
+ icon_mime text,
11
+ icon_bytes bytea,
12
+ created_at timestamptz NOT NULL DEFAULT now(),
13
+ updated_at timestamptz NOT NULL DEFAULT now(),
14
+ CONSTRAINT registrar_name_unique UNIQUE (name),
15
+ CONSTRAINT registrar_icon_mime_allowed CHECK (icon_mime IN ('image/png', 'image/jpeg', 'image/webp')),
16
+ CONSTRAINT registrar_icon_size_limit CHECK (octet_length(icon_bytes) <= 131072),
17
+ CONSTRAINT registrar_icon_both_or_none CHECK ((icon_mime IS NULL) = (icon_bytes IS NULL))
18
+ );
19
+ CREATE TRIGGER registrar_set_updated_at BEFORE UPDATE ON qpanel.registrar
20
+ FOR EACH ROW EXECUTE FUNCTION qpanel.set_updated_at();
21
+ `.execute(db);
22
+ }
23
+ export async function down(db) {
24
+ await sql `
25
+ DROP TABLE qpanel.registrar;
26
+ `.execute(db);
27
+ }
@@ -0,0 +1,47 @@
1
+ import { sql } from 'kysely';
2
+ // Only `legal_name` is required: a client is created with what is known and completed later. The Italian
3
+ // fields keep their English names: `vat_number` is the partita IVA, `tax_code` the codice fiscale, `pec` the
4
+ // certified email and `sdi_code` the e-invoicing recipient code. A client that holds domains is archived
5
+ // (`archived_at`), never deleted: domain.id_client restricts the delete.
6
+ export async function up(db) {
7
+ await sql `
8
+ CREATE TABLE qpanel.client (
9
+ id uuid PRIMARY KEY DEFAULT uuidv7(),
10
+ legal_name text NOT NULL,
11
+ trading_name text,
12
+ vat_number text,
13
+ tax_code text,
14
+ address_line text,
15
+ postal_code text,
16
+ city text,
17
+ province text,
18
+ country_code char(2),
19
+ email text,
20
+ phone text,
21
+ pec text,
22
+ sdi_code text,
23
+ billing_email text,
24
+ billing_address_line text,
25
+ billing_postal_code text,
26
+ billing_city text,
27
+ billing_province text,
28
+ billing_country_code char(2),
29
+ iban text,
30
+ contact_name text,
31
+ contact_phone text,
32
+ contact_email text,
33
+ archived_at timestamptz,
34
+ created_at timestamptz NOT NULL DEFAULT now(),
35
+ updated_at timestamptz NOT NULL DEFAULT now(),
36
+ CONSTRAINT client_country_code_format CHECK (country_code ~ '^[A-Z]{2}$'),
37
+ CONSTRAINT client_billing_country_code_format CHECK (billing_country_code ~ '^[A-Z]{2}$')
38
+ );
39
+ CREATE TRIGGER client_set_updated_at BEFORE UPDATE ON qpanel.client
40
+ FOR EACH ROW EXECUTE FUNCTION qpanel.set_updated_at();
41
+ `.execute(db);
42
+ }
43
+ export async function down(db) {
44
+ await sql `
45
+ DROP TABLE qpanel.client;
46
+ `.execute(db);
47
+ }
@@ -0,0 +1,22 @@
1
+ import { sql } from 'kysely';
2
+ // The index serves the client page, which lists the notes newest first, and the cascade delete.
3
+ export async function up(db) {
4
+ await sql `
5
+ CREATE TABLE qpanel.client_note (
6
+ id uuid PRIMARY KEY DEFAULT uuidv7(),
7
+ id_client uuid NOT NULL,
8
+ body text NOT NULL,
9
+ created_at timestamptz NOT NULL DEFAULT now(),
10
+ updated_at timestamptz NOT NULL DEFAULT now(),
11
+ CONSTRAINT id_client FOREIGN KEY (id_client) REFERENCES qpanel.client (id) ON DELETE CASCADE
12
+ );
13
+ CREATE INDEX client_note_id_client_created_at_idx ON qpanel.client_note (id_client, created_at DESC);
14
+ CREATE TRIGGER client_note_set_updated_at BEFORE UPDATE ON qpanel.client_note
15
+ FOR EACH ROW EXECUTE FUNCTION qpanel.set_updated_at();
16
+ `.execute(db);
17
+ }
18
+ export async function down(db) {
19
+ await sql `
20
+ DROP TABLE qpanel.client_note;
21
+ `.execute(db);
22
+ }
@@ -0,0 +1,37 @@
1
+ import { sql } from 'kysely';
2
+ // `name` is citext, so uniqueness and lookups ignore case, and the CHECK keeps it lower case in the A-label
3
+ // form (punycode for an IDN); the UI shows the U-label. Both foreign keys restrict: a registrar or a client
4
+ // that still has domains cannot be deleted. Every column but `notes` is required. `name::text` is explicit
5
+ // because `citext = text` would otherwise pick an operator by implicit cast.
6
+ export async function up(db) {
7
+ await sql `
8
+ CREATE TABLE qpanel.domain (
9
+ id uuid PRIMARY KEY DEFAULT uuidv7(),
10
+ name qpanel.citext NOT NULL,
11
+ id_registrar uuid NOT NULL,
12
+ id_client uuid NOT NULL,
13
+ expires_on date NOT NULL,
14
+ annual_fee_cents integer NOT NULL,
15
+ currency char(3) NOT NULL DEFAULT 'EUR',
16
+ auto_renew boolean NOT NULL DEFAULT false,
17
+ notes text,
18
+ created_at timestamptz NOT NULL DEFAULT now(),
19
+ updated_at timestamptz NOT NULL DEFAULT now(),
20
+ CONSTRAINT domain_name_unique UNIQUE (name),
21
+ CONSTRAINT domain_name_lower_case CHECK (name::text = lower(name::text)),
22
+ CONSTRAINT domain_annual_fee_cents_not_negative CHECK (annual_fee_cents >= 0),
23
+ CONSTRAINT domain_currency_format CHECK (currency ~ '^[A-Z]{3}$'),
24
+ CONSTRAINT id_registrar FOREIGN KEY (id_registrar) REFERENCES qpanel.registrar (id) ON DELETE RESTRICT,
25
+ CONSTRAINT id_client FOREIGN KEY (id_client) REFERENCES qpanel.client (id) ON DELETE RESTRICT
26
+ );
27
+ CREATE INDEX domain_id_registrar_idx ON qpanel.domain (id_registrar);
28
+ CREATE INDEX domain_id_client_idx ON qpanel.domain (id_client);
29
+ CREATE TRIGGER domain_set_updated_at BEFORE UPDATE ON qpanel.domain
30
+ FOR EACH ROW EXECUTE FUNCTION qpanel.set_updated_at();
31
+ `.execute(db);
32
+ }
33
+ export async function down(db) {
34
+ await sql `
35
+ DROP TABLE qpanel.domain;
36
+ `.execute(db);
37
+ }
@@ -0,0 +1,24 @@
1
+ import { sql } from 'kysely';
2
+ // The FQDN is `label` plus the domain's name. The unique constraint also serves the cascade delete.
3
+ export async function up(db) {
4
+ await sql `
5
+ CREATE TABLE qpanel.subdomain (
6
+ id uuid PRIMARY KEY DEFAULT uuidv7(),
7
+ id_domain uuid NOT NULL,
8
+ label text NOT NULL,
9
+ environment qpanel.environment,
10
+ notes text,
11
+ created_at timestamptz NOT NULL DEFAULT now(),
12
+ updated_at timestamptz NOT NULL DEFAULT now(),
13
+ CONSTRAINT subdomain_id_domain_label_unique UNIQUE (id_domain, label),
14
+ CONSTRAINT id_domain FOREIGN KEY (id_domain) REFERENCES qpanel.domain (id) ON DELETE CASCADE
15
+ );
16
+ CREATE TRIGGER subdomain_set_updated_at BEFORE UPDATE ON qpanel.subdomain
17
+ FOR EACH ROW EXECUTE FUNCTION qpanel.set_updated_at();
18
+ `.execute(db);
19
+ }
20
+ export async function down(db) {
21
+ await sql `
22
+ DROP TABLE qpanel.subdomain;
23
+ `.execute(db);
24
+ }
@@ -0,0 +1,25 @@
1
+ import { sql } from 'kysely';
2
+ // A service is a name and an optional port (ADR-012). The unique constraint also serves the cascade delete.
3
+ export async function up(db) {
4
+ await sql `
5
+ CREATE TABLE qpanel.service (
6
+ id uuid PRIMARY KEY DEFAULT uuidv7(),
7
+ id_subdomain uuid NOT NULL,
8
+ name text NOT NULL,
9
+ port integer,
10
+ notes text,
11
+ created_at timestamptz NOT NULL DEFAULT now(),
12
+ updated_at timestamptz NOT NULL DEFAULT now(),
13
+ CONSTRAINT service_id_subdomain_name_unique UNIQUE (id_subdomain, name),
14
+ CONSTRAINT service_port_range CHECK (port BETWEEN 1 AND 65535),
15
+ CONSTRAINT id_subdomain FOREIGN KEY (id_subdomain) REFERENCES qpanel.subdomain (id) ON DELETE CASCADE
16
+ );
17
+ CREATE TRIGGER service_set_updated_at BEFORE UPDATE ON qpanel.service
18
+ FOR EACH ROW EXECUTE FUNCTION qpanel.set_updated_at();
19
+ `.execute(db);
20
+ }
21
+ export async function down(db) {
22
+ await sql `
23
+ DROP TABLE qpanel.service;
24
+ `.execute(db);
25
+ }