@quatronic/sdk 0.10.1 → 0.11.0-test.014be98

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 (90) hide show
  1. package/README.md +6 -0
  2. package/dist/chunk-BJN7YE63.js +46 -0
  3. package/dist/chunk-BJN7YE63.js.map +1 -0
  4. package/dist/{chunk-TPBRMW5N.js → chunk-GYUIIM5X.js} +35 -45
  5. package/dist/chunk-GYUIIM5X.js.map +1 -0
  6. package/dist/chunk-JM5LHJUJ.js +32 -0
  7. package/dist/chunk-JM5LHJUJ.js.map +1 -0
  8. package/dist/{chunk-YFZB5EW6.js → chunk-P5GBQVO7.js} +2 -2
  9. package/dist/chunk-S7TJQVXV.js +34 -0
  10. package/dist/chunk-S7TJQVXV.js.map +1 -0
  11. package/dist/{chunk-IFESUTF2.js → chunk-VQKYPW5V.js} +7 -3
  12. package/dist/chunk-VQKYPW5V.js.map +1 -0
  13. package/dist/{chunk-POZI4OKJ.js → chunk-WOFBDOMY.js} +2 -2
  14. package/dist/chunk-YJZZURE4.js +83 -0
  15. package/dist/chunk-YJZZURE4.js.map +1 -0
  16. package/dist/cli/skills-postinstall.js +13 -6
  17. package/dist/cli/skills.js +11 -5
  18. package/dist/context-CWvUIBHJ.d.ts +196 -0
  19. package/dist/eslint/index.d.ts +11 -1
  20. package/dist/eslint/index.js +123 -4
  21. package/dist/eslint/index.js.map +1 -1
  22. package/dist/expo/auth/index.d.ts +14 -0
  23. package/dist/expo/auth/index.js +324 -0
  24. package/dist/expo/auth/index.js.map +1 -0
  25. package/dist/expo/config/index.d.ts +38 -0
  26. package/dist/expo/config/index.js +35 -0
  27. package/dist/expo/config/index.js.map +1 -0
  28. package/dist/expo/log/index.d.ts +9 -0
  29. package/dist/expo/log/index.js +16 -0
  30. package/dist/expo/log/index.js.map +1 -0
  31. package/dist/expo/query/index.d.ts +41 -0
  32. package/dist/expo/query/index.js +98 -0
  33. package/dist/expo/query/index.js.map +1 -0
  34. package/dist/expo/sentry/index.d.ts +33 -0
  35. package/dist/expo/sentry/index.js +121 -0
  36. package/dist/expo/sentry/index.js.map +1 -0
  37. package/dist/expo/testing/index.d.ts +32 -0
  38. package/dist/expo/testing/index.js +58 -0
  39. package/dist/expo/testing/index.js.map +1 -0
  40. package/dist/expo/updates/index.d.ts +51 -0
  41. package/dist/expo/updates/index.js +163 -0
  42. package/dist/expo/updates/index.js.map +1 -0
  43. package/dist/next/auth/index.d.ts +50 -0
  44. package/dist/next/auth/index.js +524 -101
  45. package/dist/next/auth/index.js.map +1 -1
  46. package/dist/next/boot/index.js +3 -3
  47. package/dist/next/db/index.d.ts +3 -27
  48. package/dist/next/db/index.js +11 -30
  49. package/dist/next/db/index.js.map +1 -1
  50. package/dist/next/security/index.d.ts +24 -1
  51. package/dist/next/security/index.js +29 -0
  52. package/dist/next/security/index.js.map +1 -1
  53. package/dist/next/sentry/client.js +3 -3
  54. package/dist/next/sentry/client.js.map +1 -1
  55. package/dist/next/sentry/index.js +1 -1
  56. package/dist/next/sentry/register.js +3 -3
  57. package/dist/node/db/migrate/index.d.ts +28 -0
  58. package/dist/node/db/migrate/index.js +16 -0
  59. package/dist/node/db/migrate/index.js.map +1 -0
  60. package/dist/node/sentry/index.js +1 -1
  61. package/dist/node/sentry/register.js +2 -2
  62. package/package.json +89 -2
  63. package/skills/catalog.json +4 -1
  64. package/skills/qore-add-api-route/SKILL.md +1 -1
  65. package/skills/qore-add-connection/SKILL.next.md +3 -1
  66. package/skills/qore-add-connection/SKILL.node.md +3 -1
  67. package/skills/qore-add-env-key/SKILL.md +174 -9
  68. package/skills/qore-add-feature/SKILL.md +1 -1
  69. package/skills/qore-add-integration/SKILL.next.md +4 -2
  70. package/skills/qore-add-integration/SKILL.node.md +6 -6
  71. package/skills/qore-add-page/SKILL.md +1 -1
  72. package/skills/qore-author-skill/SKILL.md +1 -1
  73. package/skills/qore-debug-issue/SKILL.md +10 -0
  74. package/skills/qore-mobile-add-screen/SKILL.md +64 -0
  75. package/skills/qore-mobile-call-server/SKILL.md +75 -0
  76. package/skills/qore-mobile-run-on-device/SKILL.md +44 -0
  77. package/skills/qore-observability/SKILL.md +17 -0
  78. package/skills/qore-secure-io/SKILL.md +15 -0
  79. package/skills/qore-ship-checklist/SKILL.md +10 -0
  80. package/skills/qore-translate-strings/SKILL.md +10 -0
  81. package/skills/qore-use-addons/SKILL.md +2 -0
  82. package/skills/qore-use-database/SKILL.md +177 -147
  83. package/skills/qore-use-design-system/SKILL.md +1 -1
  84. package/skills/qore-use-mail-domain/SKILL.next.md +1 -1
  85. package/skills/qore-use-mail-domain/SKILL.node.md +2 -2
  86. package/skills/qore-use-permissions/SKILL.md +10 -0
  87. package/dist/chunk-IFESUTF2.js.map +0 -1
  88. package/dist/chunk-TPBRMW5N.js.map +0 -1
  89. /package/dist/{chunk-YFZB5EW6.js.map → chunk-P5GBQVO7.js.map} +0 -0
  90. /package/dist/{chunk-POZI4OKJ.js.map → chunk-WOFBDOMY.js.map} +0 -0
@@ -1,25 +1,52 @@
1
1
  ---
2
2
  name: qore-use-database
3
- description: How this module's Postgres database works — where DATABASE_URL comes from, running the database locally, adding a client (pg or Drizzle), and applying migrations. Use when reading or writing data, adding a table, or debugging a connection error.
4
- allowed-tools: Bash(pnpm:*), Bash(docker:*), Read, Edit, Write
3
+ description: How this module's Postgres database works — one convention (Drizzle, migrations at boot, integration tests), a module that already has its own database layer, and a backend that has none yet. Use when reading or writing data, adding a table or migration, adding a database to this backend, or debugging a connection error.
4
+ allowed-tools: Bash(pnpm:*), Bash(docker:*), Bash(git fetch:*), Bash(git log:*), Read, Edit, Write
5
5
  ---
6
6
 
7
7
  # Using this module's database
8
8
 
9
- This module owns a Postgres database. The platform provisions it and injects the
10
- connection string; the module brings its own client. Nothing is pre-wired — this
11
- skill is the whole contract.
9
+ This skill covers a module's own Postgres database. The platform provisions it and injects the
10
+ connection strings; the module brings its own client. One convention applies to
11
+ every backend: Drizzle schema, generated migrations applied at boot, integration
12
+ tests against a local Postgres. A backend without one starts at §2.
13
+
14
+ ## 0. First: which database layer does this module have?
15
+
16
+ Look before you build. Two developers who each add "the" database layer to the same backend end up with two migration series that both start at `0000`.
17
+
18
+ 1. Run `git fetch origin`, then `git log --oneline HEAD..origin/main -- src/db src/lib/db.ts drizzle.config.ts docker-compose.yml`. A teammate may have landed a layer since you branched. If so, `git merge origin/main` (ask first) and use theirs.
19
+ 2. Then pick the row that matches what you find:
20
+
21
+ | You find | Do |
22
+ |---|---|
23
+ | `src/db/migrate.ts` calling `migrateApp` | The standard layer. Follow §3–§5. |
24
+ | Another layer: its own migration runner, a `schema_migrations` table, plain `pg` queries, another `src/db/` layout | Keep it. Add tables and migrations in its style, through its runner. Never start a second migration series or a second pool beside it. Moving it to the standard layer is a separate change the team decides on, not a side effect of a feature. |
25
+ | No layer: no migrations and no tables. `src/db/lock-down-public.ts` (the template's boot-time lockdown of schema `public`; keep its call) alone is not a layer. | §2, then build the standard layer (§3–§5). |
26
+
27
+ Keeping a layer of its own means it must still apply the new migration on every deploy. Check that, and fix what is missing in the same change: its runner is awaited before `server.listen`, and its migration files reach the runtime image (a build step that copies them into `dist/`, or a Dockerfile `COPY`). If that runner uses the runtime pool (`DATABASE_URL`) while `src/index.ts` runs `lockDownPublicSchema`, it cannot create a table in `public` on the platform. Tell the developer before relying on it, because changing which role runs the migrations is a decision about the layer.
12
28
 
13
29
  ## 1. Where `DATABASE_URL` comes from
14
30
 
15
- `src/config/env.ts` requires `DATABASE_URL` (`z.string().min(1)`), so the service
31
+ Once it has a database, `src/config/env.ts` requires `DATABASE_URL` (`z.string().startsWith("postgres")`), so the service
16
32
  refuses to boot without it.
17
33
 
34
+ How to declare, mark and check a key: `/qore-add-env-key`.
35
+
18
36
  | Where | How it arrives |
19
37
  |-------|----------------|
20
38
  | **Local** | `pnpm bootstrap` (or `qore env pull`) fetches it from the portal into `.env`. It points at the docker-compose database below on this module's own port: `postgresql://postgres:postgres@localhost:<DB_PORT>/app`, with `DB_PORT` written alongside it |
21
39
  | **staging / prod** | The portal injects the Northflank Postgres addon's own connection string per environment. Different host, database and credentials than local — never assume the local values. |
22
40
 
41
+ `MIGRATION_DATABASE_URL` is the second key:
42
+
43
+ | Where | How it arrives |
44
+ |-------|----------------|
45
+ | **Local** | The same database as `DATABASE_URL`. |
46
+ | **staging / prod** | The add-on's admin role. The portal binds both keys per environment. |
47
+
48
+ Locally `MIGRATION_DATABASE_URL` must name the same port as `DATABASE_URL`. If `qore env pull` left it on another one (an older portal), copy `DATABASE_URL`'s value into it in `.env`.
49
+
23
50
  Rules: never hardcode a connection string, never commit `.env` (it is gitignored),
24
51
  never read `process.env.DATABASE_URL` directly — import `env` from
25
52
  `./config/env.js` so a missing value fails fast at boot instead of at first query.
@@ -27,94 +54,158 @@ never read `process.env.DATABASE_URL` directly — import `env` from
27
54
  If `pnpm dev` dies on `DATABASE_URL: Required`, your `.env` is stale: re-run
28
55
  `qore env pull` (or `qore run -- pnpm dev` to skip the file).
29
56
 
30
- ## 2. Running the database locally
57
+ Don't change `DB_PORT` or the port in either URL by hand: they are
58
+ portal-managed, and `qore env pull` overwrites them with the assigned values.
59
+ The portal never gives two modules the same port, also not across tenants.
60
+ If the port is taken anyway, `qore dev` names what holds it. Most often that is
61
+ another checkout of this module (a worktree or a second clone): stop its
62
+ database there (`docker compose down` in that folder) or work from that
63
+ checkout. Anything else: stop it, or ask for the module's local ports to be
64
+ reassigned in the portal.
65
+
66
+ An older app may still publish a fixed port in `docker-compose.yml`, as
67
+ `"5432:5432"` or `"127.0.0.1:${DB_PORT:-5432}:5432"`. Then every such app
68
+ collides on 5432 whatever port the portal assigned. Replace that line with the
69
+ `ports` entry from the compose file below, and remove any `DB_PORT=` or
70
+ `DATABASE_URL=` line from `.env.example`: `qore env pull` writes them.
71
+
72
+ `ECONNREFUSED 127.0.0.1:<DB_PORT>` means the container is not running: `pnpm db:up`.
73
+
74
+ ## 2. A backend without a database
75
+
76
+ If the data belongs to another module's database, do not add one here: connect to that module (`qore-add-connection`).
77
+
78
+ 1. If the module's Resources tab in the portal lists no Postgres, ask the developer to add it there. Claude cannot do that from here. Adding it restarts the module and binds `DATABASE_URL` and `MIGRATION_DATABASE_URL` per environment.
79
+ 2. Local Postgres. Add this `docker-compose.yml`:
80
+
81
+ ```yaml
82
+ services:
83
+ db:
84
+ image: postgres:18-alpine
85
+ # Host port comes from DB_PORT, which the portal assigns per module so no
86
+ # two local databases share a port; `qore env pull` writes it. There is
87
+ # deliberately no default: a fixed port is what made databases collide.
88
+ #
89
+ # Bound to loopback only: on most Docker setups an unqualified host port
90
+ # binds to 0.0.0.0, exposing this database (well-known postgres/postgres
91
+ # credentials) to your whole LAN. Reachable from the host only — another
92
+ # *container* can no longer reach it via the host's LAN IP; that's the
93
+ # intended trade-off for a local dev database.
94
+ ports:
95
+ - "127.0.0.1:${DB_PORT:?DB_PORT is not set. Run qore env pull (or pnpm bootstrap) first}:5432"
96
+ environment:
97
+ POSTGRES_USER: postgres
98
+ POSTGRES_PASSWORD: postgres
99
+ POSTGRES_DB: app
100
+ volumes:
101
+ # postgres:18 stores data in a versioned subdir, so the volume mounts at
102
+ # /var/lib/postgresql (not /var/lib/postgresql/data, which 18 rejects).
103
+ - pgdata:/var/lib/postgresql
104
+ healthcheck:
105
+ test: ["CMD-SHELL", "pg_isready -U postgres"]
106
+ interval: 5s
107
+ timeout: 5s
108
+ retries: 10
109
+
110
+ volumes:
111
+ pgdata:
112
+ ```
113
+
114
+ And these scripts in `package.json`:
115
+
116
+ ```json
117
+ "db:up": "docker compose up -d --wait",
118
+ "db:down": "docker compose down",
119
+ "db:reset": "docker compose down -v && docker compose up -d --wait"
120
+ ```
121
+
122
+ Then run `qore env pull` to write `DATABASE_URL` and `DB_PORT` into `.env`, and `pnpm db:up`.
123
+ A psql shell: `docker compose exec db psql -U postgres -d app`.
124
+ 3. Append `&& pnpm run db:up` to the `bootstrap` script in `package.json`, so a fresh clone starts the database.
125
+ 4. In `src/config/env.ts` add `DATABASE_URL: z.string().startsWith("postgres")` and `MIGRATION_DATABASE_URL: z.string().startsWith("postgres").optional()`.
126
+
127
+ ## 3. The standard layer
128
+
129
+ | File or script | What it holds |
130
+ |---|---|
131
+ | `drizzle.config.ts` | `schema: "./src/db/schema.ts"`, `out: "./src/db/migrations"`, `dialect: "postgresql"` |
132
+ | `src/db/schema.ts` | `export const appSchema = pgSchema("app")`; every table is defined on it |
133
+ | `src/db/migrations/` | Generated by drizzle-kit, with `meta/_journal.json` |
134
+ | `src/lib/db.ts` | `getDb()`, lazy, one `pg.Pool` with `resolvePostgresConfig(env.DATABASE_URL)`, and `closePool(): Promise<void>` |
135
+ | `src/db/migrate.ts` | `runAppMigrations(): Promise<void>` |
136
+ | `src/db/seed.ts` | The seed |
137
+ | `vitest.integration.config.ts` | Runs `src/**/*.integration.test.ts` and loads `.env` itself |
138
+ | Scripts | `db:generate` = `drizzle-kit generate`, `db:seed` = `tsx src/db/seed.ts`, `test:integration` = `vitest run --config vitest.integration.config.ts` |
139
+
140
+ Install:
31
141
 
32
142
  ```
33
- pnpm db:up # start Postgres (docker compose up -d)
34
- pnpm db:down # stop it, keep the data
35
- pnpm db:reset # destroy the volume and start clean
143
+ pnpm add drizzle-orm pg && pnpm add -D drizzle-kit @types/pg tsx
36
144
  ```
37
145
 
38
- `docker-compose.yml` creates database `app` with user/password `postgres`.
39
- `pnpm bootstrap` already runs `db:up`. The host port is `DB_PORT` from `.env`:
40
- the portal assigns each module its own, so two modules with a database never
41
- fight over a port. `ECONNREFUSED 127.0.0.1:<DB_PORT>` usually
42
- means the container is not running — `pnpm db:up` — but `db:up` is `docker
43
- compose up -d` with no health wait, so the same error is also normal for a
44
- second or two right after starting; check `docker compose ps` / the compose
45
- healthcheck, or just retry.
146
+ If `pnpm add` stops on `ERR_PNPM_IGNORED_BUILDS` for esbuild, add `esbuild: true` under `allowBuilds` in `pnpm-workspace.yaml`.
46
147
 
47
- Don't change `DB_PORT` or the port in `DATABASE_URL` by hand: both are
48
- portal-managed, and `qore env pull` overwrites them with the assigned values.
49
- If the port is taken anyway, something else is listening on it — stop that, or
50
- ask for the module's local ports to be reassigned in the portal.
148
+ `src/lib/db.ts`: one pool per process, created on first use. Never open a client per request:
51
149
 
52
- A psql shell into the running container:
150
+ ```ts
151
+ import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres"
152
+ import { Pool } from "pg"
153
+ import { resolvePostgresConfig } from "@quatronic/sdk/node/db"
154
+ import { env } from "../config/env.js"
53
155
 
54
- ```
55
- docker compose exec db psql -U postgres -d app
56
- ```
156
+ let pool: Pool | undefined
157
+ let db: NodePgDatabase | undefined
57
158
 
58
- ## 3. Adding a client
159
+ export function getDb(): NodePgDatabase {
160
+ pool ??= new Pool({ ...resolvePostgresConfig(env.DATABASE_URL), max: 10 })
161
+ return (db ??= drizzle(pool))
162
+ }
163
+
164
+ export async function closePool(): Promise<void> {
165
+ await pool?.end()
166
+ pool = undefined
167
+ db = undefined
168
+ }
169
+ ```
59
170
 
60
- Pick one and stay with it. Both are traced automatically: the SDK's Sentry
61
- register instruments `pg`, so every query becomes a span — Drizzle included.
171
+ Never configure `ssl` by hand. Always spread `resolvePostgresConfig()`: it owns the TLS decision (no TLS for local
172
+ docker-compose, encrypted-but-unverified for Northflank's managed Postgres,
173
+ which terminates TLS with its own private CA, and full certificate
174
+ verification for any external database) and it strips the ssl params out of
175
+ the URL, without which `pg` silently overrides whatever `ssl` you pass —
176
+ it parses the connection string after the client options.
62
177
 
63
- ### Option A — `pg` (default: no ORM, plain SQL)
178
+ If the service dies at boot with `Error: self-signed certificate`, this is what
179
+ was skipped: something is verifying Northflank's private CA, which can never
180
+ succeed.
64
181
 
65
- ```
66
- pnpm add pg && pnpm add -D @types/pg
67
- ```
182
+ Always parameterise. Use Drizzle's operators, or `sql` template values. String-interpolating a value into SQL is an injection bug; there are no
183
+ exceptions to this.
68
184
 
69
- Create `src/lib/db.ts` — one pool per process, created at module load;
70
- connections are opened on demand as queries need them. Never open a client
71
- per request:
185
+ `src/db/migrate.ts`:
72
186
 
73
187
  ```ts
74
- import { Pool, type QueryResultRow } from "pg"
75
- import { resolvePostgresConfig } from "@quatronic/sdk/node/db"
188
+ import { migrateApp } from "@quatronic/sdk/node/db/migrate"
76
189
  import { env } from "../config/env.js"
77
-
78
- // One pool per process. Never configure `ssl` by hand here — always spread
79
- // resolvePostgresConfig(): it owns the TLS decision (no TLS for local
80
- // docker-compose, encrypted-but-unverified for Northflank's managed Postgres,
81
- // which terminates TLS with its own private CA, and full certificate
82
- // verification for any external database) and it strips the ssl params out of
83
- // the URL, without which `pg` silently overrides whatever `ssl` you pass —
84
- // it parses the connection string after the client options.
85
- const pool = new Pool({ ...resolvePostgresConfig(env.DATABASE_URL), max: 10 })
86
-
87
- export function query<T extends QueryResultRow>(
88
- sql: string,
89
- params: unknown[] = [],
90
- ): Promise<T[]> {
91
- return pool.query<T>(sql, params).then((r) => r.rows)
190
+ import { appSchema } from "./schema.js"
191
+
192
+ export async function runAppMigrations(): Promise<void> {
193
+ await migrateApp({
194
+ schema: appSchema.schemaName,
195
+ databaseUrl: env.DATABASE_URL,
196
+ // Locally one role owns everything; on the platform the add-on's admin role is set.
197
+ migrationDatabaseUrl: env.MIGRATION_DATABASE_URL ?? env.DATABASE_URL,
198
+ })
92
199
  }
200
+ ```
93
201
 
94
- /** Run several statements on one connection inside a transaction. */
95
- export async function transaction<T>(fn: (c: import("pg").PoolClient) => Promise<T>): Promise<T> {
96
- const client = await pool.connect()
97
- try {
98
- await client.query("BEGIN")
99
- const out = await fn(client)
100
- await client.query("COMMIT")
101
- return out
102
- } catch (err) {
103
- await client.query("ROLLBACK")
104
- throw err
105
- } finally {
106
- client.release()
107
- }
108
- }
202
+ A template-generated module calls `lockDownPublicSchema` right after `migrateApp` and keeps that call; when `src/db/lock-down-public.ts` exists, add that call to the snippet above.
109
203
 
110
- export function closePool(): Promise<void> {
111
- return pool.end()
112
- }
113
- ```
204
+ Call `await runAppMigrations()` in `src/index.ts` before `server.listen`, and let a failure end the process: a service running against an unmigrated database is worse than one that does not start.
114
205
 
115
- Always parameterise — `query("select * from widgets where id = $1", [id])`.
116
- String-interpolating a value into SQL is an injection bug; there are no
117
- exceptions to this.
206
+ `migrateApp` connects as the migrator role. That matters: Drizzle's migrator always runs `CREATE SCHEMA IF NOT EXISTS "drizzle"` for its bookkeeping table, which the runtime role may not do on the platform. A runner of your own over `DATABASE_URL` may fail at that step, and it runs DDL as the request-time role without the grants.
207
+
208
+ `migrateApp` reads `src/db/migrations` relative to the working directory, so the Dockerfile copies `src/db/migrations` into the runtime image next to `dist/`. Without that copy the deployed service finds no migrations.
118
209
 
119
210
  Close the pool on shutdown, in `src/index.ts`:
120
211
 
@@ -128,95 +219,34 @@ process.on("SIGTERM", () => {
128
219
  })
129
220
  ```
130
221
 
131
- ### Option B — Drizzle (typed schema + generated migrations)
132
-
133
- ```
134
- pnpm add drizzle-orm pg && pnpm add -D drizzle-kit @types/pg tsx
135
- ```
136
-
137
- Then follow the frontend convention: `src/db/schema.ts` defines tables on
138
- `pgSchema("app")`, `drizzle.config.ts` points `out` at `src/db/migrations`, and
139
- `drizzle-kit generate` writes the SQL. Commit the generated SQL and `meta/` and
140
- never hand-edit them — change `schema.ts` and regenerate.
141
-
142
- Drizzle runs on a `pg` pool, so build it exactly like option A —
143
- `new Pool({ ...resolvePostgresConfig(env.DATABASE_URL), max: 10 })` — and pass
144
- that pool to `drizzle()`. The same rule applies: never set `ssl` yourself.
145
-
146
- If the service dies at boot with `Error: self-signed certificate`, this is what
147
- was skipped: something is verifying Northflank's private CA, which can never
148
- succeed.
149
-
150
222
  ## 4. Migrations
151
223
 
152
- There is no migration runner in this module; that is deliberate — you choose the
153
- tool. Whatever you pick, the rules are the same:
224
+ Change `src/db/schema.ts`, run `pnpm db:generate`, and commit the SQL and `meta/`.
225
+
226
+ Run it once right after writing `schema.ts`: the migrator needs `meta/_journal.json`, and `migrateApp`'s grant needs the `app` schema to exist.
154
227
 
155
228
  - Migrations are **files in the repo**, applied automatically at boot. Do not
156
229
  create tables by hand in a psql shell: staging and prod have databases you
157
230
  cannot reach.
158
231
  - Forward-only. Never edit a migration that has already run in an environment —
159
232
  add a new one.
233
+ - Never hand-edit a generated file. Change `schema.ts` and regenerate.
160
234
 
161
- Minimal plain-SQL runner if you took option A. Add `src/db/migrations/0001_init.sql`,
162
- then `src/lib/migrate.ts`:
235
+ ## 5. Integration tests
163
236
 
164
- ```ts
165
- import { readdir, readFile } from "node:fs/promises"
166
- import { join } from "node:path"
167
- import * as Sentry from "@sentry/node"
168
- import { transaction } from "./db.js"
169
-
170
- // dist/lib/migrate.js runs from dist/, and tsc never copies .sql files — the
171
- // build script must copy src/db/migrations into dist/db/migrations, e.g.:
172
- // "build": "tsc -p tsconfig.json && cp -R src/db/migrations dist/db/migrations"
173
- // Without that step this throws ENOENT, in local dev (`pnpm dev`/`pnpm start`
174
- // run dist/) and in the container alike (the Dockerfile copies dist/ wholesale).
175
- const MIGRATIONS_DIR = join(import.meta.dirname, "../db/migrations")
176
-
177
- export async function runMigrations(): Promise<void> {
178
- const files = (await readdir(MIGRATIONS_DIR)).filter((f) => f.endsWith(".sql")).sort()
179
- await transaction(async (client) => {
180
- // Serialise concurrent boots (two replicas start at once) on one advisory
181
- // lock, taken BEFORE the table it protects — otherwise two replicas can
182
- // still race the create-table statement itself.
183
- await client.query("select pg_advisory_xact_lock(hashtext('schema_migrations'))")
184
- await client.query(
185
- "create table if not exists schema_migrations (name text primary key, applied_at timestamptz not null default now())",
186
- )
187
- const { rows } = await client.query<{ name: string }>("select name from schema_migrations")
188
- const applied = new Set(rows.map((r) => r.name))
189
- for (const name of files.filter((f) => !applied.has(f))) {
190
- await client.query(await readFile(join(MIGRATIONS_DIR, name), "utf8"))
191
- await client.query("insert into schema_migrations (name) values ($1)", [name])
192
- Sentry.logger.info("migration applied", { "qore.migration.name": name })
193
- }
194
- })
195
- }
196
- ```
237
+ `pnpm db:up`, then `pnpm test:integration` runs `src/**/*.integration.test.ts` against the local database.
197
238
 
198
- This runner wraps *all* pending migrations in a single transaction, so a
199
- statement that cannot run inside a transaction block (e.g. `CREATE INDEX
200
- CONCURRENTLY`, or `ALTER TYPE … ADD VALUE` on older Postgres versions) will
201
- fail. Such a migration needs to run outside the shared transaction — give it
202
- its own connection/transaction rather than adding it to the loop above.
239
+ `vitest.integration.config.ts` loads `.env` itself (`process.loadEnvFile`), because Vitest does not, and without it the tests miss the portal-assigned `DB_PORT`.
203
240
 
204
- Call it in `src/index.ts` **before** `server.listen` and let a failure crash the
205
- process — a service running against an unmigrated database is worse than one that
206
- does not start:
207
-
208
- ```ts
209
- await runMigrations()
210
- server.listen(env.PORT, () => { /* ... */ })
211
- ```
241
+ Keep `*.integration.test.ts` out of `pnpm test:run`: add it to `vitest.config.ts` `exclude` if it is missing.
212
242
 
213
- ## 5. Sharing this database with another module
243
+ ## 6. Sharing this database with another module
214
244
 
215
245
  Do not hand your `DATABASE_URL` to another module. The portal models this as a
216
246
  connection: the consumer gets `CONN_<ALIAS>_URI` / `_HOST` / `_USER` / … for your
217
247
  resource. See the `qore-add-connection` skill.
218
248
 
219
- ## 6. Before you ship
249
+ ## 7. Before you ship
220
250
 
221
- `pnpm lint && pnpm typecheck && pnpm test:run && pnpm build`, and check that a fresh clone works:
251
+ `pnpm lint && pnpm typecheck && pnpm test:run && pnpm test:integration (when the module has it) && pnpm build`, and check that a fresh clone works:
222
252
  `pnpm db:reset && pnpm bootstrap && pnpm build && pnpm dev`.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: qore-use-design-system
3
- description: Use this app's house component kit and design tokens. Use whenever building or restyling UI — pages, forms, tables, dialogs — so the app stays visually consistent.
3
+ description: Use the web app's (src/) house component kit and design tokens. Use whenever building or restyling UI — pages, forms, tables, dialogs — so the app stays visually consistent.{{#if mobile}} Not for the phone app in mobile/ (use the qore-mobile-* skills).{{/if}}
4
4
  ---
5
5
 
6
6
  # Use the design system
@@ -18,7 +18,7 @@ environments:
18
18
  | `MAIL_FROM` | the full from-header, e.g. `Acme Support <support@acme.nl>` |
19
19
 
20
20
  > These are system-managed: they never appear in `.env.example`, never show up
21
- > in this module's Secrets tab, and you cannot set them yourself. Until a
21
+ > in this module's Variables tab, and you cannot set them yourself. Until a
22
22
  > domain is linked they're simply absent.
23
23
 
24
24
  ## Hard rule: never present in `local` or preview
@@ -17,8 +17,8 @@ environments:
17
17
  | `MAIL_SENDING_DOMAIN` | the domain, e.g. `acme.nl` — informational only, already baked into `MAIL_FROM` |
18
18
  | `MAIL_FROM` | the full from-header, e.g. `Acme Support <support@acme.nl>` |
19
19
 
20
- > These are system-managed: they never appear in `.env.example`, never show up
21
- > in this module's Secrets tab, and you cannot set them yourself. Until a
20
+ > These are system-managed: they never show up
21
+ > in this module's Variables tab, and you cannot set them yourself. Until a
22
22
  > domain is linked they're simply absent.
23
23
 
24
24
  ## Hard rule: never present in `local` or preview
@@ -114,3 +114,13 @@ Run `pnpm lint && pnpm typecheck && pnpm test:run && pnpm build`, then
114
114
 
115
115
  > `hasRole` from `@/lib/roles` still exists for cases that genuinely key off a
116
116
  > raw role, but prefer permissions.
117
+
118
+ {{#if mobile}}
119
+ ## The phone app (`mobile/`)
120
+
121
+ The phone reads the signed-in user's permissions from `/api/auth/me` and offers
122
+ `useCan("<permission>")` and `<Can permission="…" fallback={…}>` from `@/lib/auth`. They
123
+ **only hide**: an installed app can be taken apart, so every server route the phone calls
124
+ checks the same permission with `requireAuthFor`. A role change reaches the phone on its next
125
+ `/api/auth/me`, at app start or after sign-in.
126
+ {{/if}}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sentry-core/scrub.ts"],"sourcesContent":["export const REDACTED = \"●●●\"\n\n// Bounded and anchored (`(?<![...])` + `{1,64}` local part, no `.` in the\n// domain-char class) so it cannot backtrack catastrophically on long runs of\n// email-charset bytes — see the fix-round-1 report for the O(n²) it replaced.\nconst EMAIL = /(?<![A-Z0-9._%+-])[A-Z0-9._%+-]{1,64}@[A-Z0-9-]+(?:\\.[A-Z0-9-]+)*\\.[A-Z]{2,}/gi\nconst URL_USERINFO = /\\b([a-z][a-z0-9+.-]{0,31}:\\/\\/)[^/\\s:@]+(?::[^/\\s@]*)?@/gi\nconst JWT = /eyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+/g\nconst AUTH_SCHEME = /\\b(Bearer|Basic)\\s+\\S+/gi\nconst PARAMS_TAIL = /\\bparams:\\s.*$/s\nexport const SECRET_PARAMS: ReadonlySet<string> = new Set([\"token\", \"code\", \"state\", \"password\", \"secret\", \"key\", \"session\", \"access_token\", \"refresh_token\", \"id_token\"])\nconst SECRET_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-qdc-connection-token\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"forwarded\",\n \"user-agent\",\n])\nconst DROP_LOG_ATTRS = new Set([\"ip\", \"ip_address\", \"user_agent\", \"email\", \"user_email\", \"server.address\"])\nconst REDACT_KEYS = new Set([\"db.connection_string\", \"db.user\"])\nconst REDACT_PREFIXES = [\"net.peer.\", \"net.sock.\", \"net.host.\", \"network.peer.\", \"network.local.\"]\nconst DROP_SPAN_KEYS = new Set([\"user_agent.original\", \"http.user_agent\", \"client.address\", \"http.client_ip\"])\nconst DROP_SPAN_PREFIXES = [\"http.request.header.\", \"http.response.header.\"]\nconst URL_SPAN_KEYS = new Set([\"url.full\", \"http.url\", \"url\", \"http.target\", \"url.query\", \"http.query\"])\n\nconst SECRETS = Symbol.for(\"@quatronic/sdk.sentry-secret-values\")\ntype SecretHolder = { [SECRETS]?: { values: Set<string>; longestFirst: string[] } }\nconst secretHolder = globalThis as SecretHolder\n\n// On globalThis because a Next app can bundle this module twice: the copy\n// serverEnv() registers into is not necessarily the one beforeSend reads.\nfunction secretState(): NonNullable<SecretHolder[typeof SECRETS]> {\n return (secretHolder[SECRETS] ??= { values: new Set(), longestFirst: [] })\n}\n\nexport function registerSecretValues(values: Iterable<unknown>): void {\n const state = secretState()\n for (const v of values) if (typeof v === \"string\" && v.length >= 8) state.values.add(v)\n state.longestFirst = [...state.values].sort((a, b) => b.length - a.length)\n}\n\nfunction maskSecretValues(s: string): string {\n return secretState().longestFirst.reduce((acc, v) => acc.replaceAll(v, REDACTED), s)\n}\n\nexport function redactText(s: string): string {\n return maskSecretValues(s)\n .replace(URL_USERINFO, `$1${REDACTED}@`)\n .replace(PARAMS_TAIL, \"params: [redacted]\")\n .replace(AUTH_SCHEME, \"$1 [redacted]\")\n .replace(JWT, \"[jwt]\")\n .replace(EMAIL, \"[email]\")\n}\n\nfunction redactQuery(query: string): string {\n return query\n .split(\"&\")\n .map((pair) => {\n const [k, v] = pair.split(\"=\", 2)\n return v !== undefined && SECRET_PARAMS.has(k!.toLowerCase()) ? `${k}=[redacted]` : pair\n })\n .join(\"&\")\n}\n\nfunction redactUrl(url: string): string {\n const i = url.indexOf(\"?\")\n return i < 0 ? url : url.slice(0, i + 1) + redactQuery(url.slice(i + 1))\n}\n\n// For values that are either a URL/path or a bare query string (no `?`).\nfunction redactUrlOrQuery(v: string): string {\n return v.includes(\"?\") ? redactUrl(v) : redactQuery(v)\n}\n\ntype Dict = Record<string, unknown>\n\nexport interface SentryEventLike {\n server_name?: string\n user?: Dict\n request?: { url?: string; query_string?: unknown; cookies?: unknown; headers?: Record<string, string>; data?: unknown }\n message?: string\n exception?: { values?: Array<{ type?: string; value?: string }> }\n breadcrumbs?: Array<{ message?: string; data?: Dict }>\n contexts?: { nextjs?: Dict } & Dict\n}\n\nexport function scrubEvent<E extends SentryEventLike>(e: E): E {\n delete e.server_name\n if (e.user) e.user = e.user.id ? { id: e.user.id } : {}\n if (e.request) {\n delete e.request.cookies\n delete e.request.data\n if (e.request.url) e.request.url = redactUrl(e.request.url)\n if (typeof e.request.query_string === \"string\") e.request.query_string = redactQuery(e.request.query_string)\n if (e.request.headers) {\n e.request.headers = Object.fromEntries(\n Object.entries(e.request.headers).filter(([k]) => !SECRET_HEADERS.has(k.toLowerCase())),\n )\n }\n }\n const nextjs = e.contexts?.nextjs\n if (typeof nextjs?.request_path === \"string\") nextjs.request_path = redactUrl(nextjs.request_path)\n if (e.message) e.message = redactText(e.message)\n for (const v of e.exception?.values ?? []) if (v.value) v.value = redactText(v.value)\n for (const b of e.breadcrumbs ?? []) {\n if (b.message) b.message = redactText(b.message)\n const d = b.data\n if (!d) continue\n for (const k of [\"url\", \"from\", \"to\"]) if (typeof d[k] === \"string\") d[k] = redactUrl(d[k])\n if (typeof d[\"http.query\"] === \"string\") d[\"http.query\"] = redactUrlOrQuery(d[\"http.query\"])\n if (Array.isArray(d.arguments)) d.arguments = d.arguments.map((a) => (typeof a === \"string\" ? redactText(a) : a))\n }\n return e\n}\n\nexport interface SentryLogLike {\n message: string\n attributes?: Dict\n}\n\nexport function scrubLog<L extends SentryLogLike>(l: L): L {\n l.message = redactText(l.message)\n if (l.attributes) {\n const out: Dict = {}\n for (const [k, v] of Object.entries(l.attributes)) {\n if (DROP_LOG_ATTRS.has(k)) continue\n out[k] = typeof v === \"string\" ? redactText(v) : v\n }\n l.attributes = out\n }\n return l\n}\n\nexport interface SentrySpanLike {\n description?: string\n data?: Dict\n}\n\nexport function scrubSpan<S extends SentrySpanLike>(s: S): S {\n // Browser page-metric spans are described by the full page URL.\n if (typeof s.description === \"string\") s.description = redactUrl(s.description)\n for (const [k, v] of Object.entries(s.data ?? {})) {\n if (DROP_SPAN_KEYS.has(k) || DROP_SPAN_PREFIXES.some((p) => k.startsWith(p))) delete s.data![k]\n else if (REDACT_KEYS.has(k) || REDACT_PREFIXES.some((p) => k.startsWith(p))) s.data![k] = REDACTED\n else if (typeof v === \"string\" && URL_SPAN_KEYS.has(k)) s.data![k] = redactUrlOrQuery(v)\n }\n return s\n}\n"],"mappings":";AAAO,IAAM,WAAW;AAKxB,IAAM,QAAQ;AACd,IAAM,eAAe;AACrB,IAAM,MAAM;AACZ,IAAM,cAAc;AACpB,IAAM,cAAc;AACb,IAAM,gBAAqC,oBAAI,IAAI,CAA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9E,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,EAAE,QAAQ,CAAC,CAAC,GAAG;AACjD,QAAI,eAAe,IAAI,CAAC,KAAK,mBAAmB,KAAK,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,EAAG,QAAO,EAAE,KAAM,CAAC;AAAA,aACrF,YAAY,IAAI,CAAC,KAAK,gBAAgB,KAAK,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,EAAG,GAAE,KAAM,CAAC,IAAI;AAAA,aACjF,OAAO,MAAM,YAAY,cAAc,IAAI,CAAC,EAAG,GAAE,KAAM,CAAC,IAAI,iBAAiB,CAAC;AAAA,EACzF;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/db-core/migration-db.ts","../src/auth-core/migrate.ts"],"sourcesContent":["import { Pool } from \"pg\"\nimport { drizzle, type NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { sql } from \"drizzle-orm\"\nimport { resolvePostgresConfig } from \"./postgres-config\"\n\nexport interface MigrationDb {\n readonly db: NodePgDatabase\n readonly close: () => Promise<void>\n}\n\n// Migrations get their own short-lived pool, separate from the app's\n// long-lived runtime pool — it exists only for the duration of the boot-time\n// migration call and is torn down immediately after.\nexport function createMigrationDb(databaseUrl: string): MigrationDb {\n const pool = new Pool(resolvePostgresConfig(databaseUrl))\n return { db: drizzle(pool), close: () => pool.end() }\n}\n\n// The addon's regular/admin credentials are both delivered as full DSNs\n// (POSTGRES_URI / POSTGRES_URI_ADMIN — see the templates SecretGroup\n// addonDependencies mapping), not as separate username/password fields, so\n// callers that need the runtime role's name for a GRANT statement parse it\n// out of the runtime connection string instead of reading it separately.\nexport function parseRoleFromUrl(databaseUrl: string): string {\n return decodeURIComponent(new URL(databaseUrl).username)\n}\n\n// `current_user` is compared as the server reports it, so the comparison holds\n// for a role whose name needed quoting in the DSN.\nasync function isCurrentUser(db: NodePgDatabase, role: string): Promise<boolean> {\n const result = await db.execute<{ current_user: string }>(\n sql.raw(`SELECT current_user AS \"current_user\"`),\n )\n return result.rows[0]?.current_user === role\n}\n\n// Safe to call on every boot, whether or not the migrator and runtime roles\n// are the same (the fallback case for environments that haven't opted into a\n// separate migration role yet — see MIGRATION_DATABASE_URL fallback in\n// portal-api/portal-web). ALTER DEFAULT PRIVILEGES only binds objects created\n// after it runs, so this also explicitly grants on ALL TABLES to cover\n// whatever this same run just created.\n//\n// The fallback case is skipped outright rather than issued anyway: granting a\n// role privileges to itself is either redundant (it owns the objects, so it\n// already holds everything) or impossible (it does not, so GRANT raises `must\n// be owner of table …` / `permission denied for schema …`). Issuing it made\n// that second case a boot-time failure on an environment where there was\n// nothing whatsoever to grant.\nexport async function grantRuntimeDefaultPrivileges(\n db: NodePgDatabase,\n schema: string,\n runtimeRole: string,\n): Promise<void> {\n if (await isCurrentUser(db, runtimeRole)) {\n return\n }\n await db.execute(\n sql.raw(`GRANT USAGE ON SCHEMA \"${schema}\" TO \"${runtimeRole}\"`),\n )\n await db.execute(\n sql.raw(\n `ALTER DEFAULT PRIVILEGES IN SCHEMA \"${schema}\" GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO \"${runtimeRole}\"`,\n ),\n )\n await db.execute(\n sql.raw(\n `GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA \"${schema}\" TO \"${runtimeRole}\"`,\n ),\n )\n}\n","import { sql } from \"drizzle-orm\"\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { grantRuntimeDefaultPrivileges } from \"../db-core/migration-db\"\n\n// Migrations are inlined as string constants rather than read from .sql files\n// at runtime. A runtime `readFile` does not survive bundlers that only trace\n// JS — notably Next.js standalone output, where the .sql is omitted and the\n// read ENOENTs, crashing the instrumentation hook and 500-ing the whole app.\n// Inlining keeps the SQL in the bundled JS so it works in every consumer.\n\n// Split out of what used to be a single MIGRATION_0001_INIT on purpose, and\n// the reason generalises to every statement below it: **Postgres checks the\n// connecting role's privileges before it evaluates `IF NOT EXISTS`.** So an\n// already-applied statement is not a no-op for a role that lacks the right —\n// it is an error:\n//\n// - `CREATE SCHEMA IF NOT EXISTS auth` needs CREATE on the *database* →\n// `permission denied for database <db>` (SQLSTATE 42501)\n// - `CREATE INDEX IF NOT EXISTS` and `ALTER TABLE ... ADD COLUMN IF NOT\n// EXISTS` need *ownership* of the table → `must be owner of table\n// sessions` (also 42501)\n//\n// That is the normal shape of a least-privileged runtime role against an\n// already-provisioned database, and because migrations run in order one such\n// error aborts every statement after it. It has now bitten staging twice: the\n// first time `login_state.forced_reauth` never landed and every\n// `/api/auth/login` 500'd; the second time `0001_init:tables` failed on its\n// `CREATE INDEX` with `must be owner of table sessions`, again blocking every\n// later ALTER even though there was nothing at all to do.\n//\n// So each migration below carries an `isApplied` catalog probe and the runner\n// skips it when its effect is already present. Catalog lookups need nothing\n// beyond CONNECT, so a role with only DML inside an up-to-date `auth` schema\n// gets through cleanly, while a migration that genuinely still has work to do\n// is attempted and — if the role cannot do it — fails loudly, by name.\nconst MIGRATION_0001_SCHEMA = `\nCREATE SCHEMA IF NOT EXISTS auth;\n`\n\nconst MIGRATION_0001_TABLES = `\nCREATE TABLE IF NOT EXISTS auth.sessions (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n user_sub varchar(64) NOT NULL,\n user_email varchar(320),\n organization_id varchar(64),\n organization_alias varchar(255),\n access_token text NOT NULL,\n access_expires_at timestamptz NOT NULL,\n refresh_ct bytea NOT NULL,\n refresh_iv bytea NOT NULL,\n refresh_expires_at timestamptz NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n revoked_at timestamptz\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_sessions_user_sub\n ON auth.sessions(user_sub) WHERE revoked_at IS NULL;\n\nCREATE TABLE IF NOT EXISTS auth.login_state (\n state varchar(128) PRIMARY KEY,\n code_verifier varchar(255) NOT NULL,\n redirect_path text NOT NULL DEFAULT '/',\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_login_state_expires\n ON auth.login_state(expires_at);\n`\n\n// The KC ID token, so RP-initiated logout can pass it as `id_token_hint` —\n// without it, Keycloak's end-session endpoint falls back to showing a logout\n// confirmation page. Nullable: existing sessions predate this column until\n// their next login or token refresh backfills it.\nconst MIGRATION_0002_ID_TOKEN = `\nALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS id_token text;\n`\n\n// Records that this login asked Keycloak to re-authenticate (prompt=login +\n// max_age=0). The callback needs it to know whether the ID token's auth_time\n// MUST prove a fresh authentication (OIDC 3.1.2.1) — without the flag it cannot\n// tell a forced login from an ordinary SSO continuation.\nconst MIGRATION_0003_FORCED_REAUTH = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS forced_reauth boolean NOT NULL DEFAULT false;\n`\n\n// OIDC 3.1.3.7 (11): the nonce sent on the authorization request must be\n// checked against the ID token's claim. Nullable because rows written by an\n// older build have none; the callback treats a null nonce on the row as\n// \"nothing to check\" so an in-flight login survives the deploy.\nconst MIGRATION_0004_NONCE = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS nonce varchar(128);\n`\n\n// Bounds the one-and-only restart the callback grants on Keycloak's explicit\n// \"start over\" signals (authentication_expired / login_required). The\n// callback URL is Keycloak's fixed redirect_uri, so Keycloak never echoes our\n// own query parameters back to it — a guard read off the callback's query\n// string can never fire in production. The restarted login (our own request\n// to /api/auth/login?retried=1) stamps this column on the NEW row instead, so\n// the second callback can see it on the row rather than in a URL Keycloak\n// controls. NOT NULL DEFAULT false: every row, old or new, starts un-retried.\nconst MIGRATION_0005_RETRIED = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS retried boolean NOT NULL DEFAULT false;\n`\n\n// A session created for an identity that did not match what the login expected\n// exists, holds real tokens, and grants nothing until a human confirms it.\n//\n// DELIBERATELY `DEFAULT false` rather than a nullable column with a backfill:\n// these migrations re-run on every app start, so an `UPDATE ... WHERE\n// pending_identity_confirm IS NULL` would confirm every row still awaiting a\n// human on the next deploy — silently adopting exactly the identity this\n// mechanism exists to stop. A default means pre-existing rows are already\n// confirmed, which is correct: they were issued under the old rules.\nconst MIGRATION_0006_PENDING_CONFIRM = `\nALTER TABLE auth.sessions\n ADD COLUMN IF NOT EXISTS pending_identity_confirm boolean NOT NULL DEFAULT false;\n`\n\n// Who this login was supposed to end up as: the subject of the session being\n// replaced, and/or the address the user typed. The callback compares Keycloak's\n// answer against these instead of adopting whatever comes back. Nullable: a\n// clean first login on a fresh browser expects nobody in particular.\nconst MIGRATION_0007_EXPECTED_IDENTITY = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_sub varchar(64);\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_email varchar(320);\n`\n\ninterface Migration {\n // Named so a failure can say *which* statement broke — see the catch below.\n readonly name: string\n readonly sql: string\n // \"Is this migration's effect already present?\" Answered from the catalogs\n // only, so it never needs a privilege the migration itself would need. A\n // partially-applied migration must answer `false` (the SQL is written to be\n // idempotent, so re-running the applied half is harmless).\n readonly isApplied: (db: NodePgDatabase) => Promise<boolean>\n // A migration may only add to the schema: a prod rollback keeps the\n // database, and the previous release must still work on it\n // (scripts/migration-lint.mjs refuses anything else). `true` marks the rare\n // migration that removes or tightens something on purpose; ship it only once\n // no prod still runs a version that reads the old shape.\n readonly contract?: boolean\n}\n\n// All probes funnel through here: one boolean expression, evaluated by the\n// server. Every one of them reads `pg_catalog` directly rather than going\n// through `to_regclass`/`to_regnamespace` or `information_schema`, both of\n// which are privilege-sensitive in ways that defeat the purpose: `to_regclass`\n// resolves the name and so raises `permission denied for schema auth` for a\n// role without USAGE, and `information_schema.columns` silently hides columns\n// the role holds no privilege on — reporting an applied migration as missing\n// and sending us straight into the ALTER we were trying to avoid. The catalogs\n// themselves are world-readable.\nasync function probe(db: NodePgDatabase, expression: string): Promise<boolean> {\n const result = await db.execute<{ applied: boolean }>(\n sql.raw(`SELECT (${expression}) AS \"applied\"`),\n )\n return result.rows[0]?.applied === true\n}\n\nconst schemaExists = (schema: string) => (db: NodePgDatabase) =>\n probe(db, `EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '${schema}')`)\n\n// Tables and indexes alike — both live in `pg_class`.\nconst relationsExist =\n (...relations: readonly (readonly [schema: string, name: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = relations.map(([schema, name]) => `('${schema}','${name}')`).join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE (n.nspname, c.relname) IN (${tuples})) = ${relations.length}`,\n )\n }\n\nconst columnsExist =\n (...columns: readonly (readonly [schema: string, table: string, column: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = columns\n .map(([schema, table, column]) => `('${schema}','${table}','${column}')`)\n .join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE a.attnum > 0 AND NOT a.attisdropped\n AND (n.nspname, c.relname, a.attname) IN (${tuples})) = ${columns.length}`,\n )\n }\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n name: \"0001_init:schema\",\n sql: MIGRATION_0001_SCHEMA,\n isApplied: schemaExists(\"auth\"),\n },\n {\n name: \"0001_init:tables\",\n sql: MIGRATION_0001_TABLES,\n isApplied: relationsExist(\n [\"auth\", \"sessions\"],\n [\"auth\", \"ix_auth_sessions_user_sub\"],\n [\"auth\", \"login_state\"],\n [\"auth\", \"ix_auth_login_state_expires\"],\n ),\n },\n {\n name: \"0002_id_token\",\n sql: MIGRATION_0002_ID_TOKEN,\n isApplied: columnsExist([\"auth\", \"sessions\", \"id_token\"]),\n },\n {\n name: \"0003_forced_reauth\",\n sql: MIGRATION_0003_FORCED_REAUTH,\n isApplied: columnsExist([\"auth\", \"login_state\", \"forced_reauth\"]),\n },\n {\n name: \"0004_nonce\",\n sql: MIGRATION_0004_NONCE,\n isApplied: columnsExist([\"auth\", \"login_state\", \"nonce\"]),\n },\n {\n name: \"0005_retried\",\n sql: MIGRATION_0005_RETRIED,\n isApplied: columnsExist([\"auth\", \"login_state\", \"retried\"]),\n },\n {\n name: \"0006_pending_confirm\",\n sql: MIGRATION_0006_PENDING_CONFIRM,\n isApplied: columnsExist([\"auth\", \"sessions\", \"pending_identity_confirm\"]),\n },\n {\n name: \"0007_expected_identity\",\n sql: MIGRATION_0007_EXPECTED_IDENTITY,\n isApplied: columnsExist(\n [\"auth\", \"login_state\", \"expected_sub\"],\n [\"auth\", \"login_state\", \"expected_email\"],\n ),\n },\n]\n\nexport interface RunAuthMigrationsOptions {\n // When provided, grants this role SELECT/INSERT/UPDATE/DELETE on every\n // table in the `auth` schema — both ones this call just created and ones a\n // future boot's migrations will create. Omit for a single-role setup (the\n // fallback state of an environment that hasn't opted into a separate\n // migration role yet); passing it is what makes it safe for `db` to\n // connect as an admin/owner role while the app itself never does.\n readonly runtimeRole?: string\n}\n\nexport async function runAuthMigrations(\n db: NodePgDatabase,\n opts: RunAuthMigrationsOptions = {},\n): Promise<void> {\n for (const migration of MIGRATIONS) {\n try {\n if (await migration.isApplied(db)) {\n // Already there — do not issue the statement at all. See the comment\n // above MIGRATION_0001_SCHEMA for why relying on `IF NOT EXISTS` to make\n // it a no-op is not safe under every role.\n continue\n }\n await db.execute(sql.raw(migration.sql))\n } catch (err) {\n // Re-thrown, not swallowed: the caller decides what to do with a failed\n // migration. Naming the statement is what turns a bare \"permission\n // denied for database x\" into something you can actually act on; the\n // `cause` keeps the original Postgres error (code, detail, etc.) intact.\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`auth migration \"${migration.name}\" failed: ${message}`, { cause: err })\n }\n }\n\n if (opts.runtimeRole) {\n await grantRuntimeDefaultPrivileges(db, \"auth\", opts.runtimeRole)\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,YA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