@cubicecho/server-kit 0.9.0 → 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/README.md +11 -0
- package/_agents/docs/05-graphql.md +3 -2
- package/dist/graphql/index.d.ts +1 -0
- package/dist/graphql/index.js +1 -0
- package/dist/graphql/introspection.d.ts +28 -0
- package/dist/graphql/introspection.js +71 -0
- package/llms.txt +2 -0
- package/package.json +4 -3
- package/skill/SKILL.md +84 -0
- package/skill/adopting.md +58 -0
- package/skill/auth.md +359 -0
- package/skill/boot.md +326 -0
- package/skill/database.md +103 -0
- package/skill/defaults.md +72 -0
- package/skill/graphql.md +153 -0
- package/skill/mcp.md +87 -0
- package/skill/sso.md +187 -0
- package/skill/testing.md +133 -0
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.
|