@cubicecho/server-kit 0.1.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.
Files changed (60) hide show
  1. package/LICENSE +0 -0
  2. package/README.md +0 -0
  3. package/_agents/docs/01-database.md +0 -0
  4. package/_agents/docs/02-columns.md +0 -0
  5. package/_agents/docs/03-testing.md +0 -0
  6. package/_agents/docs/04-auth.md +54 -0
  7. package/_agents/docs/05-graphql.md +24 -0
  8. package/_agents/docs/common-mistakes.md +0 -0
  9. package/dist/auth/defaults.d.ts +31 -0
  10. package/dist/auth/defaults.js +18 -0
  11. package/dist/auth/index.d.ts +4 -0
  12. package/dist/auth/index.js +4 -0
  13. package/dist/auth/plugins.d.ts +1270 -0
  14. package/dist/auth/plugins.js +39 -0
  15. package/dist/auth/preset.d.ts +53 -0
  16. package/dist/auth/preset.js +21 -0
  17. package/dist/auth/rate-limit.d.ts +32 -0
  18. package/dist/auth/rate-limit.js +60 -0
  19. package/dist/columns/index.d.ts +0 -0
  20. package/dist/columns/index.js +0 -0
  21. package/dist/consts.d.ts +0 -0
  22. package/dist/consts.js +0 -0
  23. package/dist/db/connection.d.ts +0 -0
  24. package/dist/db/connection.js +0 -0
  25. package/dist/db/create.d.ts +0 -0
  26. package/dist/db/create.js +0 -0
  27. package/dist/db/defaults.d.ts +0 -0
  28. package/dist/db/defaults.js +0 -0
  29. package/dist/db/errors.d.ts +0 -0
  30. package/dist/db/errors.js +0 -0
  31. package/dist/db/index.d.ts +0 -0
  32. package/dist/db/index.js +0 -0
  33. package/dist/db/prepare.d.ts +0 -0
  34. package/dist/db/prepare.js +0 -0
  35. package/dist/db/ssl.d.ts +0 -0
  36. package/dist/db/ssl.js +0 -0
  37. package/dist/db/version.d.ts +0 -0
  38. package/dist/db/version.js +0 -0
  39. package/dist/db/wait.d.ts +0 -0
  40. package/dist/db/wait.js +0 -0
  41. package/dist/graphql/defaults.d.ts +17 -0
  42. package/dist/graphql/defaults.js +10 -0
  43. package/dist/graphql/errors.d.ts +59 -0
  44. package/dist/graphql/errors.js +82 -0
  45. package/dist/graphql/index.d.ts +5 -0
  46. package/dist/graphql/index.js +5 -0
  47. package/dist/graphql/logger.d.ts +13 -0
  48. package/dist/graphql/logger.js +38 -0
  49. package/dist/graphql/operation-limits.d.ts +25 -0
  50. package/dist/graphql/operation-limits.js +88 -0
  51. package/dist/graphql/validation.d.ts +28 -0
  52. package/dist/graphql/validation.js +19 -0
  53. package/dist/testing/index.d.ts +0 -0
  54. package/dist/testing/index.js +0 -0
  55. package/dist/testing/postgres-problems.d.ts +0 -0
  56. package/dist/testing/postgres-problems.js +0 -0
  57. package/dist/testing/schema-problems.d.ts +0 -0
  58. package/dist/testing/schema-problems.js +0 -0
  59. package/llms.txt +45 -1
  60. package/package.json +27 -3
@@ -0,0 +1,39 @@
1
+ import { oidcPairingPlugins } from '@cubicecho/better-auth-oidc-pairing';
2
+ import { bearer, magicLink } from 'better-auth/plugins';
3
+ import { AUTH_DEFAULTS, AUTH_PATHS } from './defaults.js';
4
+ const SECONDS_PER_MINUTE = 60;
5
+ /** better-auth's id for the magic-link plugin. */
6
+ const MAGIC_LINK_PLUGIN_ID = 'magic-link';
7
+ /**
8
+ * How people sign in: bearer sessions, OIDC with pairing, and emailed links. Never a password.
9
+ *
10
+ * @param options - The app's links and provider.
11
+ * @returns The plugins, to spread into `plugins`.
12
+ */
13
+ export function signInPlugins({ appUrl, deliver, oidc, paths, magicLinkTtlMinutes = AUTH_DEFAULTS.magicLinkTtlMinutes, }) {
14
+ const { login, verify, signedIn } = { ...AUTH_PATHS, ...paths };
15
+ const links = deliver === undefined
16
+ ? []
17
+ : [
18
+ magicLink({
19
+ expiresIn: magicLinkTtlMinutes * SECONDS_PER_MINUTE,
20
+ storeToken: 'hashed',
21
+ // Links go to the app, which spends the token over GraphQL. The REST verify route is not mounted.
22
+ sendMagicLink: ({ email, token }) => deliver({ email, token, url: `${appUrl}${verify}?token=${encodeURIComponent(token)}` }),
23
+ }),
24
+ ];
25
+ return [
26
+ bearer(),
27
+ ...oidcPairingPlugins({ ...oidc, signedInURL: `${appUrl}${signedIn}`, errorURL: `${appUrl}${login}` }),
28
+ ...links,
29
+ ];
30
+ }
31
+ /**
32
+ * Whether an instance emails sign-in links.
33
+ *
34
+ * @param auth - The auth instance.
35
+ * @returns true when it was built with a way to deliver them.
36
+ */
37
+ export function sendsMagicLinks(auth) {
38
+ return (auth.options.plugins ?? []).some((plugin) => plugin.id === MAGIC_LINK_PLUGIN_ID);
39
+ }
@@ -0,0 +1,53 @@
1
+ import { drizzleAdapter } from 'better-auth/adapters/drizzle';
2
+ import { type AuthPaths, type AuthSettings } from './defaults.ts';
3
+ /** The tables better-auth keeps, by its own model names. */
4
+ export interface AuthTables {
5
+ user: unknown;
6
+ session: unknown;
7
+ account: unknown;
8
+ verification: unknown;
9
+ /** Tables plugins add, such as `apikey` and `ssoProvider`. */
10
+ [model: string]: unknown;
11
+ }
12
+ /** What an app gives the preset. */
13
+ export interface AuthPresetOptions extends Partial<Pick<AuthSettings, 'sessionTtlDays'>> {
14
+ /** The Drizzle client. */
15
+ db: Parameters<typeof drizzleAdapter>[0];
16
+ /** The tables, passed explicitly: the rc Drizzle client is keyed by relations, so they cannot be discovered. */
17
+ tables: AuthTables;
18
+ /** What better-auth signs with. */
19
+ secret: string;
20
+ /** Where a browser reaches this server. */
21
+ serverUrl: string;
22
+ /** Where users reach the app. A sign-in may finish there. */
23
+ appUrl: string;
24
+ /**
25
+ * Pages that are somewhere else in this app.
26
+ *
27
+ * @defaultValue `AUTH_PATHS`
28
+ */
29
+ paths?: Partial<AuthPaths>;
30
+ }
31
+ /**
32
+ * The better-auth options every server shares. Spread it into `betterAuth`, then add plugins and hooks.
33
+ *
34
+ * @param options - What differs per app.
35
+ * @returns Sessions in Postgres, ids from the columns' own defaults, and the app's origin trusted.
36
+ */
37
+ export declare function authPreset({ db, tables, secret, serverUrl, appUrl, paths, sessionTtlDays, }: AuthPresetOptions): {
38
+ database: (options: import("@better-auth/core").BetterAuthOptions) => import("@better-auth/core/db/adapter").DBAdapter<import("@better-auth/core").BetterAuthOptions>;
39
+ secret: string;
40
+ baseURL: string;
41
+ trustedOrigins: string[];
42
+ advanced: {
43
+ database: {
44
+ generateId: 'uuid';
45
+ };
46
+ };
47
+ session: {
48
+ expiresIn: number;
49
+ };
50
+ onAPIError: {
51
+ errorURL: string;
52
+ };
53
+ };
@@ -0,0 +1,21 @@
1
+ import { drizzleAdapter } from 'better-auth/adapters/drizzle';
2
+ import { AUTH_DEFAULTS, AUTH_PATHS } from './defaults.js';
3
+ const SECONDS_PER_DAY = 86_400;
4
+ /**
5
+ * The better-auth options every server shares. Spread it into `betterAuth`, then add plugins and hooks.
6
+ *
7
+ * @param options - What differs per app.
8
+ * @returns Sessions in Postgres, ids from the columns' own defaults, and the app's origin trusted.
9
+ */
10
+ export function authPreset({ db, tables, secret, serverUrl, appUrl, paths, sessionTtlDays = AUTH_DEFAULTS.sessionTtlDays, }) {
11
+ return {
12
+ database: drizzleAdapter(db, { provider: 'pg', schema: tables }),
13
+ secret,
14
+ baseURL: serverUrl,
15
+ trustedOrigins: [new URL(appUrl).origin],
16
+ // On Postgres this leaves the id out of the insert, so the column's uuidv7() fills it.
17
+ advanced: { database: { generateId: 'uuid' } },
18
+ session: { expiresIn: sessionTtlDays * SECONDS_PER_DAY },
19
+ onAPIError: { errorURL: `${appUrl}${{ ...AUTH_PATHS, ...paths }.login}` },
20
+ };
21
+ }
@@ -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
+ }
File without changes
File without changes
package/dist/consts.d.ts CHANGED
File without changes
package/dist/consts.js CHANGED
File without changes
File without changes
File without changes
File without changes
package/dist/db/create.js CHANGED
File without changes
File without changes
File without changes
File without changes
package/dist/db/errors.js CHANGED
File without changes
File without changes
package/dist/db/index.js CHANGED
File without changes
File without changes
File without changes
package/dist/db/ssl.d.ts CHANGED
File without changes
package/dist/db/ssl.js CHANGED
File without changes
File without changes
File without changes
package/dist/db/wait.d.ts CHANGED
File without changes
package/dist/db/wait.js CHANGED
File without changes
@@ -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;