@cubicecho/server-kit 0.9.0 → 0.11.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.
package/skill/boot.md ADDED
@@ -0,0 +1,327 @@
1
+ # Boot and the Express app
2
+
3
+ How a server's `index.ts`, its db client and `createApp` are wired from `/db`, `/http`, `/graphql` and `/lock`.
4
+
5
+ **Contents:** [The db client](#the-db-client) · [index.ts: boot only](#indexts-boot-only) ·
6
+ [http/app.ts: build the app, don't run it](#httpappts-build-the-app-dont-run-it) ·
7
+ [graphql/handler.ts](#graphqlhandlerts) · [Shutdown](#shutdown) · [One process per database](#one-process-per-database) ·
8
+ [Health and static files](#health-and-static-files) · [In a service](#in-a-service)
9
+
10
+ Paths are an app's (`server/src/`, and a `db` workspace). A service is one package with the same folders under `server/`; the `cubicecho-backend` skill's app.md and service.md have the layouts.
11
+
12
+ ## The db client
13
+
14
+ ```ts
15
+ // db/src/index.ts (a service: server/db/client.ts)
16
+ import { connectionOptions } from '@cubicecho/server-kit/db';
17
+ import { POOL_DEFAULTS } from './defaults.ts';
18
+ import { relations } from './relations.ts';
19
+
20
+ const url = process.env.DATABASE_URL ?? '';
21
+ if (url === '') {
22
+ throw new Error('DATABASE_URL is not set. Set it in .env, for example postgres://app:app@localhost:5432/app.');
23
+ }
24
+
25
+ const isProduction = process.env.NODE_ENV === 'production';
26
+ const { drizzle } = await import('drizzle-orm/postgres-js');
27
+
28
+ /** The app's Drizzle client. Doesn't connect until the first query. */
29
+ export const db = drizzle({ connection: { url, ...connectionOptions(url, isProduction) }, relations });
30
+ export type DB = typeof db;
31
+
32
+ /**
33
+ * Closes the pool at shutdown, after the server has drained.
34
+ *
35
+ * @returns Resolves once every connection is closed. Queries still running are cancelled after `closeTimeoutSeconds`.
36
+ */
37
+ export const closeDatabase = (): Promise<void> => db.$client.end({ timeout: POOL_DEFAULTS.closeTimeoutSeconds });
38
+ ```
39
+
40
+ - **`connectionOptions` drops migration notices, and forces TLS in production to a host that is not private.** `requiresSsl` is false for localhost, a dotless name (a compose service), a private address or suffix (`.lan`, `.local`, `.internal`, `.home.arpa`), and a URL with its own `sslmode`. Self-hosters on a NAS must not need certificates.
41
+ - postgres-js doesn't connect until the first query, which is why codegen and Docker builds work with a placeholder `DATABASE_URL`.
42
+ - `POOL_DEFAULTS` (`closeTimeoutSeconds: 5`) is the server's own group (defaults.md). Reaching Postgres is the kit's `DATABASE_DEFAULTS`.
43
+ - Tests don't call `closeDatabase`: each file closes its own PGlite (the `cubicecho-backend` skill's testing.md).
44
+
45
+ ## index.ts: boot only
46
+
47
+ ```ts
48
+ import './core/preflight.ts';
49
+
50
+ import { dirname, join } from 'node:path';
51
+ import { fileURLToPath } from 'node:url';
52
+ import { closeDatabase, db } from '@cubicecho/<app>-db';
53
+ import { createSetupGate, isSetUp, setupNotice } from '@cubicecho/server-kit/auth';
54
+ import { DatabaseBootError, prepareDatabase } from '@cubicecho/server-kit/db';
55
+ import { stopOnSignals } from '@cubicecho/server-kit/http';
56
+ import { migrate } from 'drizzle-orm/postgres-js/migrator';
57
+ import { createAuth } from './auth/better-auth.ts';
58
+ import { appUrl, databaseUrl, dbConnectTimeoutMs, isProduction, oidcConfig, openSetup, port, setupCode } from './core/config.ts';
59
+ import { createAppPubSub } from './graphql/pubsub.ts';
60
+ import { createApp } from './http/app.ts';
61
+
62
+ /** Every interface. The container's port mapping decides who can reach it. */
63
+ const LISTEN_HOST = '0.0.0.0';
64
+
65
+ // Captured first: an open setup closes a fixed time from here (auth.md).
66
+ const startedAt = new Date();
67
+ const __dirname = dirname(fileURLToPath(import.meta.url));
68
+
69
+ // Before migrating, so a server that is too old is refused with nothing changed.
70
+ try {
71
+ await prepareDatabase(db, { url: databaseUrl(), isProduction: isProduction(), connectTimeoutMs: dbConnectTimeoutMs() });
72
+ } catch (error) {
73
+ if (error instanceof DatabaseBootError) {
74
+ console.error(`[db] ${error.message}`);
75
+ process.exit(1);
76
+ }
77
+ throw error;
78
+ }
79
+
80
+ // At boot, so `docker compose up` on a fresh volume is the whole install.
81
+ await migrate(db, { migrationsFolder: join(__dirname, '../../db/drizzle') });
82
+
83
+ const pubsub = createAppPubSub();
84
+ const setupGate = createSetupGate({ code: setupCode(), open: openSetup(), startedAt });
85
+ const auth = createAuth(db, { pinned: oidcConfig(), setupGate });
86
+ // The pairing plugin reads the providers at its first request. This finds a bad table now (sso.md).
87
+ await auth.api.listOidcProviders({ headers: new Headers() });
88
+ const needsSetup = (await isSetUp(auth)) === false;
89
+ const app = createApp({ db, auth, pubsub, staticDir: join(__dirname, '../../app/dist') });
90
+
91
+ const server = app.listen(port(), LISTEN_HOST, () => {
92
+ console.log(`[server] ready at ${appUrl()}`);
93
+ if (needsSetup) {
94
+ // Holds the code when the server made it up. The only place it is written.
95
+ console.log(`[setup] ${setupNotice(setupGate)}`);
96
+ }
97
+ });
98
+ stopOnSignals(server, { after: closeDatabase });
99
+ ```
100
+
101
+ `prepareDatabase`:
102
+
103
+ - **Too old refuses, newer warns.** The minimum is the kit's `MIN_POSTGRES_MAJOR`, 18. Nothing is created or changed on a server before it has been checked.
104
+ - **A server with an extension lists it:** `extensions: ['vector']`. It asks what the server *can* create, since the migration creates it. Compose and CI use an image that ships it (`pgvector/pgvector:pg18`), and PGlite gets it in its constructor in tests.
105
+ - A wrong password is not retried: waiting won't fix config. Only a `DatabaseBootError` is printed as a sentence; anything else is a bug and keeps its stack.
106
+ - `dbConnectTimeoutMs()` falls back to `DATABASE_DEFAULTS.connectTimeoutMs` when `DB_CONNECT_TIMEOUT_MS` is unset.
107
+ - Preflight checks configuration only. Postgres coming up after the app is normal, which is why reachability is `prepareDatabase`'s job.
108
+
109
+ index.ts has no logic worth a unit test. Everything it wires is a factory that takes its dependencies, and the CI `boot` job (the `cubicecho-backend` skill's deploy.md) is what tests this file.
110
+
111
+ ## http/app.ts: build the app, don't run it
112
+
113
+ `createApp` takes everything it talks to and returns the Express app. It doesn't listen, migrate or start timers, so a test builds the real app against PGlite and drives it over HTTP (testing.md).
114
+
115
+ ```ts
116
+ import type { DB } from '@cubicecho/<app>-db';
117
+ import { createRateLimiter, type RateLimiter } from '@cubicecho/server-kit/auth';
118
+ import { checkHealth, createStaticHandler, HTTP_DEFAULTS, HttpStatus, mountAuthRedirects } from '@cubicecho/server-kit/http';
119
+ import express, { type Express } from 'express';
120
+ import type { Auth } from '../auth/better-auth.ts';
121
+ import { appUrl, serverUrl, trustProxy, version } from '../core/config.ts';
122
+ import { createGraphQLHandler } from '../graphql/handler.ts';
123
+ import { type AppPubSub, createAppPubSub } from '../graphql/pubsub.ts';
124
+
125
+ /** What the app talks to. Tests pass PGlite and a test auth. */
126
+ export interface AppDeps {
127
+ db: DB;
128
+ auth: Auth;
129
+ /**
130
+ * Subscription bus. Pass it when background work publishes too.
131
+ * @defaultValue `createAppPubSub()`
132
+ */
133
+ pubsub?: AppPubSub;
134
+ /**
135
+ * Sign-in throttle. Tests pass a tighter one.
136
+ * @defaultValue `createRateLimiter()`
137
+ */
138
+ limiter?: RateLimiter;
139
+ /** The built SPA's directory. Left out in tests. */
140
+ staticDir?: string;
141
+ }
142
+
143
+ /**
144
+ * Builds the Express app: /graphql, /healthz, the OIDC redirects and the SPA.
145
+ *
146
+ * @param deps - What the app talks to.
147
+ * @returns The app, not listening.
148
+ */
149
+ export function createApp({ db, auth, pubsub = createAppPubSub(), limiter = createRateLimiter(), staticDir }: AppDeps): Express {
150
+ const app = express();
151
+ // Which proxy hops may set X-Forwarded-For. `req.ip` feeds the rate limiter.
152
+ app.set('trust proxy', trustProxy());
153
+ const graphql = createGraphQLHandler({ db, auth, pubsub, limiter });
154
+
155
+ // Yoga reads a body Express already parsed, so this is where the size cap goes. Over it: 413.
156
+ app.use(graphql.graphqlEndpoint, express.json({ limit: HTTP_DEFAULTS.bodyLimit }));
157
+ // `all`, not `use`: a mounted `use` strips the path, and Yoga matches graphqlEndpoint itself.
158
+ app.all(graphql.graphqlEndpoint, (req, res) => graphql(req, res));
159
+ // Before the static handler, whose SPA fallback would answer 200 while the database is down.
160
+ app.get('/healthz', async (_req, res) => {
161
+ const health = await checkHealth(db, version());
162
+ const status = health.ok ? HttpStatus.Ok : HttpStatus.ServiceUnavailable;
163
+ res.status(status).json(health);
164
+ });
165
+ // Always, because a provider can be paired while the server runs (sso.md).
166
+ mountAuthRedirects(app, { auth, serverUrl: serverUrl(), appUrl: appUrl() });
167
+ if (staticDir !== undefined) {
168
+ app.use(createStaticHandler(staticDir));
169
+ }
170
+ return app;
171
+ }
172
+ ```
173
+
174
+ - `express.json` only parses `application/json`, which is what every client sends. Don't add parsers for other types. Uploads get their own route with their own limit.
175
+ - **Never a bare `express.json()`**: its 100 kB default is an accident, not a decision. `/mcp` sits behind the same `HTTP_DEFAULTS.bodyLimit` (mcp.md).
176
+ - **CORS:** the SPA is same-origin in production, so leave `cors()` out. A separate origin gets `cors({ origin: [appUrl()] })`. Replace any bare `cors()` you find.
177
+
178
+ ## graphql/handler.ts
179
+
180
+ ```ts
181
+ import { graphqlLogger, REQUEST_ID, useIntrospectionGate, useOperationLimits } from '@cubicecho/server-kit/graphql';
182
+ import type { Request } from 'express';
183
+ import { createYoga } from 'graphql-yoga';
184
+ import { isProduction } from '../core/config.ts';
185
+ import { type Context, type ContextDeps, createContextFactory } from '../core/context.ts';
186
+ import { createSchema } from './build-schema.ts';
187
+
188
+ /** What Express hands Yoga alongside the fetch Request. */
189
+ interface ServerContext {
190
+ /** The Express request. Absent when a test calls `yoga.fetch`. */
191
+ req?: Request;
192
+ }
193
+
194
+ /**
195
+ * Builds the Yoga handler for /graphql.
196
+ *
197
+ * @param deps - The database, auth, subscription bus and sign-in throttle.
198
+ * @returns The Yoga instance, callable as Express middleware.
199
+ */
200
+ export function createGraphQLHandler(deps: ContextDeps) {
201
+ const { schema } = createSchema(deps.db);
202
+ const contextFor = createContextFactory(deps);
203
+ return createYoga<ServerContext, Context>({
204
+ schema,
205
+ graphqlEndpoint: '/graphql',
206
+ graphiql: isProduction() === false,
207
+ // Masked errors are logged here with their real cause (graphql.md).
208
+ logging: graphqlLogger,
209
+ requestId: REQUEST_ID,
210
+ // Only a person introspects in production (graphql.md, "Introspection").
211
+ plugins: [useOperationLimits(), ...(isProduction() ? [useIntrospectionGate<ServerContext>({ allow: isPerson(contextFor) })] : [])],
212
+ // Express's view of the client address, which honors `trust proxy`.
213
+ context: ({ request, req }) => contextFor(request.headers, req?.ip),
214
+ });
215
+ }
216
+ ```
217
+
218
+ - **Every `createYoga` passes `logging: graphqlLogger` and `requestId: REQUEST_ID`.** Yoga 6 has no `YogaLogger` type, and the object of four functions Yoga 5 took now fails every request with "log.child is not a function". Yoga also trusts an incoming `x-request-id` unless told not to.
219
+ - `createGraphQLHandler` leaves its return type to inference: Yoga's server type is long, and nothing outside app.ts names it.
220
+ - `createContextFactory` and `Context` are in core/context.ts (auth.md, "Context").
221
+ - `isPerson(contextFor)` is the server's own: it returns `(request, { req }) => Promise<boolean>`, reading the caller with `contextFor(request.headers, req?.ip)` and answering whether it is a person. It returns `false` for a caller the factory refuses, rather than throwing.
222
+
223
+ ## Shutdown
224
+
225
+ `docker stop`, a redeploy and Ctrl-C all send a signal. Without a handler, Node ignores SIGTERM as PID 1, Docker waits its 10 s and kills it, and whatever was in flight is cut off. `stopOnSignals` stops accepting connections, lets running requests finish, closes what they used, and exits within `HTTP_DEFAULTS.shutdownDeadlineSeconds` (8). A second signal exits at once.
226
+
227
+ - `before` stops starting new work (timers, queue pollers) as soon as the signal arrives. `after` closes what requests were using (MCP sessions, the pool) once the server has drained. A third argument overrides the two timings.
228
+ - **`cutOff` ends what never finishes on its own.** An SSE subscription stays open until the client leaves, so the drain would run to its deadline and cut the socket, and the client would read a reset. `cutOff` runs at the drain deadline and is awaited before the connections are cut: end every open stream there (complete the run bus's watchers, return the pubsub iterators), so each client reads a clean end and reconnects. A server with subscriptions passes it. If it throws, the server still closes, and the error is raised after.
229
+ - Keep the handle `app.listen` returns. It is the only way to drain.
230
+ - The Dockerfile's `CMD` stays in exec form, `["node", "server/src/index.ts"]`, so node gets the signal. `npm start` or `sh -c` swallow it.
231
+ - Background work that `before` stops must tolerate being cut off mid-item: its queue lives in a table, so the next boot resumes it.
232
+ - Register it before any long boot-time work (draining a queue), so a stop during that work still shuts down cleanly.
233
+ - A server that announces itself closes its `createLanAdvertiser` first in `before`, so the goodbye goes out while it still answers (discovery.md).
234
+
235
+ ## One process per database
236
+
237
+ A server that keeps what it serves in memory (a cache it never re-reads, a scheduler's timers, a run bus) is wrong the moment a second copy writes to the same database. `holdPostgresLock` from `/lock` makes it the only one: a Postgres advisory lock held on a connection of its own. A server that only answers requests from the database doesn't need it.
238
+
239
+ ```ts
240
+ import { DatabaseLockError, holdPostgresLock } from '@cubicecho/server-kit/lock';
241
+ import pg from 'pg';
242
+
243
+ // A client of its own, never one from a pool, with keepAlive so a dead connection is noticed.
244
+ const session = new pg.Client({ connectionString: databaseUrl(), keepAlive: true, keepAliveInitialDelayMillis: 10_000 });
245
+ const releaseLock = await holdPostgresLock(session, {
246
+ app: '<app>',
247
+ // The same in every version, or two versions run side by side.
248
+ key: '<app>',
249
+ advice: 'Stop the other one first.',
250
+ onLost: (error) => {
251
+ console.error(`[db] ${error.message}`);
252
+ process.exit(1);
253
+ },
254
+ });
255
+ ```
256
+
257
+ - **Take it after `prepareDatabase` and before `migrate()`**, so two copies starting together never both migrate.
258
+ - **`onLost` ends the process at once, writing nothing more**: another process may hold the lock by then. Run the server under something that restarts it (compose's `restart: unless-stopped`).
259
+ - **Call it inside the same `try` as `prepareDatabase`.** `DatabaseLockError` is a `DatabaseBootError`, so that `catch` prints it as a sentence and exits. Its `code` is `DATABASE_IN_USE` or `DATABASE_LOCK_LOST`.
260
+ - A restarted container can start before the old one has stopped, so it waits `LOCK_DEFAULTS.waitMs` (15 s) for the holder to let go, and says who holds it.
261
+ - **Shutdown releases it last:** `after` closes the pool, then calls `releaseLock()`, so the last write is in before another process may start.
262
+ - The lock's connection is `pg`, which the server installs; the kit needs no peer for it. After a silent network loss Postgres holds the old connection's lock until it notices, so a restart is refused until then.
263
+
264
+ ## Health and static files
265
+
266
+ - **`/healthz` answers `{ ok, version }` and never says why it is not ok.** Anyone may ask, and a driver's error names hosts. `checkHealth` round-trips to Postgres and logs the error with its cause, so monitoring that wants the reason reads the log.
267
+ - `createStaticHandler` serves the built app: `/assets/` and `/_expo/` files are kept for a year, and one that is gone is a 404. Any other path that is not a file is `index.html`.
268
+ - **It answers every path**, so `/healthz`, `/mcp` and `mountAuthRedirects` are mounted before it.
269
+
270
+ ## In a service
271
+
272
+ One package, and `/mcp` beside `/graphql`. `createApp` returns the MCP handler too, so shutdown can close its sessions:
273
+
274
+ ```ts
275
+ export function createApp({ dist, limiter = createRateLimiter(), ...deps }: AppDeps): BuiltApp {
276
+ const app = express();
277
+ app.set('trust proxy', trustProxy());
278
+ // Already wrapped by applyPermissions. One instance, shared with /mcp.
279
+ const { schema } = createSchema(deps.db);
280
+ const contextFor = createContextFactory({ ...deps, limiter });
281
+ const yoga = createYoga<{ req?: express.Request }, Context>({
282
+ schema,
283
+ graphqlEndpoint: '/graphql',
284
+ graphiql: isProduction() === false,
285
+ logging: graphqlLogger,
286
+ requestId: REQUEST_ID,
287
+ plugins: [useOperationLimits(), ...(isProduction() ? [useIntrospectionGate({ allow: isPerson(contextFor) })] : [])],
288
+ context: ({ request, req }) => contextFor(request.headers, req?.ip),
289
+ });
290
+ const mcp = createMcpHandler(schema, contextFor);
291
+
292
+ // One cap for both doors.
293
+ const json = express.json({ limit: HTTP_DEFAULTS.bodyLimit });
294
+ app.use(yoga.graphqlEndpoint, json);
295
+ app.all(yoga.graphqlEndpoint, (req, res) => yoga(req, res));
296
+ app.all('/mcp', json, mcp);
297
+ mountAuthRedirects(app, { auth: deps.auth, serverUrl: serverUrl(), appUrl: appUrl() });
298
+ app.get('/healthz', async (_req, res) => {
299
+ const health = await checkHealth(deps.db, version());
300
+ res.status(health.ok ? HttpStatus.Ok : HttpStatus.ServiceUnavailable).json(health);
301
+ });
302
+ if (dist !== undefined) {
303
+ app.use(createStaticHandler(dist));
304
+ }
305
+ return { app, mcp };
306
+ }
307
+ ```
308
+
309
+ ```ts
310
+ // index.ts, after prepareDatabase, migrate and createAuth as above
311
+ const runs = createRunBus();
312
+ const { app, mcp } = createApp({ db, auth, runs, dist: path.join(ROOT, 'dist') });
313
+ const server = app.listen(port(), () => console.log(`[server] ready at http://localhost:${port()}/graphql`));
314
+
315
+ // Background work starts after listen. Its queues live in tables, so a restart resumes them.
316
+ const scheduler = startScheduler({ db, runs });
317
+ stopOnSignals(server, {
318
+ before: () => scheduler.stop(),
319
+ after: async () => {
320
+ await mcp.close();
321
+ await closeDatabase();
322
+ },
323
+ });
324
+ await drainQueue({ db, runs });
325
+ ```
326
+
327
+ The run bus, the scheduler and `createMcpHandler` are the server's own (the `cubicecho-backend` skill's realtime.md, and mcp.md here).
@@ -0,0 +1,103 @@
1
+ # Tables, ids and Postgres
2
+
3
+ What `/columns` and `/db` give a server's Drizzle models, which rows get an id, and why Postgres 18 is the minimum.
4
+
5
+ **Contents:** [The columns](#the-columns) · [Ids](#ids) · [Singletons](#singletons) ·
6
+ [better-auth tables](#better-auth-tables) · [Postgres 18 and PGlite 0.5](#postgres-18-and-pglite-05) ·
7
+ [The driver](#the-driver)
8
+
9
+ Naming, foreign keys, enums, relations, migrations and querying are the `cubicecho-backend` skill's database.md.
10
+
11
+ ## The columns
12
+
13
+ ```ts
14
+ import { id, moment, timestamps } from '@cubicecho/server-kit/columns';
15
+ import { index, pgTable, text, uuid } from 'drizzle-orm/pg-core';
16
+ import { projects } from './projects.ts';
17
+ import { users } from './users.ts';
18
+
19
+ /** A user's todo item. */
20
+ export const todos = pgTable(
21
+ 'todos',
22
+ {
23
+ id: id(),
24
+ userId: uuid('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
25
+ projectId: uuid('project_id').notNull().references(() => projects.id, { onDelete: 'cascade' }),
26
+ title: text('title').notNull(),
27
+ /** null while open. */
28
+ completedAt: moment('completed_at'),
29
+ ...timestamps(),
30
+ },
31
+ (table) => [index('idx_todos_user_id').on(table.userId), index('idx_todos_project_id').on(table.projectId)],
32
+ );
33
+ ```
34
+
35
+ - **`id()`, `moment()`, `timestamps()` and `singleton()` are never written out by hand.** `id()` is a UUID primary key defaulting to the database's `uuidv7()`; `moment()` is a timestamp with its time zone; `timestamps()` is `createdAt` and `updatedAt` on every mutable table.
36
+ - Because `id()` is a column default, it also covers rows written by raw SQL and backfills.
37
+ - `checkSchemaConventions` (testing.md) checks ids, join tables, time zones and foreign-key indexes from these tables, with no database.
38
+
39
+ ## Ids
40
+
41
+ **Every table that holds an entity has an `id` of its own, a UUIDv7 primary key.** That includes rows nobody thinks of as entities: sessions, accounts, verifications, API keys, events, log rows. A natural key (an email, a slug, a provider's subject) gets a unique index beside the id and is never the primary key, because natural keys change and an id doesn't.
42
+
43
+ | Table | Its key |
44
+ |---|---|
45
+ | An entity | `id()` |
46
+ | One-to-one with another row (a user's settings) | `id()`, and a unique index on the reference. The parent's id is never the primary key |
47
+ | One row per instance | `id()`, and a `singleton()` column that blocks a second row |
48
+ | A join table: it only ever links two entities | The foreign keys together, no `id` |
49
+ | A row that links entities and also makes sense on its own | `id()`, and a unique index on the pair |
50
+ | Derived data | Its natural key, no `id` |
51
+
52
+ - **A join table has no id only while it is always just a join.** `project_labels` says a project has a label: `primaryKey({ columns: [table.projectId, table.labelId] })`, and an index on the second column. `group_members` has a start date and a role, so it is an entity. If you can name the thing without naming its two ends, or another table would point at it, it has an id. An existing join table with an id keeps it, since the API exposes it.
53
+ - **Derived data is the one exception, and all three must hold:** code or a trigger writes it from other tables and a user never does, nothing references its rows, and it isn't in the GraphQL schema. Telos's `change_log` is one. **An append-only log, where each row is an event that stays, is an entity.** A derived table is excused in the conventions test with its reason.
54
+ - **Why v7:** its first 48 bits are the time, so new rows land at the end of the primary-key index. A v4 id lands anywhere, which splits pages and reads cold ones on every insert.
55
+ - **`defaultRandom()` and `randomUUID()` are v4: neither makes a row's id.** On an existing table, changing the default is an ordinary migration and touches no row. v4 and v7 ids live in one `uuid` column, so never rewrite existing ids.
56
+ - **A client may send the id** of a row it shows before the server answers, made with cubeui's `newId()` (`@cubeui/new-id`), which is UUIDv7 too. Never trust one as proof of anything: tenancy checks it like any other argument.
57
+ - **An id is not a secret.** A v7 id gives away when its row was made. Anything that grants access by being known (a session token, a share link, an API key) is a separate random value in its own column, from `randomBytes` or better-auth.
58
+ - Old services' tables with text ids keep them (`legacyIds` in the conventions test). New tables use `id()`.
59
+
60
+ ## Singletons
61
+
62
+ ```ts
63
+ import { id, singleton, singletonRules } from '@cubicecho/server-kit/columns';
64
+
65
+ export const instanceSettings = pgTable(
66
+ 'instance_settings',
67
+ { id: id(), singleton: singleton(), runLimit: integer('run_limit').notNull().default(2) },
68
+ (table) => singletonRules('instance_settings', table.singleton),
69
+ );
70
+ ```
71
+
72
+ **An upsert targets `singleton`, never `id`**: each insert has a new id, so it never conflicts on it, and the unique index refuses the row.
73
+
74
+ ```ts
75
+ .onConflictDoUpdate({ target: instanceSettings.singleton, set: { runLimit: 5 } })
76
+ ```
77
+
78
+ An older singleton with a fixed text id (`'instance'`) is converted by a migration that drops its check and key and adds the two columns. The row keeps its settings.
79
+
80
+ ## better-auth tables
81
+
82
+ Declare `users`, `sessions`, `accounts`, `verifications`, `sso_providers` (sso.md) and `apikeys` (with the api-key plugin) as ordinary Drizzle tables in `models/`, each with `id()`. They are generated and migrated like everything else.
83
+
84
+ - `authPreset` sets `generateId: 'uuid'`, which on Postgres makes better-auth leave the id out of the insert, so the column default fills it. Don't add a generator function.
85
+ - better-auth gives some `verifications` rows an id made from a hash, so a value can be spent once. Those are not v7; leave them.
86
+ - Pass the tables to the preset explicitly (auth.md): the rc drizzle instance is keyed by relations, so the adapter can't discover them.
87
+ - None of them is in the GraphQL schema: they are `AUTH_TABLES` and `SERVER_TABLES` in tenancy.ts (the `cubicecho-backend` skill's schema.md).
88
+
89
+ ## Postgres 18 and PGlite 0.5
90
+
91
+ **Postgres 18 or later in production, PGlite ^0.5 in tests** (PGlite 0.5 is Postgres 18). Both have `uuidv7()` built in; on older ones `pushSchema` and migrations fail with "function uuidv7() does not exist".
92
+
93
+ - `prepareDatabase` refuses an older server before any migration runs (boot.md), so a migration that needs 18 never reaches 17.
94
+ - **One major per repo:** both compose files and CI agree, and PGlite is never behind them. `checkPostgresVersion` holds it (testing.md).
95
+ - **A server still on 17 adopts all of this in one release, announced as breaking:** the move to 18, `prepareDatabase`, `id()` as the default, and the two schema tests. Moving the data volume is an operator's job with a procedure of its own (the `cubicecho-backend` skill's deploy.md, "Moving to Postgres 18"). Until that release, new tables use `uuid('id').primaryKey().$defaultFn(() => randomUUIDv7())` from `node:crypto`, which Drizzle runs and raw SQL does not, and `schemaProblems` lists what the conventions test will want.
96
+
97
+ ## The driver
98
+
99
+ `postgres` (postgres-js) ^4 for `/db`, in apps and services alike. ^3.4 is still accepted while a server moves, but it ends the process when a connection drops while a transaction is running a query.
100
+
101
+ **A service still on `pg` moves to postgres-js when it adopts the kit.** Until then its pool has an `error` listener, `pool.on('error', (error) => console.warn(`[db] an idle connection dropped: ${error.message}`))`: `pg` emits an idle connection's error there, and Node ends a process that doesn't listen, so a Postgres restart would crash it. Never hold an advisory lock on a pool connection: take it with `/lock`'s `holdPostgresLock` on a `pg.Client` of its own (boot.md, "One process per database").
102
+
103
+ **Both the db and server packages depend on the kit, so npm hoists it to the root, and what its entries import must be there too.** When something else holds an older `zod` at the root (Expo does), npm nests the auth packages under `server/`, and the server fails at import with "Cannot find package '@cubicecho/better-auth-oidc-pairing'". Make `zod` 4 a root dependency beside `drizzle-orm`, and check that `server/node_modules` is empty.
@@ -0,0 +1,72 @@
1
+ # Tunable values: the kit's groups and the server's
2
+
3
+ Which `<CONCEPT>_DEFAULTS` groups the kit owns, which a server keeps in its own `defaults.ts`, and how one is overridden.
4
+
5
+ Every limit, timeout, size and lifetime a server uses is a member of a read-only group (`coding-standards` P22; the shape is in `cubicecho_typescript`, "Defaults"). No module states a tunable number of its own. A server's groups are in `server/src/core/defaults.ts` (an app's `POOL_DEFAULTS` is in its db package); unit conversions are in `core/consts.ts`.
6
+
7
+ ## The groups
8
+
9
+ | Group | Tunes | Read by | Owned by |
10
+ |---|---|---|---|
11
+ | `DATABASE_DEFAULTS` | connect timeout, retry backoff | `prepareDatabase`, config.ts | kit, `/db` |
12
+ | `HTTP_DEFAULTS` | the body cap, the shutdown timings, how long hashed files are cached | app.ts, `stopOnSignals`, `createStaticHandler` | kit, `/http` |
13
+ | `LOCK_DEFAULTS` | how long to wait for another process to let go of the lock, and how often to look | `holdPostgresLock` | kit, `/lock` |
14
+ | `AUTH_DEFAULTS` | session and link lifetimes | `authPreset`, `signInPlugins` | kit, `/auth` |
15
+ | `SETUP_DEFAULTS` | how long an open setup lasts, the shortest setup code | `createSetupGate`, `setupProblem` | kit, `/auth` |
16
+ | `RATE_LIMIT_DEFAULTS` | the sign-in throttle | `createRateLimiter` | kit, `/auth` |
17
+ | `OPERATION_LIMIT_DEFAULTS` | page sizes, depth, aliases, cost | build-schema.ts, `useOperationLimits` | kit, `/graphql` |
18
+ | `MCP_DEFAULTS` | selection depth, tool schema budgets | `toolOptions`, `checkMcpBudget` | kit, `/mcp` |
19
+ | `SERVER_DEFAULTS` | the port, which proxy hops are trusted | config.ts | server |
20
+ | `SECRET_DEFAULTS` | the shortest secret, whether setup is open | config.ts, preflight.ts | server |
21
+ | `OIDC_DEFAULTS` | what the environment's provider is called, how its secret is sent | config.ts | server |
22
+ | `POOL_DEFAULTS` | close timeout | the db client | server |
23
+ | `<TABLE>_DEFAULTS` | how long each string column may be | the zod schemas (graphql.md) | server |
24
+ | `<DOMAIN>_DEFAULTS` | a scheduler's poll interval, a runner's concurrency | that folder | server |
25
+
26
+ **A group the kit owns is never copied into the server.** The server passes an override where the thing is built (`useOperationLimits({ maxCost })`, `createRateLimiter({ maxAttempts })`, `toolOptions({ selectionDepth })`, `prepareDatabase(db, { connectTimeoutMs })`), and the override's value is a member of a group of the server's own, with the reason in its doc comment.
27
+
28
+ ## The server's own
29
+
30
+ ```ts
31
+ // core/defaults.ts. Every value someone might tune, as plain data. Nothing here computes, reads the environment or imports.
32
+
33
+ /** Where this server listens, and whom it believes. */
34
+ export interface ServerSettings {
35
+ /** The port to listen on. `PORT` overrides it. */
36
+ port: number;
37
+ /** Express `trust proxy`: which hops may set X-Forwarded-For. False trusts none. `TRUST_PROXY` overrides it. */
38
+ trustProxy: boolean | number | string;
39
+ }
40
+
41
+ export const SERVER_DEFAULTS: Readonly<ServerSettings> = Object.freeze({ port: 3000, trustProxy: false });
42
+
43
+ /** Who may get in, and for how long a new instance may be set up. */
44
+ export interface SecretSettings {
45
+ /** Shortest signing secret production accepts, in characters. `openssl rand -hex 32` gives twice this. */
46
+ minSecretLength: number;
47
+ /** Whether anyone who can reach an instance with no account may set it up (auth.md). `OPEN_SETUP` overrides it. */
48
+ openSetup: boolean;
49
+ }
50
+
51
+ export const SECRET_DEFAULTS: Readonly<SecretSettings> = Object.freeze({ minSecretLength: 32, openSetup: false });
52
+
53
+ /** The environment's OIDC provider (sso.md). Pairing's own settings are the package's `PAIRING_DEFAULTS`. */
54
+ export interface OidcSettings {
55
+ /** What its button says. `OIDC_NAME` overrides it. */
56
+ providerName: string;
57
+ /** How its client secret is sent. The spec's default. `OIDC_CLIENT_AUTH` overrides it. */
58
+ clientAuth: 'client_secret_basic' | 'client_secret_post';
59
+ }
60
+
61
+ export const OIDC_DEFAULTS: Readonly<OidcSettings> = Object.freeze({ providerName: 'SSO', clientAuth: 'client_secret_basic' });
62
+ ```
63
+
64
+ - **Every group is read-only**: typed `Readonly<…Settings>` and frozen, so nothing changes a default while the process runs, and a test passes an override instead of editing one.
65
+ - **These have an env var today:** `PORT`, `TRUST_PROXY`, `OPEN_SETUP`, `DB_CONNECT_TIMEOUT_MS`, `OIDC_NAME` and `OIDC_CLIENT_AUTH`, each through a getter in config.ts that falls back to the member (the `cubicecho-backend` skill's deploy.md). Changing a member means changing its comment in `.env.example` in the same commit.
66
+ - **Giving another group an outside source is a feature, decided one group at a time.** The limit groups are security bounds: don't add an env var for one in passing.
67
+ - **These stay where they are, because nobody tunes them:** the unit conversions, `DEV_SECRET` and `PLACEHOLDER_SECRET` (auth.md), `LISTEN_HOST` (boot.md), and the values a test makes up.
68
+ - **One file until it is too long to scan.** Then ask what should happen next, most likely a `defaults/` folder with one module per group.
69
+
70
+ ## core/consts.ts and HttpStatus
71
+
72
+ Unit conversions are facts (`MS_PER_SECOND`, `SECONDS_PER_MINUTE`, `SECONDS_PER_DAY`), so they are in `consts.ts`. HTTP statuses are a vocabulary, and it is the kit's: `HttpStatus` from `/http`. A status the kit lacks is added to the kit. An older repo with both in `wire.ts` moves the units to `consts.ts`, imports `HttpStatus`, and deletes the file.
@@ -0,0 +1,130 @@
1
+ # Discovery on the LAN
2
+
3
+ How a server says what it serves and announces itself on the network: its GraphQL API in `/.well-known/graphql-services.json` and as `_graphql._tcp`, and its MCP door in the AI Catalog and as `_mcp._tcp`. A server that looks for others on the network (symphony's upstreams, ai-router's MCP servers) does that itself; the end of this file says how.
4
+
5
+ **Contents:** [What the kit does and the libraries do](#what-the-kit-does-and-the-libraries-do) · [discovery/endpoints.ts](#discoveryendpointsts) ·
6
+ [Serving the documents](#serving-the-documents) · [Announcing](#announcing) · [The switches](#the-switches) ·
7
+ [Looking for others](#looking-for-others) · [Docker](#docker) · [Testing it](#testing-it)
8
+
9
+ ## What the kit does and the libraries do
10
+
11
+ Three libraries do the work, and the kit only names things the way every cubicecho server names them:
12
+
13
+ | Package | Does |
14
+ |---|---|
15
+ | `@cubicecho/discovery-core` | Serving and fetching the documents, and the one mDNS responder a process shares. Never imported by a server |
16
+ | `@cubicecho/graphql-mdns-discovery` | The GraphQL services document and `_graphql._tcp` |
17
+ | `@cubicecho/mcp-discovery` | MCP Server Cards, the AI Catalog and `_mcp._tcp` |
18
+
19
+ | Kit export | Entry | Builds |
20
+ |---|---|---|
21
+ | `discoveryNames({ app, title })` | `/discovery` | Every name the server advertises under: `AI Router on nas`, `io.github.cubicecho.ai-router.nas/<endpoint>`, `urn:air` publisher `nas.ai-router`, the GitHub link |
22
+ | `graphqlEndpoint(names, …)` | `/discovery` | The server's entry in its GraphQL services document |
23
+ | `mcpEndpoint(names, …)` | `/mcp` | Its MCP door's AI Catalog entry and Server Card |
24
+ | `createLanAdvertiser(…)` | `/discovery` | One `sync()` and one `close()` for both announcements |
25
+
26
+ **Install** `@cubicecho/graphql-mdns-discovery` for `/discovery`, `@cubicecho/mcp-discovery` too when the server has `/mcp`, and `bonjour-service` when it announces or looks. A server without an MCP door never loads mcp-discovery: the advertiser imports it only when given an `mcpPath`. `bonjour-service` is loaded on the first announcement.
27
+
28
+ **One copy of discovery-core.** Both libraries depend on it. Its errors are `instanceof`-checked across the two, and its responder is one per copy: two copies are two responders, and stopping one sends a goodbye that takes the other's address records with it. `npm ls @cubicecho/discovery-core` shows one version, deduped.
29
+
30
+ ## discovery/endpoints.ts
31
+
32
+ ```ts
33
+ import { discoveryNames, graphqlEndpoint } from '@cubicecho/server-kit/discovery';
34
+ import { mcpEndpoint } from '@cubicecho/server-kit/mcp';
35
+ import { version } from '../core/config.ts';
36
+
37
+ /** Every name the server advertises under. Read once: the hostname doesn't change. */
38
+ export const names = discoveryNames({ app: 'ai-router', title: 'AI Router' });
39
+
40
+ /** The GraphQL API, in /.well-known/graphql-services.json. */
41
+ export const graphqlApi = graphqlEndpoint(names, {
42
+ version: version(),
43
+ auth: 'Bearer <session token, or a user key>',
44
+ });
45
+
46
+ /** The MCP door, in the AI Catalog. */
47
+ export const mcpDoor = mcpEndpoint(names, {
48
+ endpoint: 'agents',
49
+ version: version(),
50
+ description: "Agents as MCP tools: one per agent a workspace key's workspace may run.",
51
+ auth: 'Bearer <workspace key>: an air_… key from a workspace in the router',
52
+ });
53
+ ```
54
+
55
+ - **`app` is the repository's name** and `title` what people call it. Both go into names other machines keep, so neither changes once a server has shipped.
56
+ - **`endpoint` is the door's stable name**, the last part of its card name and `urn:air` id. Never a path, a port or a version.
57
+ - **What's public names no data.** The documents are served to anyone, so a description says what kind of thing the door is, never which agents or tables are behind it. `auth` says what goes in the header; the value is never in any document.
58
+ - `graphqlEndpoint`'s `fields` adds what only this server has, per request: its subscriptions (`{ url: `${origin.replace(/^http/, 'ws')}/graphql`, protocol: 'graphql-ws' }`), or a `schemaUrl`. It wins over the rest.
59
+ - A server with several MCP doors or a door per record (mcp-router) builds its catalog entries itself, with `names.serviceName(endpoint)` and `names.publisher` so they read the same.
60
+
61
+ ## Serving the documents
62
+
63
+ In `createApp`, at the root and before any auth guard or the static handler:
64
+
65
+ ```ts
66
+ import { graphqlDiscoveryMiddleware } from '@cubicecho/graphql-mdns-discovery';
67
+ import { discoveryMiddleware } from '@cubicecho/mcp-discovery';
68
+
69
+ app.use(graphqlDiscoveryMiddleware(() => [graphqlApi]));
70
+ app.use(discoveryMiddleware(() => [mcpDoor]));
71
+ ```
72
+
73
+ - **Served whether or not the server announces.** They are public and cost nothing, and a client that was given the address reads them without mDNS.
74
+ - Each answers only its own paths and passes everything else on, in either order.
75
+ - The URLs in them come from the request's `Host`, so a client on the LAN is told LAN addresses. Behind a proxy that ends TLS, the origin reads as `http`: return paths instead (the library's serving.md).
76
+
77
+ ## Announcing
78
+
79
+ In index.ts, after the app is built:
80
+
81
+ ```ts
82
+ import { createLanAdvertiser } from '@cubicecho/server-kit/discovery';
83
+ import { names } from './discovery/endpoints.ts';
84
+
85
+ const advertiser = createLanAdvertiser({
86
+ isWanted: mdnsAdvertise,
87
+ options: () => ({ name: names.instance, port: port(), mcpPath: '/mcp' }),
88
+ log: (message) => console.log(`[discovery] ${message}`),
89
+ });
90
+ const server = app.listen(port(), LISTEN_HOST, () => {
91
+ // After listen, so a watcher that finds the announcement can already read the documents.
92
+ void advertiser.sync();
93
+ });
94
+ stopOnSignals(server, {
95
+ // First, so the goodbye goes out while the server still answers.
96
+ before: () => advertiser.close(),
97
+ after: closeDatabase,
98
+ });
99
+ ```
100
+
101
+ - **`_graphql._tcp` always, `_mcp._tcp` with an `mcpPath`,** under one instance name and port. `graphqlPath` is `/graphql` unless given.
102
+ - **One that fails is logged and the server carries on.** The name taken, multicast blocked: discovery is never a reason not to serve. The next `sync()` tries again.
103
+ - **`options` is read when an announcement starts**, so a changed port takes effect on the next one.
104
+ - Listen on the LAN (`0.0.0.0`), not only localhost, or what is announced can't be reached.
105
+
106
+ ## The switches
107
+
108
+ The kit reads no environment. Whether the server announces is the server's own switch, passed as `isWanted`, wherever it keeps it: an env flag read in core/config.ts, a row in its settings table, a constant.
109
+
110
+ - **Off unless the server turns it on.** mDNS needs the host's network (Docker below), and a server that is never looked for has no reason to multicast.
111
+ - **It is read on every `sync()`.** A switch the server keeps in its database calls `advertiser.sync()` after saving it, and the announcement starts or stops without a restart.
112
+ - **Announcing and looking are two switches.** One says the server may be found, the other that it trusts the network enough to suggest what it finds.
113
+
114
+ ## Looking for others
115
+
116
+ What a server does with what it finds is its own: the kit has no part in it. Use the libraries' watchers, `watchGraphqlServices` from `@cubicecho/graphql-mdns-discovery/mdns` and `watchServers` from `@cubicecho/mcp-discovery/mdns`:
117
+
118
+ - Import them with `await import(…)` behind the server's own switch, so a server that doesn't look never loads them.
119
+ - Skip `names.instance`: a server that announces sees itself.
120
+ - **A found server is a suggestion.** Anything on the network can announce. A person adds it, or the server's own rule allows it, never the name alone.
121
+ - Stop the watch in `stopOnSignals`'s `before`, beside `advertiser.close()`.
122
+
123
+ ## Docker
124
+
125
+ Docker's default bridge network drops multicast. A container that announces or looks runs with `network_mode: host`, and the switch stays off in any compose file that doesn't.
126
+
127
+ ## Testing it
128
+
129
+ - **The documents**, in `http/app.test.ts` (testing.md): the services document lists `names.serviceName('graphql')` with the request's origin, and the card names no data and holds no secret. Read the card through the catalog's `url`.
130
+ - **The announcement**, without multicast: `createLanAdvertiser`'s `announce` takes a function per type, which a test records. Real multicast is the libraries' to test, and is skipped when `CI=true`.