@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/graphql.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# Errors, validation and limits
|
|
2
|
+
|
|
3
|
+
How a server uses `/graphql`: the coded errors a client reads, the logger for the ones it doesn't, zod through `parseOrThrow`, and the bounds on every operation.
|
|
4
|
+
|
|
5
|
+
**Contents:** [The contract](#the-contract) · [The helpers](#the-helpers) ·
|
|
6
|
+
[Masked errors are logged, variables never are](#masked-errors-are-logged-variables-never-are) ·
|
|
7
|
+
[Validation with zod 4](#validation-with-zod-4) · [Ownership in hand-written code](#ownership-in-hand-written-code) ·
|
|
8
|
+
[Mapping library errors](#mapping-library-errors) · [Limits: page size, cost and depth](#limits-page-size-cost-and-depth) ·
|
|
9
|
+
[Introspection](#introspection) · [Testing errors and limits](#testing-errors-and-limits)
|
|
10
|
+
|
|
11
|
+
## The contract
|
|
12
|
+
|
|
13
|
+
Clients branch on `extensions.code`, never on the message. Yoga masks every non-`GraphQLError` as `Unexpected error.` / `INTERNAL_SERVER_ERROR`, on purpose: an unexpected failure is the server's problem, and its details are not the client's business.
|
|
14
|
+
|
|
15
|
+
- **Errors a caller should read are `GraphQLError`s built by the kit's helpers.** Everything else is a plain `throw new Error(...)` and stays masked. Keep Yoga's default `maskedErrors`.
|
|
16
|
+
- **Codes everywhere.** Expected failures (bad input, not found, a rule refusing the write) are thrown as coded errors too. No result payloads (`{ ok, error }`, `FooResult = Foo | FooError` unions): a mutation returns its row type or throws. This may be revisited org-wide; until then, don't introduce payload types or mix the two styles.
|
|
17
|
+
|
|
18
|
+
| Code | `ErrorCode` member | When |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| `UNAUTHENTICATED` | `Unauthenticated` | No session, or an expired one. Clients drop their token on it, so a bad sign-in link or one-time token is `BAD_USER_INPUT`, never this |
|
|
21
|
+
| `NOT_FOUND` | `NotFound` | The row doesn't exist **or belongs to someone else**. One code for both, so callers can't probe for ids |
|
|
22
|
+
| `BAD_USER_INPUT` | `BadUserInput` | Authenticated, but the arguments are wrong in a way the caller can fix |
|
|
23
|
+
| `TOO_MANY_REQUESTS` | `TooManyRequests` | Rate limited. `extensions.retryAfter` says how many seconds to wait |
|
|
24
|
+
| `CONFLICT` | `Conflict` | The request is fine, but the instance is in a state that refuses it, such as pairing a provider twice |
|
|
25
|
+
| `FORBIDDEN` | `Forbidden` | The *kind* of caller may never do this (a permission rule, a role). **Never for ownership** |
|
|
26
|
+
| `QUERY_TOO_COMPLEX` | `QueryTooComplex` | Too deep, too aliased or too costly. A client bug: fix the query |
|
|
27
|
+
| `DRIZZLE_LIMIT_EXCEEDED` | none | A `limit` above the maximum page size. drizzle-graphql's own, passed through. Page instead |
|
|
28
|
+
| `INTERNAL_SERVER_ERROR` | none | Anything masked. Yoga sets it; never throw it yourself |
|
|
29
|
+
|
|
30
|
+
## The helpers
|
|
31
|
+
|
|
32
|
+
`ErrorCode`, `badInput`, `notFound`, `forbidden`, `conflict`, `unauthenticated`, `rateLimited`, `tooComplex`, `requireAuth`, `parseOrThrow` and `errorMessage`, all from `@cubicecho/server-kit/graphql`. No server writes its own.
|
|
33
|
+
|
|
34
|
+
- **`ErrorCode` is a vocabulary** (`cubicecho_typescript`, "Vocabularies"): server code and tests use the member, never the word. An error only one server has, with its own `extensions.reason`, is built in that server from these codes. A code every server needs is added to the kit.
|
|
35
|
+
- **`requireAuth(ctx)`** returns `ctx.userId` or throws `unauthenticated()`.
|
|
36
|
+
- **`errorMessage(error)`** reads a caught `unknown` for logs and wrapped errors. Never `(error as Error).message`, never the `instanceof` ternary inline. It is not for client messages: a caught library error reaches the client only through a coded helper, with a message you wrote.
|
|
37
|
+
- `tooComplex` is thrown by `useOperationLimits` alone.
|
|
38
|
+
|
|
39
|
+
## Masked errors are logged, variables never are
|
|
40
|
+
|
|
41
|
+
Yoga logs each error it masks, with its original cause, through its `logging` option. That line is the only record of what actually broke.
|
|
42
|
+
|
|
43
|
+
- **Every Yoga passes `logging: graphqlLogger` and `requestId: REQUEST_ID`** (boot.md). The logger tags lines `[graphql]`, prints the masked error's path, cause and stack, and prints warnings and errors only, whatever `LOG_LEVEL` and `DEBUG` say. A failed query is logged without its parameters or Postgres's `detail`, which carry what people typed.
|
|
44
|
+
- **Never `logging: false`.** It silences masked errors too, and a production failure leaves no trace.
|
|
45
|
+
- **Never log operation variables or resolver arguments**, in a plugin, a resolver or a hook. Sign-in variables carry tokens, and other inputs carry whatever users typed. Log ids and counts.
|
|
46
|
+
- Coded errors aren't logged: they are expected outcomes, and a flood of `NOT_FOUND` lines would bury real failures.
|
|
47
|
+
- Every log line has a `[subsystem]` tag (`[server]`, `[db]`, `[setup]`, `[graphql]`, `[mcp]`), no emoji, and never a secret.
|
|
48
|
+
|
|
49
|
+
## Validation with zod 4
|
|
50
|
+
|
|
51
|
+
GraphQL types check shape; zod checks meaning (lengths, trimmed non-empty, ranges, email, string enums). How long a column may be is a setting, so it is a group in defaults.ts, one per table:
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
// core/defaults.ts
|
|
55
|
+
/** Limits on what a todo may hold. */
|
|
56
|
+
export interface TodoSettings {
|
|
57
|
+
/** Longest title, in characters. */
|
|
58
|
+
maxTitleLength: number;
|
|
59
|
+
/** Longest notes, in characters. */
|
|
60
|
+
maxNotesLength: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const TODO_DEFAULTS: Readonly<TodoSettings> = Object.freeze({ maxTitleLength: 500, maxNotesLength: 10_000 });
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
// todos/input.ts
|
|
68
|
+
export const titleSchema = z.string().trim().min(1, 'Title cannot be empty.').max(TODO_DEFAULTS.maxTitleLength, 'Title is too long.');
|
|
69
|
+
const notesSchema = z.string().max(TODO_DEFAULTS.maxNotesLength).nullable();
|
|
70
|
+
/** Partial, since an update's `set` carries only the changed columns. */
|
|
71
|
+
export const todoInput = z.object({ title: titleSchema, notes: notesSchema }).partial();
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`parseOrThrow(schema, value)` throws `BAD_USER_INPUT` with the first issue's message. Where it runs:
|
|
75
|
+
|
|
76
|
+
- **Hand-written resolvers:** `const title = parseOrThrow(titleSchema, args.title);`, first thing.
|
|
77
|
+
- **Generated writes:** in the table's `onWrite.before`, over `writtenRows(args)` (the `cubicecho-backend` skill's schema.md).
|
|
78
|
+
|
|
79
|
+
Messages are full sentences a user could read, and name the right tool in a refusal (`'Use setDoneLane to choose which lane marks a todo done.'`). Every string column gets a `.max()` from its table's group; the body cap bounds a request, not a column. `.min(1)` is not a setting: no other number would be right.
|
|
80
|
+
|
|
81
|
+
## Ownership in hand-written code
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
/**
|
|
85
|
+
* Loads a todo the caller owns.
|
|
86
|
+
*
|
|
87
|
+
* @throws NOT_FOUND when it is missing or someone else's.
|
|
88
|
+
*/
|
|
89
|
+
async function loadOwnedTodo(ctx: Context, id: string): Promise<Todo> {
|
|
90
|
+
const userId = requireAuth(ctx);
|
|
91
|
+
const isOwnedTodo = and(eq(todos.id, id), eq(todos.userId, userId));
|
|
92
|
+
const [row] = await ctx.db.select().from(todos).where(isOwnedTodo).limit(1);
|
|
93
|
+
if (row === undefined) {
|
|
94
|
+
throw notFound('Todo not found');
|
|
95
|
+
}
|
|
96
|
+
return row;
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Updates and deletes put `userId` in the `WHERE` too, so "someone else's id" and "no such id" are the same non-event.
|
|
101
|
+
|
|
102
|
+
## Mapping library errors
|
|
103
|
+
|
|
104
|
+
- better-auth's `APIError`, served through `@cubicecho/graphql-better-auth`, maps by HTTP status, with better-auth's code in `extensions.authCode`. Override where the default is wrong for the client, as the token-spending operations do (auth.md). A direct `ctx.auth.api.*` call in a hand-written resolver maps its own: validation becomes `badInput`, never a raw throw.
|
|
105
|
+
- A Postgres unique violation (SQLSTATE `23505`, held in a constant such as `PG_UNIQUE_VIOLATION`) becomes `badInput('That name is already taken.')` where the constraint is user-facing. Named constraints (`uq_...`) let the mapping check which one.
|
|
106
|
+
- drizzle-graphql's `onError` hook can do this mapping centrally for generated mutations.
|
|
107
|
+
|
|
108
|
+
## Limits: page size, cost and depth
|
|
109
|
+
|
|
110
|
+
A generated schema is a query language over every table, unbounded by default. `todos(limit: 1000000)` pulls a table, and `projects { todos { project { todos { ... } } } }` multiplies it. Every server has all three bounds, and every number is a member of `OPERATION_LIMIT_DEFAULTS`:
|
|
111
|
+
|
|
112
|
+
1. **Page size**, in buildSchema: `limits: { defaultLimit: defaultPageSize, maxLimit: maxPageSize }` (50 and 500). A larger `limit` is refused with `DRIZZLE_LIMIT_EXCEEDED`. Per table with `limits.tables`; to-many relations their own smaller page with `limits.relations`, so `projects { todos }` is priced at a relation's page per project. Leave `clampToMax` off: a silently short page looks like the end of the data.
|
|
113
|
+
2. **Cost**: `complexity: true` in buildSchema (on by default, and stated so nobody turns it off) puts each field's cost on `extensions.complexity`. A list costs its page size times one row. `useOperationLimits` prices each operation with its own variables and refuses it over `maxCost` (10,000).
|
|
114
|
+
3. **Depth and aliases**: graphql-armor's `maxDepth` (8) and `maxAliases` (15), so an absurd document is refused before it is priced.
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
createYoga({ /* … */ plugins: [useOperationLimits()] });
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
- `useOperationLimits` holds queries, mutations and subscriptions to all three before any resolver runs, prices `__typename` at nothing (Apollo adds one everywhere), and answers a 400. Introspection is exempt from depth, so GraphiQL and codegen work.
|
|
121
|
+
- **Start with the kit's numbers.** Raise one only for a real screen that needs it, as an override (`useOperationLimits({ maxCost: 15_000 })`) whose value is a member of the server's own group in defaults.ts, and name the screen in the commit message. A page-size override goes to buildSchema's `limits` too.
|
|
122
|
+
- **A hand-written list field** caps its own `limit` (`Math.min(args.limit ?? defaultPageSize, maxPageSize)`) and carries a cost hint: `extensions: { complexity: ({ args, childComplexity }) => (args.limit ?? OPERATION_LIMIT_DEFAULTS.defaultPageSize) * childComplexity }`. Without one it is priced at `defaultFieldCost`.
|
|
123
|
+
- `/mcp` doesn't go through Yoga, so the plugin never sees it; mcp.md says what bounds that door.
|
|
124
|
+
|
|
125
|
+
## Introspection
|
|
126
|
+
|
|
127
|
+
A generated schema is every table and column the server has. In production it is not handed to whoever asks: `useIntrospectionGate` refuses `__schema` and `__type` to every request its `allow` does not let in. `__typename` stays everyone's.
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
plugins: [
|
|
131
|
+
useOperationLimits(),
|
|
132
|
+
// Development keeps GraphiQL and codegen open, as graphiql does.
|
|
133
|
+
...(isProduction() ? [useIntrospectionGate<ServerContext>({ allow: isPerson })] : []),
|
|
134
|
+
],
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
- **`allow(request, serverContext)` is the server's own.** Let in who builds clients against the schema: a person, by session or their own API key. Never an app's or a worker's key: those call the operations they were written for and have no use for the schema. It may be async, and is asked once per request, only for a document that names `__schema` or `__type`, so reading a caller costs nothing on ordinary traffic.
|
|
138
|
+
- **A server with no people** (a service such as agent-router) leaves `allow` out, so nobody introspects in production, or lets in the one key its operators hold. Its clients are built from the schema file in the repo, not from a live server.
|
|
139
|
+
- **`allow` returns false to refuse.** What it throws fails the request as the server's error, so a caller a server reads as nobody (two different keys, say) is caught there and answered `false`.
|
|
140
|
+
- **It fails closed.** Every request not let in gets graphql-js's `NoSchemaIntrospectionCustomRule`: one with no query text (a persisted operation), and one over a WebSocket, which never has its parameters read. Add the rule in `onValidate` as the gate does, never with `setValidationFn`: Yoga's validation cache keys on the rules, which is what keeps a person's cached answer from a refused caller.
|
|
141
|
+
- **No hints to a request not let in.** graphql-js answers `{ todoz }` with `Did you mean "todos"?`, which names fields one guess at a time. The gate takes the hint off. Only a document that could introspect is let in, so in production nobody gets hints; `suggestions: true` keeps them.
|
|
142
|
+
- `/mcp` doesn't go through Yoga. Its tools are the operations it lists, and it has no introspection to gate.
|
|
143
|
+
|
|
144
|
+
## Testing errors and limits
|
|
145
|
+
|
|
146
|
+
`expectError` (the `cubicecho-backend` skill's testing.md) returns `{ message, code }`. Assert on `code`, by its `ErrorCode` member; the message is incidental:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
const { code } = await bob.expectError(COMPLETE_TODO, { id: aliceTodo });
|
|
150
|
+
expect(code).toBe(ErrorCode.NotFound);
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
In-process `graphql()` skips Yoga's masking and plugins. Masking, the operation limits, the introspection gate and the body cap are tested over HTTP in `__tests__/http/app.test.ts` (testing.md), with queries built from `OPERATION_LIMIT_DEFAULTS` so a changed limit doesn't leave a test checking the old number.
|
package/skill/mcp.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# The MCP door
|
|
2
|
+
|
|
3
|
+
How a server opens `/mcp` beside `/graphql` with `/mcp` from the kit and `@cubicecho/graphql-mcp`, and what bounds it.
|
|
4
|
+
|
|
5
|
+
**Contents:** [mcp/endpoint.ts](#mcpendpointts) · [Mounting it](#mounting-it) · [Limits on this door](#limits-on-this-door) ·
|
|
6
|
+
[Budgets and hygiene](#budgets-and-hygiene)
|
|
7
|
+
|
|
8
|
+
Standard in services; optional in apps (an app may expose a read-only `/mcp`). **One schema instance, two doors.** Permissions live on the schema (graphql-casl, the `cubicecho-backend` skill's permissions.md), so they hold for both. The MCP tool list only decides what an agent is *told about*, not what it can *reach*.
|
|
9
|
+
|
|
10
|
+
## mcp/endpoint.ts
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { createHttpHandler, type McpHttpHandler } from '@cubicecho/graphql-mcp';
|
|
14
|
+
import { contextFromRequest, toolOptions } from '@cubicecho/server-kit/mcp';
|
|
15
|
+
import type { GraphQLSchema } from 'graphql';
|
|
16
|
+
import pkg from '../../package.json' with { type: 'json' };
|
|
17
|
+
import type { ContextFactory } from '../core/context.ts';
|
|
18
|
+
|
|
19
|
+
/** What an agent is offered. A listing, not a lock (permissions.ts is the lock). */
|
|
20
|
+
export const TOOLS = [
|
|
21
|
+
'Query.tasks', 'Query.runs', 'Query.runEvents',
|
|
22
|
+
'Mutation.createTask', 'Mutation.updateTaskSingle', 'Mutation.deleteTaskSingle', 'Mutation.runTask',
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
/** Orientation for generated fields, which only describe themselves as "the `tasks` query". Keyed by tool name. */
|
|
26
|
+
const HINTS: Record<string, string> = {
|
|
27
|
+
tasks: 'Every task: its prompt, model and whether it is enabled. Filter any column: `where: { name: { eq: "x" } }`.',
|
|
28
|
+
create_task: 'Adds a task. It will not fire until it has a trigger. Call `run_task` to run it now.',
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Builds the MCP handler over the permissioned schema.
|
|
33
|
+
*
|
|
34
|
+
* @param schema - The same instance /graphql serves.
|
|
35
|
+
* @param contextFor - The context factory /graphql uses, so identity matches.
|
|
36
|
+
* @returns An Express-compatible handler with `close()`.
|
|
37
|
+
*/
|
|
38
|
+
export function createMcpHandler(schema: GraphQLSchema, contextFor: ContextFactory): McpHttpHandler {
|
|
39
|
+
return createHttpHandler({
|
|
40
|
+
...toolOptions({ hints: HINTS }),
|
|
41
|
+
schema,
|
|
42
|
+
name: '<service>',
|
|
43
|
+
version: pkg.version,
|
|
44
|
+
contextFromRequest: contextFromRequest(contextFor),
|
|
45
|
+
include: TOOLS,
|
|
46
|
+
// updateTaskSingle → update_task
|
|
47
|
+
toolName: (field) => snakeCase(field.name.replace(/Single$/, '')),
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- **`contextFromRequest` copies the headers and Express's `req.ip` into the factory `/graphql` uses**, so a key or a session means the same on both doors. Don't write `toHeaders` or `clientIp` again; the kit's `toHeaders` is in `/http`.
|
|
53
|
+
- **`toolOptions`** sets `MCP_DEFAULTS.selectionDepth` (1), the read-only and destructive hints from the create, update and delete prefixes, explicit nulls on writes only, and the hints above descriptions. An option written after the spread replaces it.
|
|
54
|
+
- **It drops filters and orders on other tables**, to-one ones too. An agent that needs to filter by a related row gets a hand-written field, or filters by the foreign key column.
|
|
55
|
+
- A listing still over budget drops rarer column operators too: an `inputField` after the spread that answers for `*Filter` parents and otherwise calls `toolOptions(...).inputField` (ai-router's `admin/server.ts`).
|
|
56
|
+
- **The rename order:** the driver filters by `include` *before* it renames, so `include` names GraphQL fields (`Mutation.createTask`) while `hints` and clients see the tool name (`create_task`).
|
|
57
|
+
- Where an option of your own is still needed, use graphql-mcp's vocabularies (`MutationHints`, `NullBranches`, `OperationKind`), not bare strings.
|
|
58
|
+
- `TOOLS` and `HINTS` say what the door offers, so they are code, not settings, and stay here.
|
|
59
|
+
- `@cubicecho/graphql-mcp` is the server's own dependency, in the range the kit names.
|
|
60
|
+
|
|
61
|
+
## Mounting it
|
|
62
|
+
|
|
63
|
+
`app.all('/mcp', express.json({ limit: HTTP_DEFAULTS.bodyLimit }), handler)`, before the static handler (boot.md, "In a service").
|
|
64
|
+
|
|
65
|
+
- **`app.all`, not `app.post`:** clients also send GET and DELETE to the same path, and with `post` those get an Express HTML 404.
|
|
66
|
+
- The same body cap as `/graphql`, never a bare `express.json()`. On plain `node:http`, parse the body yourself with the same cap.
|
|
67
|
+
- Close it (`await handler.close()`) in `stopOnSignals`'s `after`, before the pool.
|
|
68
|
+
|
|
69
|
+
## Limits on this door
|
|
70
|
+
|
|
71
|
+
`/mcp` executes against the schema directly, not through Yoga, so `useOperationLimits` never sees an MCP call. What bounds it instead:
|
|
72
|
+
|
|
73
|
+
- drizzle-graphql's `limits` live in the resolvers, so `OPERATION_LIMIT_DEFAULTS.defaultPageSize` and `maxPageSize` hold here as on `/graphql`.
|
|
74
|
+
- graphql-mcp builds each tool's selection itself, and `selectionDepth` keeps it shallow. An agent can't send its own document, so there is no depth or alias attack.
|
|
75
|
+
- `HTTP_DEFAULTS.bodyLimit`, above.
|
|
76
|
+
|
|
77
|
+
**Don't raise `selectionDepth` to make up for a missing field**: add a hand-written field or a narrower tool. The exception is a derived field that is an object, such as ethos's `Habit.current`: depth 1 drops it, so ethos passes 2, as a member of its own override group with that reason.
|
|
78
|
+
|
|
79
|
+
## Budgets and hygiene
|
|
80
|
+
|
|
81
|
+
- **Size budgets:** one tool's entry is at most `MCP_DEFAULTS.maxToolSchemaChars` (40,000), the whole `tools/list` at most `maxToolListChars` (250,000). A test holds both through a real client: `checkMcpBudget(async () => (await client.listTools()).tools)` (testing.md). Prune with `include`, `inputField` and `selectionDepth` rather than changing the GraphQL schema. Raising a budget needs a reason in the commit message; override it as the second argument of `mcpProblems`, never by copying `MCP_DEFAULTS`.
|
|
82
|
+
- **Every hand-written field has a GraphQL `description`.** It *is* the tool documentation. Prose that mentions another tool uses its MCP name (`run_task`).
|
|
83
|
+
- Anything an agent can't subscribe to needs a snapshot query (`runEvents` as a query that returns the events so far).
|
|
84
|
+
- Leave download-shaped fields (exports, blobs) out of `include`.
|
|
85
|
+
- **Leave out every field that answers with a credential or changes how people sign in**: `exclude: ['Query.getSession', 'Query.listSessions']`, and none of `ssoSetup`, `pairSso`, `unpairSso` or the sign-in operations in `include`.
|
|
86
|
+
- Agents authenticate with `x-api-key` (auth.md). An anonymous call reaches the permission layer and is refused, exactly as over `/graphql`.
|
|
87
|
+
- Lines from this door carry the `[mcp]` tag. Never log keys, or tool arguments that may carry secrets.
|
package/skill/sso.md
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# SSO: OIDC sign-in, and pairing a provider from the app
|
|
2
|
+
|
|
3
|
+
How a server signs people in through OIDC and pairs its provider from a setup URL, with `signInPlugins({ oidc })` and `mountAuthRedirects`.
|
|
4
|
+
|
|
5
|
+
**Contents:** [Decisions](#decisions-dont-re-litigate) · [Files](#files) · [Environment and config](#environment-and-config) ·
|
|
6
|
+
[Tables](#tables) · [createAuth](#createauth) · [The two browser legs](#the-two-browser-legs) ·
|
|
7
|
+
[Who may pair](#who-may-pair-authadmints) · [sso/resolvers.ts](#ssoresolversts-the-apps-graphql) ·
|
|
8
|
+
[The app's pages](#the-apps-pages) · [Testing](#testing) · [Moving an app off hand-written pairing](#moving-an-app-off-hand-written-pairing)
|
|
9
|
+
|
|
10
|
+
**Every app and service ships OIDC sign-in, and its provider can be paired from the app.** An operator either sets `OIDC_ISSUER` and friends, or pastes a setup URL from their provider (heautou, or any provider with OAuth 2.0 Dynamic Client Registration) into the login page or Settings. The server registers itself (RFC 7591), and the button appears without a restart. Unpairing deletes the client at the provider (RFC 7592).
|
|
11
|
+
|
|
12
|
+
Why it is the default: self-hosters run several cubicecho apps against one provider, and copying a client id, secret and redirect URI into each `.env` is the step that goes wrong. A setup URL is one paste, and the server registers exactly the redirect URI it serves.
|
|
13
|
+
|
|
14
|
+
**The protocol is `@cubicecho/better-auth-oidc-pairing`**, which `signInPlugins` includes. Never write discovery, registration, the flow or the hand-off by hand; its README is the reference for options, endpoints and refusals. This file is what a server adds around it.
|
|
15
|
+
|
|
16
|
+
- **Leaving it out** is `oidc: false`, with the reason in a comment beside it, and then none of this file applies. The exceptions are in the `cubicecho-backend` skill's service.md.
|
|
17
|
+
- **In a service, enforced roles come first, or in the same release**: without them every account is a full operator. Its admin flag is `users.role` instead of `isAdmin`; everything else is the same.
|
|
18
|
+
- **Anyone the provider lets in may sign in.** Who that is gets decided at the provider (heautou groups).
|
|
19
|
+
|
|
20
|
+
Reference: `cubicecho/ethos` (`server/src/sso/`, `server/src/auth/admin.ts` and their tests).
|
|
21
|
+
|
|
22
|
+
## Decisions (don't re-litigate)
|
|
23
|
+
|
|
24
|
+
| Concern | Choice |
|
|
25
|
+
|---|---|
|
|
26
|
+
| Protocol | OIDC authorization code flow, through `@better-auth/sso` and the pairing plugin |
|
|
27
|
+
| Providers | Several. The environment's (`OIDC_ISSUER`) is fixed and shown as such; up to `maxPairedProviders` more are paired in the app |
|
|
28
|
+
| Where they are kept | Rows of `sso_providers`, read at each sign-in, so **the auth instance is built once, at boot, and never rebuilt** |
|
|
29
|
+
| Session hand-off | The callback ends on the app's `/auth/sso?token=…` with a one-time token, swapped for a bearer session over GraphQL. The session never rides in a URL or becomes a cookie |
|
|
30
|
+
| REST routes | Not mounted, but for the two a browser must be redirected through |
|
|
31
|
+
| Who may pair | The admin at any time. While there are no accounts, **whoever may set the instance up** (auth.md). The first account becomes the admin |
|
|
32
|
+
| Account linking | An address the provider vouches for signs in to the account that has it. The providers are the operator's own |
|
|
33
|
+
| Secrets | The setup token is sent once, to the issuer's registration endpoint, and never stored or logged. `sso_providers` holds client secrets and registration tokens and is not in the GraphQL schema |
|
|
34
|
+
|
|
35
|
+
## Files
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
db/src/models/sso-providers.ts # @better-auth/sso's table, with the pairing plugin's columns
|
|
39
|
+
db/src/models/users.ts # + isAdmin
|
|
40
|
+
server/src/
|
|
41
|
+
core/config.ts # serverUrl, oidcConfig, OIDC_PROVIDER_ID
|
|
42
|
+
core/preflight.ts # the OIDC_* checks
|
|
43
|
+
auth/better-auth.ts # signInPlugins({ oidc })
|
|
44
|
+
auth/admin.ts # isAdmin, claimFirstAdmin, hasUsers, mayChangeSignIn
|
|
45
|
+
auth/endpoints.ts # serves verifyOidcSignIn, throttled
|
|
46
|
+
http/app.ts # mountAuthRedirects
|
|
47
|
+
sso/resolvers.ts # applySsoExtension: ssoSetup, pairSso, unpairSso
|
|
48
|
+
app/app/auth/sso.tsx # spends the one-time token
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
An app with `auth-host.ts`, `sso/pairing.ts` or `sso/settings.ts` is on the old design (the last section).
|
|
52
|
+
|
|
53
|
+
## Environment and config
|
|
54
|
+
|
|
55
|
+
| Variable | Meaning |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | The environment's provider. All three or none: `@better-auth/sso` has no public clients |
|
|
58
|
+
| `OIDC_CLIENT_AUTH` | `client_secret_basic` or `client_secret_post`. Falls back to `OIDC_DEFAULTS.clientAuth` |
|
|
59
|
+
| `OIDC_NAME` | What its button says. Falls back to `OIDC_DEFAULTS.providerName` |
|
|
60
|
+
| `SERVER_URL` | Where a browser reaches this server. `APP_URL` in production (one origin), `http://localhost:PORT` in development |
|
|
61
|
+
|
|
62
|
+
- The redirect URI is the kit's `oidcRedirectUri(serverUrl(), providerId)`: `${serverUrl()}/api/auth/sso/callback/${providerId}`. Log the environment provider's at boot: it is what the operator copies into the provider, exactly.
|
|
63
|
+
- `OIDC_PROVIDER_ID` (`oidc`) is the id the environment's provider is kept under.
|
|
64
|
+
- **Preflight refuses half a setup**: one of the three variables without the others, an issuer that isn't a URL, an `OIDC_CLIENT_AUTH` it doesn't know.
|
|
65
|
+
|
|
66
|
+
## Tables
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
/**
|
|
70
|
+
* The OIDC providers people sign in with: `@better-auth/sso`'s model with the pairing plugin's columns. Written only
|
|
71
|
+
* by the plugin. It holds client secrets and registration tokens, so it is not in the GraphQL schema.
|
|
72
|
+
*/
|
|
73
|
+
export const ssoProviders = pgTable(
|
|
74
|
+
'sso_providers',
|
|
75
|
+
{
|
|
76
|
+
id: id(),
|
|
77
|
+
issuer: text('issuer').notNull(),
|
|
78
|
+
// JSON in the shape @better-auth/sso reads, client secret included.
|
|
79
|
+
oidcConfig: text('oidc_config'),
|
|
80
|
+
samlConfig: text('saml_config'),
|
|
81
|
+
// Always null: pairing is the instance's, not a user's.
|
|
82
|
+
userId: uuid('user_id').references(() => users.id, { onDelete: 'cascade' }),
|
|
83
|
+
providerId: text('provider_id').notNull(),
|
|
84
|
+
organizationId: text('organization_id'),
|
|
85
|
+
domain: text('domain').notNull(),
|
|
86
|
+
domainVerified: boolean('domain_verified'),
|
|
87
|
+
name: text('name'),
|
|
88
|
+
// `env` or `paired`. A row without one is not the plugin's.
|
|
89
|
+
source: text('source'),
|
|
90
|
+
registrationAccessToken: text('registration_access_token'),
|
|
91
|
+
registrationClientUri: text('registration_client_uri'),
|
|
92
|
+
},
|
|
93
|
+
(table) => [uniqueIndex('uq_sso_providers_provider_id').on(table.providerId), index('idx_sso_providers_user_id').on(table.userId)],
|
|
94
|
+
);
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
- The property names are the ones better-auth reads, so keep them.
|
|
98
|
+
- **It is in `SERVER_TABLES`**, which buildSchema excludes beside `AUTH_TABLES`.
|
|
99
|
+
- **`users.isAdmin`**: `boolean('is_admin').notNull().default(false)`. One flag, because the only thing it gates in an app is how people sign in. A service has `users.role`.
|
|
100
|
+
|
|
101
|
+
## createAuth
|
|
102
|
+
|
|
103
|
+
`signInPlugins({ …, oidc: { clientName, canPair, pinned } })`, as in auth.md:
|
|
104
|
+
|
|
105
|
+
- `ssoProvider: ssoProviders` is one of the preset's `tables`.
|
|
106
|
+
- **`pinned` is `oidcConfig()`, passed by index.ts and nowhere else.** The plugin keeps the `oidc` row in step with it, and `null` deletes that row. An instance built only to describe the GraphQL fields leaves it out, or it would delete the real one's row.
|
|
107
|
+
- `databaseHooks.user.create.after` calls `claimFirstAdmin`. Every way an account is made goes through better-auth's adapter, so this is the one place the first account becomes the admin.
|
|
108
|
+
- Building the instance reads nothing from the database, so index.ts calls `await auth.api.listOidcProviders({ headers: new Headers() })` once after migrating: a bad table or a clashing `oidc` row stops the boot instead of the first sign-in.
|
|
109
|
+
|
|
110
|
+
## The two browser legs
|
|
111
|
+
|
|
112
|
+
`mountAuthRedirects(app, { auth, serverUrl: serverUrl(), appUrl: appUrl() })` mounts both, after `/healthz` and before the static handler. Always, because a provider can be paired while the server runs.
|
|
113
|
+
|
|
114
|
+
| Route | What it is |
|
|
115
|
+
|---|---|
|
|
116
|
+
| `GET /api/auth/oidc-pairing/sign-in/:providerId` | Where a login button links to (`oidcSignInUrl`) |
|
|
117
|
+
| `GET /api/auth/sso/callback/:providerId` | Where the provider sends the browser back (`oidcRedirectUri`) |
|
|
118
|
+
|
|
119
|
+
It hands each request to `auth.handler` on `SERVER_URL`'s origin, whatever host the request named, and carries the cookies and redirect back. A failure logs `[auth] OIDC sign_in_failed:` and redirects to `/login?error=sign_in_failed`. Nothing else of better-auth's is mounted.
|
|
120
|
+
|
|
121
|
+
## Who may pair: auth/admin.ts
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
export async function mayChangeSignIn(db: DB, userId: string | null, gate: SetupGate): Promise<boolean> {
|
|
125
|
+
if (userId !== null && (await isAdmin(db, userId))) {
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
return (await hasUsers(db)) === false && gate.isAdmitted();
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
- **Whoever may set the instance up, while there are no accounts; only the admin after.** Otherwise a stranger could point sign-in at a provider of their own and, with accounts linked by address, sign in as anyone.
|
|
133
|
+
- **The plugin asks `canPair` with a user and nothing else**, so `pairSso` runs the call as the caller: `gate.as(code, () => ctx.auth.api.pairOidcProvider(…))`, and `gate.isAdmitted()` answers for that code inside it. It says nothing about accounts, so `hasUsers` is still asked.
|
|
134
|
+
- `claimFirstAdmin` is one `UPDATE … WHERE NOT EXISTS (SELECT 1 FROM users WHERE is_admin)`, so two first sign-ins at once can't both claim it.
|
|
135
|
+
|
|
136
|
+
## sso/resolvers.ts: the app's GraphQL
|
|
137
|
+
|
|
138
|
+
```graphql
|
|
139
|
+
extend type Query {
|
|
140
|
+
"Readable signed out, so a new instance's login page can offer to set sign-in up."
|
|
141
|
+
ssoSetup: SsoSetup!
|
|
142
|
+
}
|
|
143
|
+
extend type Mutation {
|
|
144
|
+
pairSso(setupUrl: String!, setupCode: String): SsoSetup!
|
|
145
|
+
unpairSso(providerId: String!): SsoSetup!
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`SsoSetup` has `providers` (id, name, source `PAIRED` or `ENV`, issuer, redirect URI), `canPair` and `maxProviders`. The resolvers call `listOidcProviders`, `pairOidcProvider` and `unpairOidcProvider` with the request's headers, and map the plugin's `APIError`:
|
|
150
|
+
|
|
151
|
+
| Plugin's code | Error code |
|
|
152
|
+
|---|---|
|
|
153
|
+
| `NOT_ALLOWED_TO_PAIR` | `FORBIDDEN`. With no accounts, the gate's refusal instead (`setupRefused(gate.refusal(code))`): `WRONG_SETUP_CODE` or `SETUP_WINDOW_CLOSED` |
|
|
154
|
+
| `ALREADY_PAIRED`, `TOO_MANY_PROVIDERS` | `CONFLICT` |
|
|
155
|
+
| `NO_SUCH_PROVIDER` | `NOT_FOUND` |
|
|
156
|
+
| `SET_BY_ENVIRONMENT` | `FORBIDDEN`: changed in the environment |
|
|
157
|
+
| `RATE_LIMITED` | `TOO_MANY_REQUESTS` |
|
|
158
|
+
| `BAD_URL`, `NOT_A_PROVIDER`, `NO_REGISTRATION`, `EXPIRED`, `REFUSED` | `BAD_USER_INPUT` |
|
|
159
|
+
|
|
160
|
+
- The plugin's code goes on as `extensions.reason`. Its messages are sentences an operator can act on, and never include the setup token.
|
|
161
|
+
- The plugin answers `issuer` only to a caller who may pair; everyone else sees the name.
|
|
162
|
+
- `pairSso` calls `throttle` first; signed out, on `AuthFlow.SetUp`, because it is another place to guess the setup code.
|
|
163
|
+
- **Leave `ssoSetup`, `pairSso` and `unpairSso` out of `/mcp`**: pairing is a person's decision.
|
|
164
|
+
|
|
165
|
+
## The app's pages
|
|
166
|
+
|
|
167
|
+
- The login page renders a plain link per provider in `authConfig.ssoProviders`, to its `signInUrl`: a full-page navigation, absolute, because in development the server is not the app's origin.
|
|
168
|
+
- `/auth/sso` reads `?token` and spends it **once** (a ref guard: strict mode runs effects twice), stores the bearer token and replaces the route with `/`. On failure it says the sign-in must be finished within a few minutes and only once, and links to `/login`.
|
|
169
|
+
- The setup page, the step after it, and Settings paste a setup URL into `pairSso`.
|
|
170
|
+
|
|
171
|
+
## Testing
|
|
172
|
+
|
|
173
|
+
The protocol is the package's to test. A server tests what it adds, with no `vi.mock` and no real provider: both suites stand up a fake provider on a loopback port and drive the real app over HTTP.
|
|
174
|
+
|
|
175
|
+
- **Pairing** (`__tests__/sso/pairing.test.ts`): the button appears in `authConfig` without a restart; each refusal's code and reason; with no accounts, only with the code, or anyone while setup is open and nobody after; only the admin once there is an account, whatever the code; guesses past the budget; the first account is the admin and no other; unpairing; the environment's provider can't be unpaired; no secret in any answer.
|
|
176
|
+
- **Sign-in** (`__tests__/http/sso.test.ts`): the flow lands on `/auth/sso?token=…`, and the token swaps once for a session; an existing account signs in by the vouched address; a refused callback goes to `/login?error=`.
|
|
177
|
+
|
|
178
|
+
## Moving an app off hand-written pairing
|
|
179
|
+
|
|
180
|
+
Telos-era apps kept one provider in `oidc_settings` and rebuilt better-auth through an `AuthHost`. One commit each:
|
|
181
|
+
|
|
182
|
+
1. db: `sso_providers`, `users.isAdmin` if missing, `npm run db:generate`, and the table in `SERVER_TABLES`.
|
|
183
|
+
2. `createAuth` on `authPreset` and `signInPlugins`. Remove `AuthHost`: `createApp` takes `auth`, and the context carries it.
|
|
184
|
+
3. `mountAuthRedirects`, `auth/admin.ts`, `sso/resolvers.ts` and `verifyOidcSignIn`. Delete `sso/pairing.ts`, `sso/settings.ts` and `auth/auth-host.ts`.
|
|
185
|
+
4. A boot migration that moves the `oidc_settings` row to `sso_providers` (ethos 6.0.0's `server/src/sso/migrate.ts`), then, a release later, one that drops the table.
|
|
186
|
+
|
|
187
|
+
**The redirect URI changes** from `/api/auth/callback/oidc` to `/api/auth/sso/callback/<providerId>`, and a provider refuses one it doesn't have. No alias route can hide it: the release notes say so, as a breaking change.
|
package/skill/testing.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# Tests the kit asks for
|
|
2
|
+
|
|
3
|
+
The checks `/testing` registers, and the tests every server has for what it wired from the kit. The harness they run in (PGlite per file, `createClient`, injecting instead of mocking) is the `cubicecho-backend` skill's testing.md.
|
|
4
|
+
|
|
5
|
+
**Contents:** [Schema conventions](#dbschema-conventionstestts-every-server) · [Postgres version](#dbpostgres-versiontestts-every-server) ·
|
|
6
|
+
[MCP budget](#the-mcp-budget-every-server-with-mcp) · [The sign-in throttle](#the-sign-in-throttle) ·
|
|
7
|
+
[The real app over HTTP](#httpapptestts-the-real-app-over-http)
|
|
8
|
+
|
|
9
|
+
`@cubicecho/server-kit/testing` imports Vitest and PGlite, which are dev dependencies. Import it from tests only.
|
|
10
|
+
|
|
11
|
+
## db/schema-conventions.test.ts (every server)
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import * as dbSchema from '@cubicecho/<app>-db/schema';
|
|
15
|
+
import { checkSchemaConventions } from '@cubicecho/server-kit/testing';
|
|
16
|
+
|
|
17
|
+
checkSchemaConventions(dbSchema, {
|
|
18
|
+
derived: { change_log: 'Triggers write it from the other tables.' },
|
|
19
|
+
});
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
- One test per table: ids, join tables, time zones and foreign-key indexes (database.md). It reads the Drizzle tables, so it needs no database.
|
|
23
|
+
- `derived` and `legacyIds` excuse a table from the id rule, by SQL name, with the reason as a sentence. An exception nothing needs fails. A `derived` table meets the three conditions in database.md; `legacyIds` is for a text id from before ids were UUIDv7, never a new table.
|
|
24
|
+
- Whether a row with an id should have been a join, or the other way round, is for review.
|
|
25
|
+
- A server still on Postgres 17 adds it in the release that moves it to 18. Until then, `schemaProblems` lists what will be needed.
|
|
26
|
+
|
|
27
|
+
## db/postgres-version.test.ts (every server)
|
|
28
|
+
|
|
29
|
+
The Postgres major is written in both compose files, in CI and in the PGlite package, and nothing else compares them. Tests on 18 would pass a migration that 17 in production refuses at boot.
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { resolve } from 'node:path';
|
|
33
|
+
import { checkPostgresVersion } from '@cubicecho/server-kit/testing';
|
|
34
|
+
|
|
35
|
+
checkPostgresVersion({ root: resolve(import.meta.dirname, '../../../..') });
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
- **Compose and CI are one major, 18 or later. PGlite may be ahead, with a warning, and never behind.** A new major can arrive in PGlite first without turning every repo red.
|
|
39
|
+
- It fails when CI has no Postgres job at all: the job is required (the `cubicecho-backend` skill's deploy.md).
|
|
40
|
+
- The root is four levels up in an app (`server/src/__tests__/db/`); two in a service (`tests/db/`).
|
|
41
|
+
- `deployed` and `development` name compose files that are called something else. `testedMajor` goes with the one passed to `prepareDatabase`.
|
|
42
|
+
- A program that is only a local bin has no compose file or deployed major, so it has no version test.
|
|
43
|
+
|
|
44
|
+
## The MCP budget (every server with /mcp)
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
checkMcpBudget(async () => (await client.listTools()).tools);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
List through a real MCP client connected to the real app, as an agent would. It holds one tool to `MCP_DEFAULTS.maxToolSchemaChars` and the listing to `maxToolListChars` (mcp.md).
|
|
51
|
+
|
|
52
|
+
## The sign-in throttle
|
|
53
|
+
|
|
54
|
+
The limiter's own window is the kit's to test. A server tests that each throttled operation calls it, with a small budget and a clock the test owns, so a change to `RATE_LIMIT_DEFAULTS` doesn't break it:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
const SIGN_IN = `mutation($email: String!) { signInMagicLink(email: $email) { status } }`;
|
|
58
|
+
|
|
59
|
+
beforeEach(async () => {
|
|
60
|
+
await resetTestDb(db);
|
|
61
|
+
// No link is sent before there is an account.
|
|
62
|
+
await createUser(db, 'owner@example.com');
|
|
63
|
+
const clock = Date.parse('2026-01-01T00:00:00Z');
|
|
64
|
+
limiter = createRateLimiter({ maxAttempts: 2, windowMinutes: 1 }, () => clock);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('refuses the attempt past the budget', async () => {
|
|
68
|
+
const anonymous = createClient(db, null, { limiter });
|
|
69
|
+
const variables = { email: 'alice@example.com' };
|
|
70
|
+
await anonymous.expectOk(SIGN_IN, variables);
|
|
71
|
+
await anonymous.expectOk(SIGN_IN, variables);
|
|
72
|
+
const [refusal] = (await anonymous.run(SIGN_IN, variables)).errors ?? [];
|
|
73
|
+
expect(refusal?.extensions).toMatchObject({ code: ErrorCode.TooManyRequests, retryAfter: SECONDS_PER_MINUTE });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('counts by account across addresses', async () => {
|
|
77
|
+
// Three addresses, so no address key fills. One account in three casings, so its key does.
|
|
78
|
+
const from = (ip: string) => createClient(db, null, { limiter, ip });
|
|
79
|
+
await from('198.51.100.1').expectOk(SIGN_IN, { email: 'alice@example.com' });
|
|
80
|
+
await from('198.51.100.2').expectOk(SIGN_IN, { email: ' Alice@Example.com' });
|
|
81
|
+
const { code } = await from('198.51.100.3').expectError(SIGN_IN, { email: 'ALICE@example.com' });
|
|
82
|
+
expect(code).toBe(ErrorCode.TooManyRequests);
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
A refusal is asserted by its `code` and `retryAfter`, never by matching the message. The rest of what an auth test holds is auth.md, "Tests that hold the decisions", and sso.md, "Testing".
|
|
87
|
+
|
|
88
|
+
## http/app.test.ts: the real app over HTTP
|
|
89
|
+
|
|
90
|
+
`createApp` has no side effects, so the test builds the app production runs, against PGlite, and talks to it over a socket. This catches what in-process `graphql()` can't: routing order, masking, the operation limits, the body cap, headers, `/healthz`, SSE and the OIDC redirects.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const { maxDepth, maxPageSize } = OPERATION_LIMIT_DEFAULTS;
|
|
94
|
+
/** Past `HTTP_DEFAULTS.bodyLimit`, which is 1 MB. */
|
|
95
|
+
const OVERSIZED_PADDING_BYTES = 1_100_000;
|
|
96
|
+
|
|
97
|
+
beforeAll(async () => {
|
|
98
|
+
db = await createTestDb();
|
|
99
|
+
server = createApp({ db, auth: createTestAuth(db).auth }).listen(0);
|
|
100
|
+
await new Promise<void>((resolve) => server.once('listening', resolve));
|
|
101
|
+
base = `http://127.0.0.1:${portOf(server)}`;
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('reports healthy with a live database', async () => {
|
|
105
|
+
const response = await fetch(`${base}/healthz`);
|
|
106
|
+
expect(response.status).toBe(HttpStatus.Ok);
|
|
107
|
+
expect(await response.json()).toMatchObject({ ok: true });
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('refuses a query deeper than maxDepth before running it', async () => {
|
|
111
|
+
const nest = (levels: number): string => (levels === 0 ? 'id' : `todos { project { ${nest(levels - 1)} } }`);
|
|
112
|
+
const body = await (await post({ query: `{ projects { ${nest(maxDepth)} } }` })).json();
|
|
113
|
+
expect(body.errors[0].extensions.code).toBe(ErrorCode.QueryTooComplex);
|
|
114
|
+
expect(body.data).toBeUndefined();
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('refuses a query whose cost is over maxCost', async () => {
|
|
118
|
+
const body = await (await post({ query: `{ projects(limit: ${maxPageSize}) { todos(limit: ${maxPageSize}) { id } } }` })).json();
|
|
119
|
+
expect(body.errors[0].extensions.code).toBe(ErrorCode.QueryTooComplex);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('rejects a body over the body limit with 413', async () => {
|
|
123
|
+
const response = await post({ query: '{ __typename }', variables: { pad: 'x'.repeat(OVERSIZED_PADDING_BYTES) } });
|
|
124
|
+
expect(response.status).toBe(HttpStatus.PayloadTooLarge);
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
- The depth and cost tests are unauthenticated on purpose: both bounds run before any resolver, so they must refuse a caller who couldn't read the data anyway.
|
|
129
|
+
- `bodyLimit` is a string express parses (`'1mb'`), so the 413 test can't compute from it; `OVERSIZED_PADDING_BYTES` names which limit it is past.
|
|
130
|
+
- One test per server that a list past `maxPageSize` answers `DRIZZLE_LIMIT_EXCEEDED` proves `limits` is configured.
|
|
131
|
+
- A service repeats the 413 test against `/mcp`.
|
|
132
|
+
- A server with `useIntrospectionGate` stubs `NODE_ENV=production` for one file and asks `getIntrospectionQuery()` and a `__type` query as nobody, an app's key and whoever `allow` lets in. It also asks as nobody straight after a person, which proves Yoga's validation cache doesn't hand the person's answer on, and checks a typo gets no `Did you mean`.
|
|
133
|
+
- The masked-error line can be observed with `vi.spyOn(console, 'error')`: assert it holds the original message and **not** the variables sent.
|