@cubicecho/server-kit 0.2.0 → 0.3.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/_agents/docs/04-auth.md +13 -0
- package/_agents/docs/05-graphql.md +24 -0
- package/dist/auth/defaults.d.ts +11 -0
- package/dist/auth/defaults.js +6 -0
- package/dist/auth/index.d.ts +2 -1
- package/dist/auth/index.js +2 -1
- package/dist/auth/rate-limit.d.ts +32 -0
- package/dist/auth/rate-limit.js +60 -0
- package/dist/graphql/defaults.d.ts +17 -0
- package/dist/graphql/defaults.js +10 -0
- package/dist/graphql/errors.d.ts +59 -0
- package/dist/graphql/errors.js +82 -0
- package/dist/graphql/index.d.ts +5 -0
- package/dist/graphql/index.js +5 -0
- package/dist/graphql/logger.d.ts +13 -0
- package/dist/graphql/logger.js +38 -0
- package/dist/graphql/operation-limits.d.ts +25 -0
- package/dist/graphql/operation-limits.js +88 -0
- package/dist/graphql/validation.d.ts +28 -0
- package/dist/graphql/validation.js +19 -0
- package/llms.txt +30 -1
- package/package.json +16 -4
package/_agents/docs/04-auth.md
CHANGED
|
@@ -39,3 +39,16 @@ const auth = betterAuth({
|
|
|
39
39
|
- `paths` moves the app's `login`, `verify` and `signedIn` pages.
|
|
40
40
|
- An option after the spread replaces the preset's whole value, so `session: { … }` has to repeat `expiresIn`.
|
|
41
41
|
- `@better-auth/sso` and `better-auth` are peers: install both in the server.
|
|
42
|
+
|
|
43
|
+
## Rate limiting sign-in
|
|
44
|
+
|
|
45
|
+
better-auth's own limiter never sees a server-side call, so every sign-in step calls `throttle` first.
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { createRateLimiter, throttle } from '@cubicecho/server-kit/auth';
|
|
49
|
+
|
|
50
|
+
const limiter = createRateLimiter();
|
|
51
|
+
throttle({ limiter, ip: request.ip }, 'sign-in-magic-link', email);
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
It counts by address and by account, each step on its own budget, and throws `TOO_MANY_REQUESTS` with `retryAfter`.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# GraphQL
|
|
2
|
+
|
|
3
|
+
`@cubicecho/server-kit/graphql` has what every Yoga 6 server shares: operation limits, coded errors, input validation and a logger that never prints a request's variables.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { graphqlLogger, REQUEST_ID, useOperationLimits } from '@cubicecho/server-kit/graphql';
|
|
7
|
+
import { createYoga } from 'graphql-yoga';
|
|
8
|
+
|
|
9
|
+
const yoga = createYoga({
|
|
10
|
+
schema,
|
|
11
|
+
graphqlEndpoint: '/graphql',
|
|
12
|
+
logging: graphqlLogger,
|
|
13
|
+
requestId: REQUEST_ID,
|
|
14
|
+
plugins: [useOperationLimits()],
|
|
15
|
+
});
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
- `useOperationLimits({ maxCost: 15_000 })` replaces a bound of `OPERATION_LIMIT_DEFAULTS`. It holds subscriptions to them too.
|
|
19
|
+
- Give `buildSchema` the same page sizes: `limits: { defaultLimit: OPERATION_LIMIT_DEFAULTS.defaultPageSize, maxLimit: OPERATION_LIMIT_DEFAULTS.maxPageSize }`.
|
|
20
|
+
- `badInput`, `notFound`, `forbidden`, `conflict`, `unauthenticated` and `rateLimited` build the errors a client reads, by `ErrorCode`. Anything else thrown is masked and logged.
|
|
21
|
+
- `parseOrThrow(schema, value)` takes a zod 4 schema and throws `BAD_USER_INPUT` with its first issue.
|
|
22
|
+
- `requireAuth(context)` returns `context.userId`, or throws `UNAUTHENTICATED`.
|
|
23
|
+
- `REQUEST_ID` gives each request an id of the server's own. It is in the log line of a masked error and in the `x-request-id` response header.
|
|
24
|
+
- In tests, alias `graphql` to `node_modules/graphql/index.js`: Vitest otherwise loads its two builds.
|
package/dist/auth/defaults.d.ts
CHANGED
|
@@ -18,3 +18,14 @@ export interface AuthPaths {
|
|
|
18
18
|
}
|
|
19
19
|
/** Where those pages are when the app overrides nothing. */
|
|
20
20
|
export declare const AUTH_PATHS: Readonly<AuthPaths>;
|
|
21
|
+
/** The sign-in throttle. */
|
|
22
|
+
export interface RateLimitSettings {
|
|
23
|
+
/** Attempts allowed per key inside one window. */
|
|
24
|
+
maxAttempts: number;
|
|
25
|
+
/** How long an attempt counts against its key. */
|
|
26
|
+
windowMinutes: number;
|
|
27
|
+
/** Past this many keys, a hit sweeps out the ones whose window has passed. */
|
|
28
|
+
sweepAtKeys: number;
|
|
29
|
+
}
|
|
30
|
+
/** What `createRateLimiter` uses when the app overrides nothing. */
|
|
31
|
+
export declare const RATE_LIMIT_DEFAULTS: Readonly<RateLimitSettings>;
|
package/dist/auth/defaults.js
CHANGED
|
@@ -10,3 +10,9 @@ export const AUTH_PATHS = Object.freeze({
|
|
|
10
10
|
verify: '/auth/verify',
|
|
11
11
|
signedIn: '/auth/sso',
|
|
12
12
|
});
|
|
13
|
+
/** What `createRateLimiter` uses when the app overrides nothing. */
|
|
14
|
+
export const RATE_LIMIT_DEFAULTS = Object.freeze({
|
|
15
|
+
maxAttempts: 5,
|
|
16
|
+
windowMinutes: 15,
|
|
17
|
+
sweepAtKeys: 10_000,
|
|
18
|
+
});
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
export { AUTH_DEFAULTS, AUTH_PATHS, type AuthPaths, type AuthSettings } from './defaults.ts';
|
|
1
|
+
export { AUTH_DEFAULTS, AUTH_PATHS, type AuthPaths, type AuthSettings, RATE_LIMIT_DEFAULTS, type RateLimitSettings, } from './defaults.ts';
|
|
2
2
|
export { type MagicLink, type SignInOptions, sendsMagicLinks, signInPlugins } from './plugins.ts';
|
|
3
3
|
export { type AuthPresetOptions, type AuthTables, authPreset } from './preset.ts';
|
|
4
|
+
export { createRateLimiter, type RateLimiter, type ThrottleContext, throttle } from './rate-limit.ts';
|
package/dist/auth/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
export { AUTH_DEFAULTS, AUTH_PATHS } from './defaults.js';
|
|
1
|
+
export { AUTH_DEFAULTS, AUTH_PATHS, RATE_LIMIT_DEFAULTS, } from './defaults.js';
|
|
2
2
|
export { sendsMagicLinks, signInPlugins } from './plugins.js';
|
|
3
3
|
export { authPreset } from './preset.js';
|
|
4
|
+
export { createRateLimiter, throttle } from './rate-limit.js';
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type RateLimitSettings } from './defaults.ts';
|
|
2
|
+
/** Sliding-window counter, in process. */
|
|
3
|
+
export interface RateLimiter {
|
|
4
|
+
/**
|
|
5
|
+
* Records one attempt against every key, or throws `TOO_MANY_REQUESTS` when any of them has
|
|
6
|
+
* used its budget. A refused attempt is not recorded, so hammering a closed door does not keep it closed.
|
|
7
|
+
*/
|
|
8
|
+
hit(...keys: string[]): void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Builds a limiter that holds its counts in this process.
|
|
12
|
+
*
|
|
13
|
+
* @param [overrides] - Settings that replace the defaults.
|
|
14
|
+
* @param [now] - The clock, in milliseconds since the epoch. Tests pass their own.
|
|
15
|
+
* @returns The limiter.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createRateLimiter(overrides?: Partial<RateLimitSettings>, now?: () => number): RateLimiter;
|
|
18
|
+
/** What throttling needs of a request's context. */
|
|
19
|
+
export interface ThrottleContext {
|
|
20
|
+
limiter: RateLimiter;
|
|
21
|
+
/** Client address, from Express's `req.ip`. */
|
|
22
|
+
ip: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Counts one sign-in attempt, by the caller's address and by the account when the step names one.
|
|
26
|
+
*
|
|
27
|
+
* @param context - The request's limiter and client address.
|
|
28
|
+
* @param flow - Which sign-in step this is. Each has its own budget.
|
|
29
|
+
* @param [email] - The normalized address.
|
|
30
|
+
* @throws TOO_MANY_REQUESTS once either has used its budget.
|
|
31
|
+
*/
|
|
32
|
+
export declare function throttle(context: ThrottleContext, flow: string, email?: string): void;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { rateLimited } from '../graphql/errors.js';
|
|
2
|
+
import { RATE_LIMIT_DEFAULTS } from './defaults.js';
|
|
3
|
+
const MS_PER_SECOND = 1000;
|
|
4
|
+
const SECONDS_PER_MINUTE = 60;
|
|
5
|
+
/**
|
|
6
|
+
* Builds a limiter that holds its counts in this process.
|
|
7
|
+
*
|
|
8
|
+
* @param [overrides] - Settings that replace the defaults.
|
|
9
|
+
* @param [now] - The clock, in milliseconds since the epoch. Tests pass their own.
|
|
10
|
+
* @returns The limiter.
|
|
11
|
+
*/
|
|
12
|
+
export function createRateLimiter(overrides = {}, now = Date.now) {
|
|
13
|
+
const { maxAttempts, windowMinutes, sweepAtKeys } = { ...RATE_LIMIT_DEFAULTS, ...overrides };
|
|
14
|
+
const windowMs = windowMinutes * SECONDS_PER_MINUTE * MS_PER_SECOND;
|
|
15
|
+
/** When each key was last let through, oldest first. */
|
|
16
|
+
const attempts = new Map();
|
|
17
|
+
const recent = (key, at) => (attempts.get(key) ?? []).filter((attempt) => attempt + windowMs > at);
|
|
18
|
+
// The map would otherwise keep every address ever probed.
|
|
19
|
+
const sweep = (at) => {
|
|
20
|
+
for (const key of attempts.keys()) {
|
|
21
|
+
if (recent(key, at).length === 0) {
|
|
22
|
+
attempts.delete(key);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
hit(...keys) {
|
|
28
|
+
const at = now();
|
|
29
|
+
const live = keys.map((key) => ({ key, times: recent(key, at) }));
|
|
30
|
+
// The oldest attempt is the next to leave the window. Wait for the slowest key.
|
|
31
|
+
const oldest = live.filter(({ times }) => times.length >= maxAttempts).map(({ times }) => times[0] ?? at);
|
|
32
|
+
if (oldest.length > 0) {
|
|
33
|
+
const retryAfter = Math.ceil((Math.max(...oldest) + windowMs - at) / MS_PER_SECOND);
|
|
34
|
+
const minutes = Math.ceil(retryAfter / SECONDS_PER_MINUTE);
|
|
35
|
+
throw rateLimited(`Too many sign-in attempts. Try again in ${minutes} ${minutes === 1 ? 'minute' : 'minutes'}.`, retryAfter);
|
|
36
|
+
}
|
|
37
|
+
for (const { key, times } of live) {
|
|
38
|
+
attempts.set(key, [...times, at]);
|
|
39
|
+
}
|
|
40
|
+
if (attempts.size > sweepAtKeys) {
|
|
41
|
+
sweep(at);
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Counts one sign-in attempt, by the caller's address and by the account when the step names one.
|
|
48
|
+
*
|
|
49
|
+
* @param context - The request's limiter and client address.
|
|
50
|
+
* @param flow - Which sign-in step this is. Each has its own budget.
|
|
51
|
+
* @param [email] - The normalized address.
|
|
52
|
+
* @throws TOO_MANY_REQUESTS once either has used its budget.
|
|
53
|
+
*/
|
|
54
|
+
export function throttle(context, flow, email) {
|
|
55
|
+
const keys = [`${flow}:ip:${context.ip}`];
|
|
56
|
+
if (email !== undefined) {
|
|
57
|
+
keys.push(`${flow}:email:${email}`);
|
|
58
|
+
}
|
|
59
|
+
context.limiter.hit(...keys);
|
|
60
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Bounds on one GraphQL operation. */
|
|
2
|
+
export interface OperationLimitSettings {
|
|
3
|
+
/** Rows a list returns when the request names no `limit`. */
|
|
4
|
+
defaultPageSize: number;
|
|
5
|
+
/** The largest `limit` a request may ask for. */
|
|
6
|
+
maxPageSize: number;
|
|
7
|
+
/** Deepest selection accepted. */
|
|
8
|
+
maxDepth: number;
|
|
9
|
+
/** Aliases per operation. */
|
|
10
|
+
maxAliases: number;
|
|
11
|
+
/** Cost per operation. One full page of rows with about 10 fields fits. A page of full pages doesn't. */
|
|
12
|
+
maxCost: number;
|
|
13
|
+
/** What a field costs when nothing prices it. */
|
|
14
|
+
defaultFieldCost: number;
|
|
15
|
+
}
|
|
16
|
+
/** What `useOperationLimits` and an app's `buildSchema` use when the app overrides nothing. */
|
|
17
|
+
export declare const OPERATION_LIMIT_DEFAULTS: Readonly<OperationLimitSettings>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Every value someone might tune, as plain data. Nothing here computes, reads the environment or imports.
|
|
2
|
+
/** What `useOperationLimits` and an app's `buildSchema` use when the app overrides nothing. */
|
|
3
|
+
export const OPERATION_LIMIT_DEFAULTS = Object.freeze({
|
|
4
|
+
defaultPageSize: 50,
|
|
5
|
+
maxPageSize: 500,
|
|
6
|
+
maxDepth: 8,
|
|
7
|
+
maxAliases: 15,
|
|
8
|
+
maxCost: 10_000,
|
|
9
|
+
defaultFieldCost: 1,
|
|
10
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { GraphQLError } from 'graphql';
|
|
2
|
+
/** The `extensions.code` values clients branch on. */
|
|
3
|
+
export declare const ErrorCode: {
|
|
4
|
+
readonly Unauthenticated: 'UNAUTHENTICATED';
|
|
5
|
+
readonly NotFound: 'NOT_FOUND';
|
|
6
|
+
readonly BadUserInput: 'BAD_USER_INPUT';
|
|
7
|
+
readonly TooManyRequests: 'TOO_MANY_REQUESTS';
|
|
8
|
+
readonly QueryTooComplex: 'QUERY_TOO_COMPLEX';
|
|
9
|
+
readonly Forbidden: 'FORBIDDEN';
|
|
10
|
+
readonly Conflict: 'CONFLICT';
|
|
11
|
+
};
|
|
12
|
+
export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
|
|
13
|
+
/** Arguments the caller can fix. */
|
|
14
|
+
export declare const badInput: (message: string) => GraphQLError;
|
|
15
|
+
/** Missing, or someone else's. Deliberately one code. */
|
|
16
|
+
export declare const notFound: (message: string) => GraphQLError;
|
|
17
|
+
/** This kind of caller may never do this. Never for a row: that is NOT_FOUND, so its existence is not confirmed. */
|
|
18
|
+
export declare const forbidden: (message: string) => GraphQLError;
|
|
19
|
+
/** The request is fine, but the instance is in a state that refuses it. */
|
|
20
|
+
export declare const conflict: (message: string) => GraphQLError;
|
|
21
|
+
/**
|
|
22
|
+
* Builds the signed-out refusal. Clients drop their session on it.
|
|
23
|
+
*
|
|
24
|
+
* @param [message] - Client-readable message.
|
|
25
|
+
* @returns The error, for the caller to throw.
|
|
26
|
+
*/
|
|
27
|
+
export declare function unauthenticated(message?: string): GraphQLError;
|
|
28
|
+
/**
|
|
29
|
+
* Builds the rate-limit refusal.
|
|
30
|
+
*
|
|
31
|
+
* @param message - Client-readable message.
|
|
32
|
+
* @param retryAfter - Seconds until the caller may try again.
|
|
33
|
+
* @returns The error, for the caller to throw.
|
|
34
|
+
*/
|
|
35
|
+
export declare function rateLimited(message: string, retryAfter: number): GraphQLError;
|
|
36
|
+
/**
|
|
37
|
+
* Builds the refusal of an operation that asks for more than one may.
|
|
38
|
+
*
|
|
39
|
+
* @param message - Which limit it went over.
|
|
40
|
+
* @returns The error, answered as a 400.
|
|
41
|
+
*/
|
|
42
|
+
export declare function tooComplex(message: string): GraphQLError;
|
|
43
|
+
/**
|
|
44
|
+
* Reads the signed-in user's id.
|
|
45
|
+
*
|
|
46
|
+
* @param context - Request context.
|
|
47
|
+
* @returns The user's id.
|
|
48
|
+
* @throws UNAUTHENTICATED when nobody is signed in: the id is missing, null or empty.
|
|
49
|
+
*/
|
|
50
|
+
export declare function requireAuth(context: {
|
|
51
|
+
userId?: string | null;
|
|
52
|
+
}): string;
|
|
53
|
+
/**
|
|
54
|
+
* Reads the message of any caught value.
|
|
55
|
+
*
|
|
56
|
+
* @param error - Whatever was thrown.
|
|
57
|
+
* @returns `error.message` for an Error, otherwise the value as text.
|
|
58
|
+
*/
|
|
59
|
+
export declare function errorMessage(error: unknown): string;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { GraphQLError } from 'graphql';
|
|
2
|
+
/** The status an operation refused before it runs is answered with. */
|
|
3
|
+
const BAD_REQUEST = 400;
|
|
4
|
+
/** The `extensions.code` values clients branch on. */
|
|
5
|
+
export const ErrorCode = {
|
|
6
|
+
Unauthenticated: 'UNAUTHENTICATED',
|
|
7
|
+
NotFound: 'NOT_FOUND',
|
|
8
|
+
BadUserInput: 'BAD_USER_INPUT',
|
|
9
|
+
TooManyRequests: 'TOO_MANY_REQUESTS',
|
|
10
|
+
QueryTooComplex: 'QUERY_TOO_COMPLEX',
|
|
11
|
+
Forbidden: 'FORBIDDEN',
|
|
12
|
+
Conflict: 'CONFLICT',
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Makes an error factory for one code.
|
|
16
|
+
*
|
|
17
|
+
* @param code - The `extensions.code` value.
|
|
18
|
+
* @returns A function from message to error.
|
|
19
|
+
*/
|
|
20
|
+
const withCode = (code) => (message) => new GraphQLError(message, { extensions: { code } });
|
|
21
|
+
/** Arguments the caller can fix. */
|
|
22
|
+
export const badInput = withCode(ErrorCode.BadUserInput);
|
|
23
|
+
/** Missing, or someone else's. Deliberately one code. */
|
|
24
|
+
export const notFound = withCode(ErrorCode.NotFound);
|
|
25
|
+
/** This kind of caller may never do this. Never for a row: that is NOT_FOUND, so its existence is not confirmed. */
|
|
26
|
+
export const forbidden = withCode(ErrorCode.Forbidden);
|
|
27
|
+
/** The request is fine, but the instance is in a state that refuses it. */
|
|
28
|
+
export const conflict = withCode(ErrorCode.Conflict);
|
|
29
|
+
/**
|
|
30
|
+
* Builds the signed-out refusal. Clients drop their session on it.
|
|
31
|
+
*
|
|
32
|
+
* @param [message] - Client-readable message.
|
|
33
|
+
* @returns The error, for the caller to throw.
|
|
34
|
+
*/
|
|
35
|
+
export function unauthenticated(message = 'Not authenticated') {
|
|
36
|
+
return new GraphQLError(message, { extensions: { code: ErrorCode.Unauthenticated } });
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Builds the rate-limit refusal.
|
|
40
|
+
*
|
|
41
|
+
* @param message - Client-readable message.
|
|
42
|
+
* @param retryAfter - Seconds until the caller may try again.
|
|
43
|
+
* @returns The error, for the caller to throw.
|
|
44
|
+
*/
|
|
45
|
+
export function rateLimited(message, retryAfter) {
|
|
46
|
+
return new GraphQLError(message, { extensions: { code: ErrorCode.TooManyRequests, retryAfter } });
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Builds the refusal of an operation that asks for more than one may.
|
|
50
|
+
*
|
|
51
|
+
* @param message - Which limit it went over.
|
|
52
|
+
* @returns The error, answered as a 400.
|
|
53
|
+
*/
|
|
54
|
+
export function tooComplex(message) {
|
|
55
|
+
return new GraphQLError(message, {
|
|
56
|
+
extensions: { code: ErrorCode.QueryTooComplex, http: { status: BAD_REQUEST } },
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Reads the signed-in user's id.
|
|
61
|
+
*
|
|
62
|
+
* @param context - Request context.
|
|
63
|
+
* @returns The user's id.
|
|
64
|
+
* @throws UNAUTHENTICATED when nobody is signed in: the id is missing, null or empty.
|
|
65
|
+
*/
|
|
66
|
+
export function requireAuth(context) {
|
|
67
|
+
const { userId } = context;
|
|
68
|
+
const isSignedOut = userId === undefined || userId === null || userId === '';
|
|
69
|
+
if (isSignedOut) {
|
|
70
|
+
throw unauthenticated();
|
|
71
|
+
}
|
|
72
|
+
return userId;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Reads the message of any caught value.
|
|
76
|
+
*
|
|
77
|
+
* @param error - Whatever was thrown.
|
|
78
|
+
* @returns `error.message` for an Error, otherwise the value as text.
|
|
79
|
+
*/
|
|
80
|
+
export function errorMessage(error) {
|
|
81
|
+
return error instanceof Error ? error.message : String(error);
|
|
82
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { OPERATION_LIMIT_DEFAULTS, type OperationLimitSettings } from './defaults.ts';
|
|
2
|
+
export { badInput, conflict, ErrorCode, errorMessage, forbidden, notFound, rateLimited, requireAuth, tooComplex, unauthenticated, } from './errors.ts';
|
|
3
|
+
export { graphqlLogger, REQUEST_ID } from './logger.ts';
|
|
4
|
+
export { assertWithinLimits, type Operation, useOperationLimits } from './operation-limits.ts';
|
|
5
|
+
export { type Parser, parseOrThrow } from './validation.ts';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { OPERATION_LIMIT_DEFAULTS } from './defaults.js';
|
|
2
|
+
export { badInput, conflict, ErrorCode, errorMessage, forbidden, notFound, rateLimited, requireAuth, tooComplex, unauthenticated, } from './errors.js';
|
|
3
|
+
export { graphqlLogger, REQUEST_ID } from './logger.js';
|
|
4
|
+
export { assertWithinLimits, useOperationLimits } from './operation-limits.js';
|
|
5
|
+
export { parseOrThrow } from './validation.js';
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Logger } from 'graphql-yoga';
|
|
2
|
+
/**
|
|
3
|
+
* Yoga's logger with the `[graphql]` tag: warnings and errors, each with its request's id.
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* The level is fixed, so `LOG_LEVEL` and `DEBUG` in the environment cannot turn on lines that describe requests.
|
|
7
|
+
* An attribute that is not named here is never printed, since operation variables carry sign-in tokens.
|
|
8
|
+
*/
|
|
9
|
+
export declare const graphqlLogger: Logger;
|
|
10
|
+
/** Yoga's `requestId` option: each request gets an id of ours, never one the caller chose. */
|
|
11
|
+
export declare const REQUEST_ID: Readonly<{
|
|
12
|
+
trustHeader: false;
|
|
13
|
+
}>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { GraphQLError } from 'graphql';
|
|
2
|
+
import { Logger } from 'graphql-yoga';
|
|
3
|
+
const TAG = '[graphql]';
|
|
4
|
+
/**
|
|
5
|
+
* Picks what to print for a logged error. A masked one prints its path and its cause, which carries the real stack.
|
|
6
|
+
*
|
|
7
|
+
* @param error - What was logged.
|
|
8
|
+
* @returns The values to print.
|
|
9
|
+
*/
|
|
10
|
+
function describe(error) {
|
|
11
|
+
if (error === undefined) {
|
|
12
|
+
return [];
|
|
13
|
+
}
|
|
14
|
+
const isMasked = error instanceof GraphQLError && error.originalError !== undefined;
|
|
15
|
+
return isMasked ? [error.path?.join('.') ?? '', error.originalError] : [error];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Yoga's logger with the `[graphql]` tag: warnings and errors, each with its request's id.
|
|
19
|
+
*
|
|
20
|
+
* @remarks
|
|
21
|
+
* The level is fixed, so `LOG_LEVEL` and `DEBUG` in the environment cannot turn on lines that describe requests.
|
|
22
|
+
* An attribute that is not named here is never printed, since operation variables carry sign-in tokens.
|
|
23
|
+
*/
|
|
24
|
+
export const graphqlLogger = new Logger({
|
|
25
|
+
level: 'warn',
|
|
26
|
+
writers: [
|
|
27
|
+
{
|
|
28
|
+
write: (level, attributes, message) => {
|
|
29
|
+
const { err, requestId } = Array.isArray(attributes) ? {} : (attributes ?? {});
|
|
30
|
+
const parts = [TAG, requestId, message].filter((part) => part !== undefined && part !== null && part !== '');
|
|
31
|
+
const print = level === 'error' ? console.error : console.warn;
|
|
32
|
+
print(...parts, ...describe(err));
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
],
|
|
36
|
+
});
|
|
37
|
+
/** Yoga's `requestId` option: each request gets an id of ours, never one the caller chose. */
|
|
38
|
+
export const REQUEST_ID = Object.freeze({ trustHeader: false });
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type DocumentNode, type GraphQLSchema } from 'graphql';
|
|
2
|
+
import type { Plugin } from 'graphql-yoga';
|
|
3
|
+
import { type OperationLimitSettings } from './defaults.ts';
|
|
4
|
+
/** One request's operation, as pricing needs it. */
|
|
5
|
+
export interface Operation {
|
|
6
|
+
schema: GraphQLSchema;
|
|
7
|
+
document: DocumentNode;
|
|
8
|
+
operationName?: string;
|
|
9
|
+
variables?: Record<string, unknown>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Holds an operation to the limits.
|
|
13
|
+
*
|
|
14
|
+
* @param operation - The validated operation.
|
|
15
|
+
* @param [overrides] - Bounds that replace the defaults.
|
|
16
|
+
* @throws QUERY_TOO_COMPLEX when it is too deep, too aliased or too costly.
|
|
17
|
+
*/
|
|
18
|
+
export declare function assertWithinLimits(operation: Operation, overrides?: Partial<OperationLimitSettings>): void;
|
|
19
|
+
/**
|
|
20
|
+
* The Yoga plugin that holds every operation, subscriptions included, to the limits before it runs.
|
|
21
|
+
*
|
|
22
|
+
* @param [overrides] - Bounds that replace the defaults.
|
|
23
|
+
* @returns The plugin, for `createYoga({ plugins })`.
|
|
24
|
+
*/
|
|
25
|
+
export declare function useOperationLimits(overrides?: Partial<OperationLimitSettings>): Plugin;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { maxAliasesRule } from '@escape.tech/graphql-armor-max-aliases';
|
|
2
|
+
import { maxDepthRule } from '@escape.tech/graphql-armor-max-depth';
|
|
3
|
+
import { GraphQLError, TypeNameMetaFieldDef, validate, } from 'graphql';
|
|
4
|
+
import { fieldExtensionsEstimator, getComplexity, simpleEstimator, } from 'graphql-query-complexity';
|
|
5
|
+
import { OPERATION_LIMIT_DEFAULTS } from './defaults.js';
|
|
6
|
+
import { tooComplex } from './errors.js';
|
|
7
|
+
/**
|
|
8
|
+
* Prices `__typename` at nothing, since Apollo adds one to every selection.
|
|
9
|
+
*
|
|
10
|
+
* @param options - The field being priced.
|
|
11
|
+
* @param options.field - The field.
|
|
12
|
+
* @returns 0 for `__typename`, otherwise undefined, so the next estimator prices it.
|
|
13
|
+
*/
|
|
14
|
+
const typenameEstimator = ({ field }) => field.name === TypeNameMetaFieldDef.name ? 0 : undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Prices an operation with its own variables.
|
|
17
|
+
*
|
|
18
|
+
* @param operation - The operation.
|
|
19
|
+
* @param defaultFieldCost - What a field costs when nothing prices it.
|
|
20
|
+
* @returns The cost, or 0 when the variables do not fit, which execution reports.
|
|
21
|
+
*/
|
|
22
|
+
function priceOf({ schema, document, operationName, variables = {} }, defaultFieldCost) {
|
|
23
|
+
try {
|
|
24
|
+
return getComplexity({
|
|
25
|
+
schema,
|
|
26
|
+
query: document,
|
|
27
|
+
operationName,
|
|
28
|
+
variables,
|
|
29
|
+
estimators: [
|
|
30
|
+
typenameEstimator,
|
|
31
|
+
fieldExtensionsEstimator(),
|
|
32
|
+
simpleEstimator({ defaultComplexity: defaultFieldCost }),
|
|
33
|
+
],
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error instanceof GraphQLError) {
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Holds an operation to the limits.
|
|
45
|
+
*
|
|
46
|
+
* @param operation - The validated operation.
|
|
47
|
+
* @param [overrides] - Bounds that replace the defaults.
|
|
48
|
+
* @throws QUERY_TOO_COMPLEX when it is too deep, too aliased or too costly.
|
|
49
|
+
*/
|
|
50
|
+
export function assertWithinLimits(operation, overrides = {}) {
|
|
51
|
+
const { maxDepth, maxAliases, maxCost, defaultFieldCost } = { ...OPERATION_LIMIT_DEFAULTS, ...overrides };
|
|
52
|
+
// Armor's own error has no code, so each rule throws ours in its place.
|
|
53
|
+
const refuse = (message) => () => {
|
|
54
|
+
throw tooComplex(message);
|
|
55
|
+
};
|
|
56
|
+
validate(operation.schema, operation.document, [
|
|
57
|
+
maxDepthRule({
|
|
58
|
+
n: maxDepth,
|
|
59
|
+
flattenFragments: true,
|
|
60
|
+
propagateOnRejection: false,
|
|
61
|
+
onReject: [refuse(`A query may nest at most ${maxDepth} levels deep.`)],
|
|
62
|
+
}),
|
|
63
|
+
maxAliasesRule({
|
|
64
|
+
n: maxAliases,
|
|
65
|
+
propagateOnRejection: false,
|
|
66
|
+
onReject: [refuse(`A query may use at most ${maxAliases} aliases.`)],
|
|
67
|
+
}),
|
|
68
|
+
]);
|
|
69
|
+
const cost = priceOf(operation, defaultFieldCost);
|
|
70
|
+
if (cost > maxCost) {
|
|
71
|
+
throw tooComplex(`This query costs ${cost}; the most one may cost is ${maxCost}. Ask for fewer rows.`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The Yoga plugin that holds every operation, subscriptions included, to the limits before it runs.
|
|
76
|
+
*
|
|
77
|
+
* @param [overrides] - Bounds that replace the defaults.
|
|
78
|
+
* @returns The plugin, for `createYoga({ plugins })`.
|
|
79
|
+
*/
|
|
80
|
+
export function useOperationLimits(overrides = {}) {
|
|
81
|
+
const check = ({ args }) => assertWithinLimits({
|
|
82
|
+
schema: args.schema,
|
|
83
|
+
document: args.document,
|
|
84
|
+
operationName: args.operationName ?? undefined,
|
|
85
|
+
variables: args.variableValues ?? undefined,
|
|
86
|
+
}, overrides);
|
|
87
|
+
return { onExecute: check, onSubscribe: check };
|
|
88
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A zod schema, by the one method used here.
|
|
3
|
+
*
|
|
4
|
+
* @typeParam Output - What it parses to.
|
|
5
|
+
*/
|
|
6
|
+
export interface Parser<Output> {
|
|
7
|
+
safeParse: (value: unknown) => {
|
|
8
|
+
success: true;
|
|
9
|
+
data: Output;
|
|
10
|
+
} | {
|
|
11
|
+
success: false;
|
|
12
|
+
error: {
|
|
13
|
+
issues: readonly {
|
|
14
|
+
message: string;
|
|
15
|
+
}[];
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Parses with zod, turning a failure into BAD_USER_INPUT.
|
|
21
|
+
*
|
|
22
|
+
* @typeParam Output - What the schema parses to.
|
|
23
|
+
* @param schema - The zod schema.
|
|
24
|
+
* @param value - Untrusted input.
|
|
25
|
+
* @returns The parsed value.
|
|
26
|
+
* @throws BAD_USER_INPUT with the first issue's message.
|
|
27
|
+
*/
|
|
28
|
+
export declare function parseOrThrow<Output>(schema: Parser<Output>, value: unknown): Output;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { badInput } from './errors.js';
|
|
2
|
+
/** What the caller reads when a schema refuses a value and says nothing of its own. */
|
|
3
|
+
const INVALID = 'That input is not valid.';
|
|
4
|
+
/**
|
|
5
|
+
* Parses with zod, turning a failure into BAD_USER_INPUT.
|
|
6
|
+
*
|
|
7
|
+
* @typeParam Output - What the schema parses to.
|
|
8
|
+
* @param schema - The zod schema.
|
|
9
|
+
* @param value - Untrusted input.
|
|
10
|
+
* @returns The parsed value.
|
|
11
|
+
* @throws BAD_USER_INPUT with the first issue's message.
|
|
12
|
+
*/
|
|
13
|
+
export function parseOrThrow(schema, value) {
|
|
14
|
+
const result = schema.safeParse(value);
|
|
15
|
+
if (result.success === false) {
|
|
16
|
+
throw badInput(result.error.issues[0]?.message ?? INVALID);
|
|
17
|
+
}
|
|
18
|
+
return result.data;
|
|
19
|
+
}
|
package/llms.txt
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
Agent-facing docs for @cubicecho/server-kit: one task or concept per page, then what each package.json "exports" entry exports. Generated from _agents/docs/ and the doc comments in src/ by @cubicecho/agent-docs; edit those, not this file.
|
|
6
6
|
|
|
7
|
-
Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@electric-sql/pglite` ^0.5.0 (optional), `better-auth` >=1.7.28 <1.8.0, `drizzle-orm` 1.0.0-rc.5, `postgres` ^3.4.0, `vitest` ^5.0.0 (optional).
|
|
7
|
+
Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@electric-sql/pglite` ^0.5.0 (optional), `better-auth` >=1.7.28 <1.8.0, `drizzle-orm` 1.0.0-rc.5, `graphql` ^16.0.0, `graphql-yoga` ^6.0.0, `postgres` ^3.4.0, `vitest` ^5.0.0 (optional).
|
|
8
8
|
|
|
9
9
|
## Docs
|
|
10
10
|
|
|
@@ -12,6 +12,7 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@ele
|
|
|
12
12
|
- [Columns](_agents/docs/02-columns.md): `@cubicecho/server-kit/columns` has the Drizzle columns that keep a table to the conventions: a UUIDv7 id, moments with a time zone, and a table limited to one row.
|
|
13
13
|
- [Test checks](_agents/docs/03-testing.md): `@cubicecho/server-kit/testing` registers Vitest tests that hold an app to the backend standard: its tables, and the Postgres it runs.
|
|
14
14
|
- [Auth preset](_agents/docs/04-auth.md): `@cubicecho/server-kit/auth` has the better-auth options and sign-in plugins every server shares: sessions in Postgres, bearer tokens, emailed links, and OIDC with pairing. The app still calls `betterAuth`, so it adds its own plugins and hooks and keeps exact types.
|
|
15
|
+
- [GraphQL](_agents/docs/05-graphql.md): `@cubicecho/server-kit/graphql` has what every Yoga 6 server shares: operation limits, coded errors, input validation and a logger that never prints a request's variables.
|
|
15
16
|
- [Common mistakes](_agents/docs/common-mistakes.md): What goes wrong when the kit is wired up slightly differently, and the fix for each.
|
|
16
17
|
|
|
17
18
|
## Exports: @cubicecho/server-kit/auth
|
|
@@ -20,6 +21,8 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@ele
|
|
|
20
21
|
- `AUTH_PATHS`: Where those pages are when the app overrides nothing.
|
|
21
22
|
- `AuthPaths` (type): The app's pages a sign-in passes through, as paths under `appUrl`.
|
|
22
23
|
- `AuthSettings` (type): Session and link lifetimes.
|
|
24
|
+
- `RATE_LIMIT_DEFAULTS`: What `createRateLimiter` uses when the app overrides nothing.
|
|
25
|
+
- `RateLimitSettings` (type): The sign-in throttle.
|
|
23
26
|
- `MagicLink` (type): What delivering one sign-in link is given.
|
|
24
27
|
- `SignInOptions` (type): What an app gives `signInPlugins`.
|
|
25
28
|
- `sendsMagicLinks`: Whether an instance emails sign-in links.
|
|
@@ -27,6 +30,10 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@ele
|
|
|
27
30
|
- `AuthPresetOptions` (type): What an app gives the preset.
|
|
28
31
|
- `AuthTables` (type): The tables better-auth keeps, by its own model names.
|
|
29
32
|
- `authPreset`: The better-auth options every server shares.
|
|
33
|
+
- `createRateLimiter`: Builds a limiter that holds its counts in this process.
|
|
34
|
+
- `RateLimiter` (type): Sliding-window counter, in process.
|
|
35
|
+
- `ThrottleContext` (type): What throttling needs of a request's context.
|
|
36
|
+
- `throttle`: Counts one sign-in attempt, by the caller's address and by the account when the step names one.
|
|
30
37
|
|
|
31
38
|
## Exports: @cubicecho/server-kit/columns
|
|
32
39
|
|
|
@@ -57,6 +64,28 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@ele
|
|
|
57
64
|
- `Queryable` (type): Anything that can run a query: the Drizzle client on postgres-js, pg or PGlite.
|
|
58
65
|
- `waitForDatabase`: Waits until Postgres answers a query.
|
|
59
66
|
|
|
67
|
+
## Exports: @cubicecho/server-kit/graphql
|
|
68
|
+
|
|
69
|
+
- `OPERATION_LIMIT_DEFAULTS`: What `useOperationLimits` and an app's `buildSchema` use when the app overrides nothing.
|
|
70
|
+
- `OperationLimitSettings` (type): Bounds on one GraphQL operation.
|
|
71
|
+
- `badInput`: Arguments the caller can fix.
|
|
72
|
+
- `conflict`: The request is fine, but the instance is in a state that refuses it.
|
|
73
|
+
- `ErrorCode`: The `extensions.code` values clients branch on.
|
|
74
|
+
- `errorMessage`: Reads the message of any caught value.
|
|
75
|
+
- `forbidden`: This kind of caller may never do this.
|
|
76
|
+
- `notFound`: Missing, or someone else's.
|
|
77
|
+
- `rateLimited`: Builds the rate-limit refusal.
|
|
78
|
+
- `requireAuth`: Reads the signed-in user's id.
|
|
79
|
+
- `tooComplex`: Builds the refusal of an operation that asks for more than one may.
|
|
80
|
+
- `unauthenticated`: Builds the signed-out refusal.
|
|
81
|
+
- `graphqlLogger`: Yoga's logger with the `[graphql]` tag: warnings and errors, each with its request's id.
|
|
82
|
+
- `REQUEST_ID`: Yoga's `requestId` option: each request gets an id of ours, never one the caller chose.
|
|
83
|
+
- `assertWithinLimits`: Holds an operation to the limits.
|
|
84
|
+
- `Operation` (type): One request's operation, as pricing needs it.
|
|
85
|
+
- `useOperationLimits`: The Yoga plugin that holds every operation, subscriptions included, to the limits before it runs.
|
|
86
|
+
- `Parser` (type): A zod schema, by the one method used here.
|
|
87
|
+
- `parseOrThrow`: Parses with zod, turning a failure into BAD_USER_INPUT.
|
|
88
|
+
|
|
60
89
|
## Exports: @cubicecho/server-kit/testing
|
|
61
90
|
|
|
62
91
|
- `PostgresFiles` (type): Where a repo says which Postgres it runs.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cubicecho/server-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "The server code every cubicecho GraphQL backend shares: database boot, id columns and the checks that keep a schema to the standard.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Benjamin Van Treese",
|
|
@@ -35,6 +35,10 @@
|
|
|
35
35
|
"types": "./dist/db/index.d.ts",
|
|
36
36
|
"import": "./dist/db/index.js"
|
|
37
37
|
},
|
|
38
|
+
"./graphql": {
|
|
39
|
+
"types": "./dist/graphql/index.d.ts",
|
|
40
|
+
"import": "./dist/graphql/index.js"
|
|
41
|
+
},
|
|
38
42
|
"./testing": {
|
|
39
43
|
"types": "./dist/testing/index.d.ts",
|
|
40
44
|
"import": "./dist/testing/index.js"
|
|
@@ -49,7 +53,7 @@
|
|
|
49
53
|
"access": "public"
|
|
50
54
|
},
|
|
51
55
|
"scripts": {
|
|
52
|
-
"build": "tsc -p tsconfig.build.json",
|
|
56
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
53
57
|
"prepack": "npm run build && agent-docs llms",
|
|
54
58
|
"check": "npm run check:biome && npm run check:types",
|
|
55
59
|
"check:biome": "biome check --write .",
|
|
@@ -63,6 +67,8 @@
|
|
|
63
67
|
"@electric-sql/pglite": "^0.5.0",
|
|
64
68
|
"better-auth": ">=1.7.28 <1.8.0",
|
|
65
69
|
"drizzle-orm": "1.0.0-rc.5",
|
|
70
|
+
"graphql": "^16.0.0",
|
|
71
|
+
"graphql-yoga": "^6.0.0",
|
|
66
72
|
"postgres": "^3.4.0",
|
|
67
73
|
"vitest": "^5.0.0"
|
|
68
74
|
},
|
|
@@ -89,13 +95,19 @@
|
|
|
89
95
|
"better-auth": "^1.7.28",
|
|
90
96
|
"drizzle-kit": "^1.0.0-rc.5",
|
|
91
97
|
"drizzle-orm": "^1.0.0-rc.5",
|
|
98
|
+
"express": "^5.3.0",
|
|
92
99
|
"graphql": "^16.15.0",
|
|
100
|
+
"graphql-yoga": "^6.1.1",
|
|
93
101
|
"postgres": "^3.4.10",
|
|
94
102
|
"semantic-release": "^25.0.9",
|
|
95
103
|
"typescript": "^7.0.2",
|
|
96
|
-
"vitest": "^5.1.2"
|
|
104
|
+
"vitest": "^5.1.2",
|
|
105
|
+
"zod": "^4.6.7"
|
|
97
106
|
},
|
|
98
107
|
"dependencies": {
|
|
99
|
-
"@cubicecho/better-auth-oidc-pairing": "^1.1.0"
|
|
108
|
+
"@cubicecho/better-auth-oidc-pairing": "^1.1.0",
|
|
109
|
+
"@escape.tech/graphql-armor-max-aliases": "^2.6.3",
|
|
110
|
+
"@escape.tech/graphql-armor-max-depth": "^2.4.3",
|
|
111
|
+
"graphql-query-complexity": "^2.0.0"
|
|
100
112
|
}
|
|
101
113
|
}
|