@cubicecho/server-kit 0.8.1 → 0.10.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/SKILL.md ADDED
@@ -0,0 +1,84 @@
1
+ ---
2
+ name: cubicecho-server-kit
3
+ description: How to build, update or review a cubicecho GraphQL server on @cubicecho/server-kit, the shared server code and the one set of versions — which kit entry does which job (/db prepareDatabase and connectionOptions, /columns id() moment() timestamps() singleton(), /auth authPreset signInPlugins setup gate device links throttle, /graphql ErrorCode errors parseOrThrow useOperationLimits useIntrospectionGate graphqlLogger, /http stopOnSignals with its cutOff step checkHealth createStaticHandler mountAuthRedirects, /lock holdPostgresLock, /mcp toolOptions contextFromRequest, /testing checkSchemaConventions checkPostgresVersion checkMcpBudget), how an app wires each one into createApp and index.ts, UUIDv7 ids on Postgres 18, better-auth with OIDC sign-in and provider pairing by Dynamic Client Registration, the defaults groups the kit owns, and moving an existing server onto the kit. Load it whenever you touch a cubicecho backend's boot, database, auth, SSO, errors, limits, MCP door or tests, or the kit itself.
4
+ ---
5
+
6
+ # cubicecho server kit
7
+
8
+ Every cubicecho GraphQL server is built on `@cubicecho/server-kit`. The kit is functions the server calls, not a framework: the server keeps its own `createApp`, schema, auth instance and boot order, and calls the kit for everything two servers would otherwise both write. This skill is how a server uses it.
9
+
10
+ **Load these first**, from the same skills server:
11
+
12
+ - `cubicecho_typescript` and `coding-standards`: the TypeScript, tooling and readability rules. This skill repeats neither.
13
+ - `cubicecho-backend`: what a server is built of that the kit has no part in — the app and service archetypes and their folders, the drizzle-graphql schema and its hooks, Drizzle conventions, realtime, casl permissions, Docker, CI and release, and the PGlite test harness. It is on the skills server as `cubicecho-backend` (`cubicecho/skills/backend/` on the NAS for now). When this skill says "the `cubicecho-backend` skill's X.md", that is where to look.
14
+
15
+ The kit's API reference ships in the package: `node_modules/@cubicecho/server-kit/llms.txt` and `_agents/docs/`. This skill says how the pieces are wired into a server and why; the reference says what each function takes.
16
+
17
+ ## Which file for which job
18
+
19
+ | Task | Entry | Load |
20
+ |---|---|---|
21
+ | `index.ts` and `createApp`: boot order, `prepareDatabase`, `/healthz`, the static handler, the body cap, the Yoga handler, shutdown and its `cutOff` step | `/db`, `/http`, `/graphql` | [boot.md](boot.md) |
22
+ | One process per database: `holdPostgresLock`, for a server that keeps what it serves in memory | `/lock` | [boot.md](boot.md), "One process per database" |
23
+ | Tables: `id()`, `moment()`, `timestamps()`, `singleton()`, which rows get an id, the better-auth tables, `connectionOptions`, Postgres 18 | `/columns`, `/db` | [database.md](database.md) |
24
+ | Sign-in: `authPreset`, `signInPlugins`, sessions, setting up a new instance, device links and recovery, better-auth served as GraphQL, the throttle, API keys, the auth secret | `/auth` | [auth.md](auth.md) |
25
+ | OIDC sign-in and pairing a provider from a setup URL, who may pair, `mountAuthRedirects` | `/auth`, `/http` | [sso.md](sso.md), after auth.md |
26
+ | Errors a client reads, `ErrorCode`, masking and the logger, zod with `parseOrThrow`, page size, depth and cost, who may introspect | `/graphql` | [graphql.md](graphql.md) |
27
+ | The `/mcp` door: `toolOptions`, `contextFromRequest`, `MCP_DEFAULTS`, budgets | `/mcp` | [mcp.md](mcp.md) |
28
+ | A limit, timeout, size or lifetime: the kit's `<CONCEPT>_DEFAULTS` groups and the server's own | all | [defaults.md](defaults.md) |
29
+ | The tests the kit registers, and the tests that hold what a server wires | `/testing` | [testing.md](testing.md) |
30
+ | Putting an existing server on the kit, upgrading the kit, or changing the kit | — | [adopting.md](adopting.md) |
31
+
32
+ A new server needs the `cubicecho-backend` skill's archetype file, then boot, database, auth, sso, graphql, defaults and testing here.
33
+
34
+ ## Versions
35
+
36
+ One set for every server. The kit has the singletons as peers, so npm refuses a server outside these ranges. What only one entry needs is an optional peer that the server installs itself: `postgres` for `/db`; `better-auth`, `@better-auth/sso` and `@cubicecho/better-auth-oidc-pairing` for `/auth`; `@cubicecho/graphql-mcp` for `/mcp`.
37
+
38
+ | Package | Version |
39
+ |---|---|
40
+ | `@cubicecho/server-kit` | ^0.9 |
41
+ | Node | 26 |
42
+ | Postgres / PGlite (tests) | 18 or later / ^0.5 |
43
+ | `drizzle-orm`, `drizzle-kit` | `1.0.0-rc.5`, exact |
44
+ | `@vantreeseba/drizzle-graphql` | ^19 |
45
+ | `postgres` | ^4 (^3.4 is still accepted; it ends the process when a connection drops mid-transaction) |
46
+ | `graphql` | 16 |
47
+ | `graphql-yoga` | ^6 |
48
+ | `express` | 5 |
49
+ | `better-auth`, `@better-auth/sso`, `@better-auth/api-key` | ^1.7.28 |
50
+ | `@cubicecho/better-auth-oidc-pairing` | ^1.1 |
51
+ | `@cubicecho/graphql-better-auth` | ^1.1 |
52
+ | `@cubicecho/graphql-mcp` (with `/mcp`) | ^3.1 |
53
+ | `zod` | 4 |
54
+ | `nodemailer` (an optional dependency) | ^10 |
55
+ | `vitest` | 5 |
56
+ | `typescript` | 7 |
57
+
58
+ - **A version changes here first, then in the kit's peers, then in each server.** A server doesn't move a singleton on its own, and never installs with `--legacy-peer-deps`, which drops packages better-auth needs.
59
+ - **Adopting any part of the kit means the whole set.** See adopting.md.
60
+ - `graphql` 17 and PGlite 0.6 are out and have not been tried. Don't move to either in passing.
61
+
62
+ ## What the kit holds a server to
63
+
64
+ Each rule is stated once here; the file it names has the detail and the code.
65
+
66
+ - **Code two servers need is in the kit, and a server never copies it.** Where a server needs the kit to do more, change the kit (adopting.md, "Changing the kit"). Something only one server needs stays in that server.
67
+ - **Boot prepares Postgres before it migrates.** `prepareDatabase` waits with capped backoff, creates a missing database, and refuses a server older than 18 or missing an extension, before anything is changed. A `DatabaseBootError` is printed as a sentence; anything else keeps its stack. See boot.md.
68
+ - **Build the app, don't run it.** `createApp(deps)` returns the Express app with no listen and no side effects. index.ts is boot only, and ends in `stopOnSignals(server, { after: closeDatabase })`, with `cutOff` ending any SSE streams. See boot.md.
69
+ - **A server that keeps state in memory holds the database lock.** It takes `holdPostgresLock` before migrating, and stops at once when the lock is lost. See boot.md.
70
+ - **Every entity has a UUIDv7 `id()`**, from Postgres's `uuidv7()`. A join table and derived data go without. A secret is never an id. `checkSchemaConventions` holds it. See database.md.
71
+ - **People sign in with a link or a provider, never a password**, through `authPreset` and `signInPlugins`, with sessions in Postgres. better-auth's endpoints are served as GraphQL; its REST routes are not mounted. See auth.md.
72
+ - **A new instance is set up in the app, with a code**: `SETUP_CODE`, or one the server makes up and logs once; `OPEN_SETUP=true` opts out for 15 minutes after a start. Every server also has device links and a recovery command. No link is ever logged. See auth.md.
73
+ - **Sign-in is throttled by the kit.** Every sign-in operation calls `throttle(ctx, flow, email?)` first. `ctx.ip` is only right when `TRUST_PROXY` is. See auth.md.
74
+ - **OIDC sign-in, with pairing from the app, is on by default.** Leaving it out is `oidc: false` with a reason. See sso.md.
75
+ - **Codes everywhere.** A failure a client reads is a coded `GraphQLError` from the kit's helpers, a member of `ErrorCode`; everything else is masked by Yoga and logged by `graphqlLogger`. Rows the caller doesn't own are `NOT_FOUND`, never `FORBIDDEN`. Caught values are read with `errorMessage(error)`. See graphql.md.
76
+ - **Every query is bounded**: `limits` and `complexity: true` in buildSchema, `useOperationLimits()` on every Yoga, and the `HTTP_DEFAULTS.bodyLimit` cap on `/graphql` and `/mcp`. See graphql.md and boot.md.
77
+ - **Only who `allow` lets in introspects in production**: `useIntrospectionGate` on every Yoga, a person or nobody, never an app's key. See graphql.md.
78
+ - **Tunables live in `defaults.ts`.** A group the kit owns is overridden where the thing is built, never copied. See defaults.md.
79
+ - **`/healthz` is `{ ok, version }`**, 503 when Postgres doesn't answer, and never says why. See boot.md.
80
+ - **The kit's checks run in every server's tests**: `checkSchemaConventions`, `checkPostgresVersion`, and `checkMcpBudget` where there is `/mcp`. See testing.md.
81
+
82
+ ## Before you finish
83
+
84
+ The TS skill's `npm run check && npm test`. A schema change also needs `npm run db:generate` and the migration committed. A change to the kit itself also needs its page in `_agents/docs/` and the file here that uses it.
@@ -0,0 +1,58 @@
1
+ # Adopting, upgrading and changing the kit
2
+
3
+ How an existing server moves onto `@cubicecho/server-kit`, how a server takes a new kit release, and when the kit itself should change.
4
+
5
+ ## Putting an existing server on the kit
6
+
7
+ **Adopting any part of the kit means the whole set of versions** (SKILL.md, "Versions"), because the kit's peers refuse anything else. So the upgrades are the first commits, each on its own:
8
+
9
+ 1. **Drizzle rc.5 and drizzle-graphql 19**, if the server is behind. From rc.4 and drizzle-graphql 13 this is a PR of its own, and breaking for clients:
10
+ - change every pin at once (root `overrides`, root dependency, the db and server packages), then run `npx drizzle-kit up` in `db/`. It rewrites the `snapshot.json` files, never `migration.sql`, and `db:generate` should then say "No schema changes".
11
+ - `not()` is typed `SQL | undefined`: where a function must return `SQL`, write `not(x) ?? <fail-closed SQL>`, never a cast.
12
+ - Date columns and their filters are the `Date` scalar, so a hand-written field that takes a day takes `Date` too; a bad day is refused as `DRIZZLE_INVALID_INPUT_VALUE`.
13
+ - Scalars come from `@vantreeseba/drizzle-graphql`, not graphql-scalars (the `cubicecho-backend` skill's schema.md).
14
+ 2. **Yoga 6.** It breaks a hand-written logger, which `graphqlLogger` replaces (graphql.md).
15
+ 3. **Vitest 5**, with Storybook 10.6.9 and `@vitest/browser-*` 5 beside it where the app has them.
16
+ 4. **better-auth ^1.7.28**, `@better-auth/sso` and `@cubicecho/better-auth-oidc-pairing`, all three even with `oidc: false`.
17
+
18
+ Check with `npm ls` that each has one copy. Never `--legacy-peer-deps`.
19
+
20
+ Then replace the server's own copies, one concern per commit, with only that concern changing:
21
+
22
+ | The server has its own | Replace with | Then |
23
+ |---|---|---|
24
+ | shutdown, health, static, OIDC redirect modules | `/http`: `stopOnSignals`, `checkHealth`, `createStaticHandler`, `mountAuthRedirects` | delete them (boot.md) |
25
+ | a hand-written Yoga logger, an `x-request-id` handler | `graphqlLogger`, `REQUEST_ID` | |
26
+ | error helpers, an error-code list, `(error as Error).message` | `ErrorCode` and the helpers, `errorMessage` | graphql.md |
27
+ | depth or cost plugins | `useOperationLimits()`, and `limits` with `complexity: true` in buildSchema | graphql.md |
28
+ | an introspection plugin, `NoSchemaIntrospectionCustomRule` | `useIntrospectionGate({ allow })` | graphql.md |
29
+ | `rate-limit.ts`, `throttle.ts` | `createRateLimiter`, `throttle` | auth.md |
30
+ | better-auth options written out | `authPreset`, `signInPlugins` | auth.md, then sso.md |
31
+ | a connection-retry loop, `ssl` logic | `prepareDatabase`, `connectionOptions` | boot.md, in the Postgres 18 release |
32
+ | hand-written id and timestamp columns | `id()`, `moment()`, `timestamps()` | database.md, in the Postgres 18 release |
33
+ | `contextFromRequest`-like code for `/mcp`, its own budgets | `contextFromRequest`, `toolOptions`, `checkMcpBudget` | mcp.md |
34
+ | copies of the kit's defaults groups | overrides where the thing is built | defaults.md |
35
+
36
+ **The Postgres 18 release goes last and is announced as breaking**: the move to 18, `prepareDatabase`, `id()` as the default, and the two schema tests together (database.md). `prepareDatabase` stops every instance still on 17, so it is never adopted before.
37
+
38
+ Where the server diverges from the rest of the standard (layout, tenancy, deploy), the order is in the `cubicecho-backend` skill's app.md, "Bringing an existing app up to standard".
39
+
40
+ `notes` and `eunomia` are not on the kit yet. Their servers are too far behind to adopt it piece by piece, so leave them unless the task is their rewrite.
41
+
42
+ ## Taking a new kit release
43
+
44
+ - Read the kit's `CHANGELOG.md`. A minor before 1.0 may break; the entry says what to change.
45
+ - Bump `@cubicecho/server-kit` in every package that depends on it (in an app, the db and server workspaces), and any peer whose range moved, in one commit.
46
+ - Re-read the kit page (`node_modules/@cubicecho/server-kit/_agents/docs/`) of each entry the release touched, and this skill's file for it.
47
+
48
+ ## Changing the kit
49
+
50
+ **Code two servers need is in the kit, and a server never copies it.** When a server needs the kit to do more, change the kit rather than wrapping it or copying it in. Something only one server needs stays in that server, and a setting every server overrides does not belong in the kit.
51
+
52
+ The kit's own rules are in its `AGENTS.md`. The ones a server author meets:
53
+
54
+ - One entry per folder, and an entry imports only its own peers, so a server that skips `/mcp` never installs graphql-mcp.
55
+ - No `process.env`, no `process.exit` but in `stopOnSignals`, and no logging but through a `log` parameter: the server decides all three.
56
+ - A failure an operator can fix is a `DatabaseBootError` whose message says how, and never holds a credential.
57
+ - A new dependency or peer, a change to a peer range, or a higher `MIN_POSTGRES_MAJOR` is asked about first.
58
+ - An API change updates its page in `_agents/docs/` and the file of this skill that uses it.
package/skill/auth.md ADDED
@@ -0,0 +1,359 @@
1
+ # Auth: better-auth through the kit
2
+
3
+ How a server signs people in with `/auth`: the preset, setting up a new instance, links for another device, better-auth served as GraphQL, the throttle and API keys.
4
+
5
+ **Contents:** [Decisions](#decisions-dont-re-litigate) · [Files](#files) · [auth/better-auth.ts](#authbetter-authts) ·
6
+ [Setting up a new instance](#setting-up-a-new-instance) · [Getting back in](#getting-back-in-another-device-and-recovery) ·
7
+ [auth/endpoints.ts](#authendpointsts-better-auths-endpoints-as-graphql) · [authConfig](#authresolversts-authconfig) ·
8
+ [Email](#authemailts) · [Rate limiting sign-in](#rate-limiting-sign-in) · [Context](#context) · [API keys](#api-keys) ·
9
+ [The secret](#the-secret) · [Tests that hold the decisions](#tests-that-hold-the-decisions) ·
10
+ [Bringing older auth up to this](#bringing-older-auth-up-to-this)
11
+
12
+ OIDC sign-in and pairing build on this file and are in sso.md. Reference implementations: `cubicecho/s3-artifacts-mcp` for setup, device links and recovery; `cubicecho/ethos` (`server/src/auth/`) for what is served and tested.
13
+
14
+ ## Decisions (don't re-litigate)
15
+
16
+ | Concern | Choice |
17
+ |---|---|
18
+ | Users, accounts, verifications, sessions | Postgres through `authPreset`, ids from the column default (database.md). The session **token** is better-auth's own random string |
19
+ | **Sessions** | **In Postgres**, no `secondaryStorage`. A restart signs nobody out, and replicas share them. They last `AUTH_DEFAULTS.sessionTtlDays` (30): there is no password to fall back on |
20
+ | Transport | `Authorization: Bearer <token>` (the `bearer` plugin). No cookies, except the OIDC state cookie |
21
+ | **Sign-in methods** | **A link or a provider, never a password.** Links when `SMTP_URL` is set, OIDC when a provider is set or paired, and a one-time link from a signed-in device or the recovery command. **No setting lets an address alone sign in, and no link is ever logged** |
22
+ | **The first account** | The setup page, with a code, or an OIDC provider. Nothing else |
23
+ | Roles | A service has `admin` and `user`; an app has one admin flag (sso.md) |
24
+ | Local run modes | None of this. A bin or a daemon trusts the OS user (the `cubicecho-backend` skill's service.md) |
25
+ | API surface | better-auth's endpoints served as GraphQL by `@cubicecho/graphql-better-auth`. Its REST routes are not mounted |
26
+ | Machine callers | `@better-auth/api-key` keys sent as `x-api-key` (standard in services) |
27
+ | Brute force | The kit's `throttle`, first in every sign-in operation. better-auth's limiter only runs on its REST router |
28
+
29
+ Why no passwords: a self-hosted server has no one to run password resets, and a password is one more secret to leak. A link proves the inbox, and a provider proves the account.
30
+
31
+ ## Files
32
+
33
+ ```
34
+ server/src/auth/
35
+ better-auth.ts # createAuth(db, opts): authPreset, signInPlugins and the server's own plugins
36
+ endpoints.ts # applyBetterAuthExtension: better-auth's endpoints as GraphQL, with our `around`s
37
+ resolvers.ts # applyAuthExtension: authConfig, setUp, createSignInLink, spendSignInLink
38
+ email.ts # sendMagicLinkEmail (nodemailer over SMTP_URL)
39
+ recovery.ts # recoveryLink: what server/src/recover.ts prints
40
+ admin.ts # isAdmin, claimFirstAdmin, hasUsers, mayChangeSignIn (sso.md)
41
+ ```
42
+
43
+ A server with its own `rate-limit.ts`, `throttle.ts` or `auth-host.ts` deletes them: the first two are the kit's, and the instance is never rebuilt.
44
+
45
+ ## auth/better-auth.ts
46
+
47
+ `createAuth` takes the db and anything with a side effect as arguments, so tests build the real auth against PGlite and capture links. The server calls `betterAuth` itself, so its own plugins and hooks are in view and `auth.api` keeps exact types.
48
+
49
+ ```ts
50
+ import { authPreset, createSetupGate, type MagicLink, type SetupGate, signInPlugins } from '@cubicecho/server-kit/auth';
51
+ import { betterAuth } from 'better-auth';
52
+
53
+ /** Overrides for tests. Production uses the defaults. */
54
+ export interface AuthOptions {
55
+ /** What better-auth signs with. @defaultValue `authSecret()` */
56
+ secret?: string;
57
+ /** Delivers a sign-in link. Tests capture it. @defaultValue `sendMagicLinkEmail` with SMTP, none without */
58
+ sendMagicLink?: (link: MagicLink) => Promise<void>;
59
+ /** The environment's OIDC provider, or null for none. Only index.ts passes it (sso.md). */
60
+ pinned?: OidcConfig | null;
61
+ /** How an instance with no account is set up. @defaultValue one with a code nobody is told */
62
+ setupGate?: SetupGate;
63
+ }
64
+
65
+ /**
66
+ * Builds the better-auth instance. Server code calls `auth.api.*`; none of its REST routes are mounted.
67
+ *
68
+ * @param db - The database sessions and pending links are kept in.
69
+ * @param [options] - Test overrides.
70
+ * @returns The auth instance, and its setup gate.
71
+ */
72
+ export function createAuth(
73
+ db: DB,
74
+ { secret = authSecret(), sendMagicLink, pinned, setupGate = createSetupGate({ open: false, startedAt: new Date() }) }: AuthOptions = {},
75
+ ) {
76
+ const smtpDelivery = smtpConfigured() ? sendMagicLinkEmail : undefined;
77
+ const auth = betterAuth({
78
+ ...authPreset({
79
+ db,
80
+ tables: { user: users, session: sessions, account: accounts, verification: verifications, ssoProvider: ssoProviders },
81
+ secret,
82
+ serverUrl: serverUrl(),
83
+ appUrl: appUrl(),
84
+ }),
85
+ databaseHooks: { user: { create: { after: async (user) => claimFirstAdmin(db, user.id) } } },
86
+ plugins: [
87
+ ...signInPlugins({
88
+ appUrl: appUrl(),
89
+ deliver: sendMagicLink ?? smtpDelivery,
90
+ setup: setupGate,
91
+ oidc: {
92
+ clientName: '<App>',
93
+ canPair: ({ userId }) => mayChangeSignIn(db, userId, setupGate),
94
+ ...(pinned === undefined ? {} : { pinned }),
95
+ },
96
+ }),
97
+ ],
98
+ });
99
+ // With the instance whose first account it decides, so a page is never told about another gate.
100
+ return Object.assign(auth, { setupGate });
101
+ }
102
+
103
+ /** The better-auth instance `createAuth` builds. */
104
+ export type Auth = ReturnType<typeof createAuth>;
105
+
106
+ /** @returns The user id a request's session belongs to, or null. */
107
+ export async function sessionUserId(auth: Auth, headers: Headers): Promise<string | null> {
108
+ const session = await auth.api.getSession({ headers });
109
+ return session?.user.id ?? null;
110
+ }
111
+ ```
112
+
113
+ - `createAuth` has no written return type: `auth.api`'s type is built from the plugin list. Keep the plugins one array literal, with `signInPlugins` spread into it.
114
+ - **An option after the preset's spread replaces the preset's whole value**, so a `session: { … }` of your own repeats `expiresIn`. Never add `emailAndPassword`.
115
+ - Lifetimes and page paths are `AUTH_DEFAULTS` and `AUTH_PATHS`; override through `sessionTtlDays`, `magicLinkTtlMinutes` or `paths`.
116
+ - `secret`, `sendMagicLink` and `pinned` are dependencies, not settings, so they stay in `AuthOptions`.
117
+ - `sendsMagicLinks(auth)` reads the instance, not `SMTP_URL`, so a test's captured links count as on.
118
+ - `better-auth`, `@better-auth/sso` and `@cubicecho/better-auth-oidc-pairing` are the server's own dependencies, all three even with `oidc: false`.
119
+ - The instance travels on the context (`ctx.auth`). No module imports a global `auth`.
120
+
121
+ ## Setting up a new instance
122
+
123
+ Every server is self-hosted, so the first start ends on a setup page, not in a container's log. **A code is needed by default**, because whoever sets an instance up owns it.
124
+
125
+ | `SETUP_CODE` | `OPEN_SETUP` | Who may set up an instance with no account |
126
+ |---|---|---|
127
+ | set | any | Whoever has the operator's code. What a quickstart compose file requires |
128
+ | unset | unset | Whoever has the code the server made up at this start, which `setupNotice` logs while there is no account |
129
+ | unset | `true` | Anyone who can reach it, for `SETUP_DEFAULTS.openMinutes` (15) after a start. For a network nobody else reaches, and what `.env.example` sets for development |
130
+
131
+ ```ts
132
+ // preflight.ts, inside an `if` on either variable: the import brings all of better-auth.
133
+ const problem = setupProblem({ code: setupCode(), open: openSetup(), appUrl: configuredAppUrl() });
134
+ if (problem !== undefined) {
135
+ fatal(problem);
136
+ }
137
+
138
+ // auth/resolvers.ts
139
+ fields.setUp.resolve = async (_parent, args: { email: string; code?: string | null }, context: Context) => {
140
+ throttle(context, AuthFlow.SetUp);
141
+ const email = parseOrThrow(emailInput, args.email);
142
+ return claimInstance(context.auth, context.auth.setupGate, { code: args.code ?? null, email, name: nameFor(email) });
143
+ };
144
+ ```
145
+
146
+ - **The plugin `signInPlugins({ setup })` adds holds the first account to one caller, across processes**, and refuses every other way of making it: until there is an account no link is emailed or spent. An OIDC provider may make the first account too (sso.md).
147
+ - **Once there is an account the variables do nothing.** Neither ever signs anyone in to an account that exists.
148
+ - **`authConfig.setup`** is `{ needsCode, codeIsInLog, endsAt }`, or null once there is an account. It never says the code.
149
+ - **Every place that takes the code shares `AuthFlow.SetUp`'s budget**: `setUp`, and `pairSso` signed out.
150
+ - **The address is unverified**, so the page asks for it twice, and `changeEmail` (on in the preset) fixes a typo until a link or provider verifies it.
151
+ - After the claim the page offers to pair a provider. Skipping is allowed, and says how to get back in.
152
+ - **An empty database is a new instance**, so a reset opens setup again. A made-up code is the process's own, so several replicas need `SETUP_CODE`.
153
+ - A server for one person refuses the second account in its own `user.create.before`, which runs after the kit's.
154
+
155
+ ## Getting back in: another device, and recovery
156
+
157
+ With no SMTP and no provider, a session is the only thing a person has. Every server has both:
158
+
159
+ - **Settings: "Sign in on another device".** `createSignInLink(auth, userId)` (from a session, for the caller's own account, never from an API key) answers `{ token, expiresAt }`; the page shows `signInLinkUrl(appUrl, token)` once, as text and a QR code. `/auth/link` takes the token out of the address bar and spends it over GraphQL with `spendSignInLink`, throttled.
160
+ - **`server/src/recover.ts`**, run as `docker exec <container> node server/src/recover.ts`: prints the same link for the owner or first admin. It makes no account. Whoever can run it can already read the database and the secret.
161
+
162
+ A link works once, for 15 minutes, and is stored as a hash. Its token is in the URL's fragment, which no server or proxy is sent. **There are no invites**: another person joins through a provider or an emailed link.
163
+
164
+ ## auth/endpoints.ts: better-auth's endpoints as GraphQL
165
+
166
+ `@cubicecho/graphql-better-auth` reads the endpoints off an auth instance and serves them as typed fields, so a better-auth upgrade moves the API with it. What the server adds goes in each operation's `around`.
167
+
168
+ ```ts
169
+ import { applyBetterAuthGraphQL, betterAuthGraphQL, type OperationOptions } from '@cubicecho/graphql-better-auth';
170
+ import { asSetupRefusal, sendsMagicLinks, throttle } from '@cubicecho/server-kit/auth';
171
+ import { badInput, parseOrThrow } from '@cubicecho/server-kit/graphql';
172
+ import { GraphQLError, type GraphQLSchema } from 'graphql';
173
+
174
+ /** The better-auth endpoints served, by name. An allowlist. */
175
+ export const BETTER_AUTH_OPERATIONS = [
176
+ 'signInMagicLink', 'magicLinkVerify', 'verifyOidcSignIn',
177
+ 'getSession', 'listSessions', 'signOut', 'revokeSession', 'revokeSessions', 'revokeOtherSessions',
178
+ ];
179
+
180
+ /** The sign-in steps that are throttled. Each has its own budget. */
181
+ export const AuthFlow = {
182
+ SetUp: 'setup',
183
+ SignInMagicLink: 'sign-in-magic-link',
184
+ MagicLinkVerify: 'magic-link-verify',
185
+ VerifyOidcSignIn: 'verify-oidc-sign-in',
186
+ SpendSignInLink: 'spend-sign-in-link',
187
+ PairSso: 'pair-sso',
188
+ } as const;
189
+
190
+ const BAD_LINK = 'Invalid or expired sign-in link.';
191
+
192
+ /**
193
+ * Runs a token-spending call, and answers any refusal with one message: BAD_USER_INPUT, never the
194
+ * UNAUTHENTICATED better-auth's 401 maps to, which is what the client drops its session on.
195
+ */
196
+ async function refusedAs(next: () => Promise<unknown>, message: string): Promise<unknown> {
197
+ try {
198
+ return await next();
199
+ } catch (error) {
200
+ throw error instanceof GraphQLError ? badInput(message) : error;
201
+ }
202
+ }
203
+
204
+ const signInMagicLink: OperationOptions<Context> = {
205
+ omitArgs: ['name', 'metadata', 'callbackURL', 'newUserCallbackURL', 'errorCallbackURL'],
206
+ around: async (call, next) => {
207
+ const normalized = String(call.body.email).toLowerCase().trim();
208
+ throttle(call.context, AuthFlow.SignInMagicLink, normalized);
209
+ const email = parseOrThrow(emailInput, normalized);
210
+ if (sendsMagicLinks(call.context.auth) === false) {
211
+ throw badInput('This instance cannot email sign-in links. Use a provider, or a link from a device that is signed in.');
212
+ }
213
+ call.body.email = email;
214
+ call.body.name = nameFor(email);
215
+ try {
216
+ return await next();
217
+ } catch (error) {
218
+ // Nothing is emailed before the instance is set up.
219
+ throw asSetupRefusal(error);
220
+ }
221
+ },
222
+ };
223
+
224
+ const magicLinkVerify: OperationOptions<Context> = {
225
+ around: (call, next) => {
226
+ // By IP alone: until the token verifies there is no address to count against.
227
+ throttle(call.context, AuthFlow.MagicLinkVerify);
228
+ if (sendsMagicLinks(call.context.auth) === false) {
229
+ throw badInput(BAD_LINK);
230
+ }
231
+ return refusedAs(next, BAD_LINK);
232
+ },
233
+ };
234
+
235
+ const verifyOidcSignIn: OperationOptions<Context> = {
236
+ around: (call, next) => {
237
+ throttle(call.context, AuthFlow.VerifyOidcSignIn);
238
+ return refusedAs(next, 'Invalid or expired sign-in. Sign in again.');
239
+ },
240
+ };
241
+
242
+ /** Signing out with no session is `success: false`, not an error. */
243
+ const signOut: OperationOptions<Context> = {
244
+ omitArgs: ['callbackURL', 'disableRedirect', 'state'],
245
+ around: async (call, next) =>
246
+ (await sessionUserId(call.context.auth, call.context.headers)) === null ? { success: false } : next(),
247
+ };
248
+
249
+ export function applyBetterAuthExtension(schema: GraphQLSchema, db: DB): GraphQLSchema {
250
+ // Described from an instance that always has the magic-link plugin, so the fields don't depend on SMTP_URL.
251
+ // It leaves `pinned` out, so it never touches the environment's provider row.
252
+ const describing = createAuth(db, { sendMagicLink: async () => {} });
253
+ const built = betterAuthGraphQL<Context>(describing, {
254
+ include: BETTER_AUTH_OPERATIONS,
255
+ auth: (context) => context.auth,
256
+ headers: (context) => context.headers,
257
+ operations: { signInMagicLink, magicLinkVerify, verifyOidcSignIn, signOut },
258
+ });
259
+ return applyBetterAuthGraphQL(schema, built);
260
+ }
261
+ ```
262
+
263
+ - **`include` is an allowlist.** A new plugin's endpoints are served only once named here.
264
+ - **The schema is described once, from a fixed instance**, so the SDL and client types don't change with the environment. A field whose plugin is off at runtime refuses in its `around`.
265
+ - **Refusals of a token are `BAD_USER_INPUT`, never `UNAUTHENTICATED`.** Everything else goes through the package's `toGraphQLError`: the code from the HTTP status, better-auth's own code in `extensions.authCode`.
266
+ - A client that already calls `verifyOneTimeToken` keeps that name with the package's `fieldName` option.
267
+ - `getSession` and `listSessions` answer with session tokens, so `/mcp` excludes them (mcp.md).
268
+ - **Never mount `/api/auth/{*any}`.** The only better-auth paths served over HTTP are the two OIDC redirects (sso.md).
269
+
270
+ ## auth/resolvers.ts: authConfig
271
+
272
+ ```graphql
273
+ "Which ways of signing in this instance offers, so the sign-in page shows only those."
274
+ type AuthConfig {
275
+ "The instance can email sign-in links."
276
+ magicLink: Boolean!
277
+ "How an instance with no account is set up. Null once it has one."
278
+ setup: InstanceSetup
279
+ "The OIDC providers to sign in with, one button each. Empty when none."
280
+ ssoProviders: [SsoProvider!]!
281
+ }
282
+ extend type Query { authConfig: AuthConfig! }
283
+ ```
284
+
285
+ `magicLink` is `sendsMagicLinks(ctx.auth)`; `ssoProviders` is `listOidcProviders` with each one's `signInUrl` (sso.md). There is no `me` field: the client reads its profile through the generated `users` query, scoped to its own row. `applyAuthExtension`, `applyBetterAuthExtension` and `applySsoExtension` go in build-schema.ts's extension chain.
286
+
287
+ ## auth/email.ts
288
+
289
+ `sendMagicLinkEmail({ email, url })` sends through `SMTP_URL` (a nodemailer connection URL), from `SMTP_FROM` or `<app>@` the host of `APP_URL`, and says the link works once for `AUTH_DEFAULTS.magicLinkTtlMinutes` minutes. The link and token are never logged and never in a response.
290
+
291
+ - **nodemailer ^10 is an optional dependency**, imported inside `sendMagicLinkEmail`, so an instance with no SMTP never loads it. Preflight imports it when `SMTP_URL` is set and refuses to start without it.
292
+ - **`SMTP_URL` needs `APP_URL`**, which preflight checks. A server that takes its address from the request would email a link pointing wherever the requester chose.
293
+
294
+ ## Rate limiting sign-in
295
+
296
+ better-auth's limiter runs in its REST router. A `ctx.auth.api.*` call never passes through it, so **none of the GraphQL fields are limited by it**.
297
+
298
+ - Call `throttle(context, flow, email?)` **first** in every sign-in `around`, in `setUp`, `spendSignInLink` and `pairSso`, before any lookup or email, so a refused attempt costs nothing.
299
+ - It counts by address and by account, each flow on its own budget of `RATE_LIMIT_DEFAULTS` (5 in 15 minutes), and throws `TOO_MANY_REQUESTS` with `retryAfter`. Steps with no address yet count by IP alone.
300
+ - Normalize the address (lowercase, trimmed) before throttling, or casings each get a budget.
301
+ - `ctx.ip` is Express's `req.ip`, the real client only when `TRUST_PROXY` matches the proxy in front. If it's wrong, every client shares the proxy's address and one budget.
302
+ - The limiter is a dependency: `createApp({ limiter })` defaults it to `createRateLimiter()`, and tests pass `createRateLimiter({ maxAttempts: 2 }, now)`. Replicas each keep their own counts, which is acceptable for sign-in.
303
+
304
+ ## Context
305
+
306
+ `createContextFactory` in core/context.ts builds every request's context, for `/graphql` and `/mcp` alike, so there is one place a caller is read:
307
+
308
+ ```ts
309
+ export function createContextFactory({ db, auth, pubsub, limiter }: ContextDeps): ContextFactory {
310
+ return async (headers, ip = UNKNOWN_IP) => ({
311
+ db, auth, pubsub, limiter, headers, ip,
312
+ userId: await sessionUserId(auth, headers),
313
+ loaders: createLoaders(db),
314
+ });
315
+ }
316
+ ```
317
+
318
+ Resolvers call `requireAuth(ctx)` (graphql.md), never read `ctx.userId` directly, and never take a user id from an argument. In a service, `x-api-key` is read first, then the session, and the context carries `caller` (`CALLER_USER` or `CALLER_AGENT`), `role` and `keyId` (the `cubicecho-backend` skill's service.md, "Identity").
319
+
320
+ ## API keys
321
+
322
+ ```ts
323
+ // Minted server-side (no headers) so server-only fields can be set. The plugin's default
324
+ // per-key rate limit (10 a day) starves anything that polls. No days means no expiry.
325
+ const created = await ctx.auth.api.createApiKey({
326
+ body: { userId, name, metadata: { kind: CALLER_AGENT }, rateLimitEnabled: false, expiresIn: days ? days * SECONDS_PER_DAY : undefined },
327
+ });
328
+ // The only time the plaintext exists. Only its hash is stored.
329
+ return created.key;
330
+ ```
331
+
332
+ - Add `apiKey({ enableMetadata: true })` beside `...signInPlugins(...)`, and `apikey: apikeys` to the preset's `tables`. Keep it on `storage: 'database'`.
333
+ - Key management is a hand-written mutation, not a served endpoint, and is allowed **only from a session**, so a leaked key can't mint its successor.
334
+ - **A key belongs to a person.** List, rename and revoke are Drizzle reads and deletes on `apikeys` scoped by `referenceId`; someone else's key is `NOT_FOUND`, and a service's admin may see all. Deleting the row revokes it.
335
+ - **A key has no admin rights, even an admin's.** An admin operation an agent needs is a named scope an admin grants.
336
+ - Every credential a service accepts works on every door it is meant for: test a key against `/graphql` and `/mcp`. Metadata may be double-encoded JSON in some plugin versions; parse defensively.
337
+
338
+ ## The secret
339
+
340
+ core/config.ts has `DEV_SECRET` (used when `BETTER_AUTH_SECRET` is unset, so development needs no `.env` entry), `PLACEHOLDER_SECRET` (what `.env.example` ships), and `describeWeakSecret(secret)`, which answers why a secret must not sign production tokens: unset, a published default, or shorter than `SECRET_DEFAULTS.minSecretLength` (32). In production preflight refuses with `BETTER_AUTH_SECRET <reason>. Set a strong random value: generate one with \`openssl rand -hex 32\`.`
341
+
342
+ `APP_URL` is where links point; `SERVER_URL` is where the OIDC redirects live (sso.md). Log both at boot. With an account and no SMTP or provider, say at boot how to get in: a signed-in device, or the recovery command.
343
+
344
+ ## Tests that hold the decisions
345
+
346
+ The preset's own tests cover ids, hashed links and the absence of passwords. A server's auth test covers what it could override:
347
+
348
+ - a session made by signing in is a row in `sessions`, and gone after `signOut`
349
+ - `auth.options.emailAndPassword` is undefined, and no GraphQL answer has `set-cookie`
350
+ - each throttled operation refuses past its budget (testing.md)
351
+ - `setUp` with no code, a wrong one and the right one; a second `setUp`; several at once, with one winner
352
+ - nothing is emailed before setup, and the code is in no answer
353
+ - a device link signs in once and needs a session; `recoveryLink` makes no account
354
+
355
+ ## Bringing older auth up to this
356
+
357
+ One commit each: sessions to Postgres (drop `secondaryStorage`), then `authPreset` and `signInPlugins`, then endpoints.ts replacing hand-written `signIn`/`verifyMagicLink` mutations (the client's operations renamed in the same commit), then `throttle`, then setup, device links and recovery, then dropping `emailAndPassword` once links or a provider are in place.
358
+
359
+ **`SECURE_LOCAL_NET` and `EXPOSE_MAGIC_LINK` are gone.** The first made an address the whole credential; the second handed a link to whoever asked. A server that still reads them drops both in the release that adds setup, device links and recovery (breaking: someone with no provider or SMTP needs the recovery command), and preflight warns while either is set. Hand-written pairing moves as sso.md says.