@lenne.tech/nest-server 12.6.12 → 12.6.14
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/.claude/rules/configurable-features.md +1 -1
- package/.claude/rules/package-management.md +7 -7
- package/.claude/rules/role-system.md +10 -0
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/decorators/rest-user.decorator.js +4 -0
- package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
- package/dist/core/common/filters/http-exception-log.filter.js +4 -0
- package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
- package/dist/core/common/helpers/context.helper.js +9 -0
- package/dist/core/common/helpers/context.helper.js.map +1 -1
- package/dist/core/common/helpers/decorator.helper.js +4 -0
- package/dist/core/common/helpers/decorator.helper.js.map +1 -1
- package/dist/core/common/helpers/execution-context-request.helper.d.ts +9 -1
- package/dist/core/common/helpers/execution-context-request.helper.js +29 -0
- package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +10 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +237 -0
- package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
- package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
- package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
- package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
- package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
- package/dist/core/common/plugins/complexity.plugin.js +73 -9
- package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
- package/dist/core/modules/auth/guards/auth.guard.js +10 -2
- package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/roles.guard.js +11 -1
- package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
- package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
- package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
- package/dist/core.module.js +2 -1
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/types/graphql-upload.d.ts +34 -2
- package/docs/REQUEST-LIFECYCLE.md +33 -9
- package/docs/security-overrides.md +3 -2
- package/migration-guides/12.6.12-to-12.6.13.md +162 -0
- package/migration-guides/12.6.13-to-12.6.14.md +143 -0
- package/package.json +10 -3
- package/src/core/common/decorators/rest-user.decorator.ts +6 -0
- package/src/core/common/filters/http-exception-log.filter.ts +9 -0
- package/src/core/common/helpers/context.helper.ts +14 -0
- package/src/core/common/helpers/decorator.helper.ts +5 -0
- package/src/core/common/helpers/execution-context-request.helper.ts +78 -1
- package/src/core/common/helpers/graphql-upload.helper.ts +520 -0
- package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
- package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
- package/src/core/common/plugins/complexity.plugin.ts +150 -9
- package/src/core/modules/auth/guards/auth.guard.ts +19 -2
- package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
- package/src/core/modules/auth/guards/roles.guard.ts +23 -1
- package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
- package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
- package/src/core.module.ts +5 -1
- package/src/index.ts +1 -0
- package/src/types/graphql-upload.d.ts +34 -2
|
@@ -1,11 +1,127 @@
|
|
|
1
1
|
import { Plugin } from '@nestjs/apollo';
|
|
2
2
|
import { GraphQLSchemaHost } from '@nestjs/graphql';
|
|
3
3
|
import type { ApolloServerPlugin, BaseContext, GraphQLRequestListener } from '@apollo/server';
|
|
4
|
-
import { GraphQLError } from 'graphql';
|
|
5
|
-
import {
|
|
4
|
+
import { getVariableValues, GraphQLError, Kind, TypeInfo, ValidationContext, visit, visitWithTypeInfo } from 'graphql';
|
|
5
|
+
import type {
|
|
6
|
+
ASTVisitor,
|
|
7
|
+
DefinitionNode,
|
|
8
|
+
DocumentNode,
|
|
9
|
+
FragmentDefinitionNode,
|
|
10
|
+
GraphQLSchema,
|
|
11
|
+
OperationDefinitionNode,
|
|
12
|
+
SelectionSetNode,
|
|
13
|
+
} from 'graphql';
|
|
14
|
+
import { createComplexityRule, fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity';
|
|
6
15
|
|
|
7
16
|
import { ConfigService } from '../services/config.service.js';
|
|
8
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Most variable coercion errors the pre-check collects before it stops. It only needs to know WHETHER the variables
|
|
20
|
+
* coerce, and one error answers that. Every error graphql creates for a variable computes its line and column by
|
|
21
|
+
* scanning the query up to the variable's definition: with execution's cap of 50 the pre-check cost 550 ms for a
|
|
22
|
+
* 959 KiB multipart request whose definitions stood after 490,000 line breaks (12.6.14).
|
|
23
|
+
*/
|
|
24
|
+
const VARIABLE_COERCION_MAX_ERRORS = 1;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Most visits × declared variables the complexity analysis may cost (12.6.14, SEC-4). graphql-query-complexity runs
|
|
28
|
+
* `Object.keys()` over the operation's variables at every field and every `@skip` / `@include` it visits — measured on
|
|
29
|
+
* Node 24 at 12–90 ns per variable and visit, so the limit is reached after at most about 23 ms. 38,000 declared
|
|
30
|
+
* variables and 4,900 visits blocked the event loop for 17 s before. With the default cost of 1 per field, a query
|
|
31
|
+
* `maxComplexity: 1000` accepts has at most 1,000 fields; with 30 variables that is at most 30,000.
|
|
32
|
+
*/
|
|
33
|
+
const COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK = 250_000;
|
|
34
|
+
|
|
35
|
+
/** The visitor graphql-query-complexity builds (the class itself is not exported). */
|
|
36
|
+
type ComplexityVisitor = ReturnType<ReturnType<typeof createComplexityRule>>;
|
|
37
|
+
|
|
38
|
+
/** Fields and `@skip` / `@include` directives in the selection sets — each one a visit with the variables walked. */
|
|
39
|
+
function variableVisits(definitions: readonly (FragmentDefinitionNode | OperationDefinitionNode)[]): number {
|
|
40
|
+
let visits = 0;
|
|
41
|
+
const pending: SelectionSetNode[] = definitions.map((definition) => definition.selectionSet);
|
|
42
|
+
while (pending.length) {
|
|
43
|
+
const selectionSet = pending.pop()!;
|
|
44
|
+
for (const selection of selectionSet.selections) {
|
|
45
|
+
for (const directive of selection.directives ?? []) {
|
|
46
|
+
if (directive.name.value === 'include' || directive.name.value === 'skip') {
|
|
47
|
+
visits++;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (selection.kind === Kind.FIELD) {
|
|
51
|
+
visits++;
|
|
52
|
+
}
|
|
53
|
+
if (selection.kind !== Kind.FRAGMENT_SPREAD && selection.selectionSet) {
|
|
54
|
+
pending.push(selection.selectionSet);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return visits;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The complexity graphql-query-complexity's `getComplexity()` computes, with each fragment evaluated once (12.6.14,
|
|
63
|
+
* SEC-4).
|
|
64
|
+
*
|
|
65
|
+
* The library evaluates a fragment again at EVERY spread, without caching, and at every visit coerces the field's
|
|
66
|
+
* literal arguments again. Its node cap (10,000 visits) bounds the visits, not their cost:
|
|
67
|
+
* `{...F ×3300} fragment F on Query { findUsers(filter: { … value: [0,0,…41,667 items] }) }` blocked the event loop
|
|
68
|
+
* for 2.2 s from a 100 KB JSON POST and for 22.5 s from a 990 KB multipart request — before any guard, with variables
|
|
69
|
+
* that coerce.
|
|
70
|
+
*
|
|
71
|
+
* A fragment's complexity depends on the fragment alone: its type is its type condition, and the variables and the
|
|
72
|
+
* estimators are the same for every spread. So the first spread evaluates it, every further spread reuses the result
|
|
73
|
+
* and adds the nodes the evaluation visited to the library's node count, so a query over 10,000 nodes is refused as
|
|
74
|
+
* before. The number this returns is the one `getComplexity()` returns; the work is that of the document, each
|
|
75
|
+
* fragment once. A field's `complexity` extension (read by `fieldExtensionsEstimator`) must therefore depend only on its
|
|
76
|
+
* arguments and `childComplexity` — as a function it runs once per fragment, not once per spread.
|
|
77
|
+
*
|
|
78
|
+
* The analysis stops at the first error it reports. The library catches the coercion error of every field's arguments
|
|
79
|
+
* and goes on, and `getComplexity()` throws the last one at the end — but every error with a node computes its line and
|
|
80
|
+
* column by scanning the query up to it. `query($x: String = "a") { a: getUser(id: $x) { id } b: … }` with
|
|
81
|
+
* `{"x": null}` is valid, passes the variable check and fails at every one of up to 9,999 fields: 1.4 s from a 98 KiB
|
|
82
|
+
* JSON POST, 86 s from a 993 KiB multipart request with the fields after 395,000 line breaks (12.6.14). The request is
|
|
83
|
+
* refused either way; now with the first error instead of the last.
|
|
84
|
+
*
|
|
85
|
+
* Built like `getComplexity()` (graphql-query-complexity 2.0.0, `QueryComplexity.js`), through the public
|
|
86
|
+
* `createComplexityRule()`; the cache wraps `nodeComplexity` of this one visitor, which the library calls through
|
|
87
|
+
* `this` for every fragment spread.
|
|
88
|
+
*/
|
|
89
|
+
function computeComplexity(schema: GraphQLSchema, query: DocumentNode, variables: Record<string, unknown>): number {
|
|
90
|
+
const typeInfo = new TypeInfo(schema);
|
|
91
|
+
const context = new ValidationContext(schema, query, typeInfo, (error) => {
|
|
92
|
+
throw error;
|
|
93
|
+
});
|
|
94
|
+
const visitor: ComplexityVisitor = createComplexityRule({
|
|
95
|
+
estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
|
|
96
|
+
// The maximum is checked by the plugin; the visitor only computes.
|
|
97
|
+
maximumComplexity: Infinity,
|
|
98
|
+
variables,
|
|
99
|
+
})(context);
|
|
100
|
+
|
|
101
|
+
const evaluate = visitor.nodeComplexity.bind(visitor);
|
|
102
|
+
const fragments = new Map<string, { complexity: number; nodes: number }>();
|
|
103
|
+
visitor.nodeComplexity = (node, typeDef, activeFragments) => {
|
|
104
|
+
if (node.kind !== Kind.FRAGMENT_DEFINITION) {
|
|
105
|
+
return evaluate(node, typeDef, activeFragments);
|
|
106
|
+
}
|
|
107
|
+
const known = fragments.get(node.name.value);
|
|
108
|
+
if (known) {
|
|
109
|
+
visitor.evaluatedNodes += known.nodes;
|
|
110
|
+
if (visitor.evaluatedNodes >= visitor.maxQueryNodes) {
|
|
111
|
+
throw new GraphQLError('Query exceeds the maximum allowed number of nodes.');
|
|
112
|
+
}
|
|
113
|
+
return known.complexity;
|
|
114
|
+
}
|
|
115
|
+
const before = visitor.evaluatedNodes;
|
|
116
|
+
const complexity = evaluate(node, typeDef, activeFragments);
|
|
117
|
+
fragments.set(node.name.value, { complexity, nodes: visitor.evaluatedNodes - before });
|
|
118
|
+
return complexity;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
visit(query, visitWithTypeInfo(typeInfo, visitor as unknown as ASTVisitor));
|
|
122
|
+
return visitor.complexity;
|
|
123
|
+
}
|
|
124
|
+
|
|
9
125
|
@Plugin()
|
|
10
126
|
export class ComplexityPlugin implements ApolloServerPlugin {
|
|
11
127
|
constructor(
|
|
@@ -18,14 +134,39 @@ export class ComplexityPlugin implements ApolloServerPlugin {
|
|
|
18
134
|
const { schema } = this.gqlSchemaHost;
|
|
19
135
|
|
|
20
136
|
return {
|
|
21
|
-
async didResolveOperation({ document, request }) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
137
|
+
async didResolveOperation({ document, operation, request }) {
|
|
138
|
+
// No operation resolved: several operations and no `operationName` naming one of them. Apollo still calls this
|
|
139
|
+
// hook, and graphql's `execute()` refuses the request afterwards, before it coerces a single variable.
|
|
140
|
+
// getComplexity() instead evaluated EVERY operation of such a document and coerced the variables for each
|
|
141
|
+
// (12.6.14, SEC-3): 860 operations sharing one 16,000-item variable blocked the event loop for 5.9 s from a
|
|
142
|
+
// 100 KB JSON POST, 1,720 operations for 25.5 s from 200 KB.
|
|
143
|
+
if (!operation) {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Invalid variables (12.6.14, SEC-2): getComplexity() coerces without an error cap, so a list of invalid items
|
|
148
|
+
// created one error per item — 1.5 s and 300 MB for 100 KB, 15 s and 2 GB for 1 MB. Execution refuses such
|
|
149
|
+
// variables itself, with graphql's cap of 50, before any resolver runs, so there is no complexity to compute.
|
|
150
|
+
const { errors } = getVariableValues(schema, operation.variableDefinitions ?? [], request.variables ?? {}, {
|
|
151
|
+
maxErrors: VARIABLE_COERCION_MAX_ERRORS,
|
|
28
152
|
});
|
|
153
|
+
if (errors?.length) {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// The resolved operation alone, with the fragments it may spread: the analysis evaluates exactly the operation
|
|
158
|
+
// execution runs, and coerces its variables once.
|
|
159
|
+
const fragments = document.definitions.filter(
|
|
160
|
+
(definition: DefinitionNode): definition is FragmentDefinitionNode =>
|
|
161
|
+
definition.kind === Kind.FRAGMENT_DEFINITION,
|
|
162
|
+
);
|
|
163
|
+
const variableCount = operation.variableDefinitions?.length ?? 0;
|
|
164
|
+
if (variableVisits([operation, ...fragments]) * variableCount > COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK) {
|
|
165
|
+
throw new GraphQLError('Query is too complex: too many fields for its number of variables');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const query: DocumentNode = { definitions: [operation, ...fragments], kind: Kind.DOCUMENT };
|
|
169
|
+
const complexity = computeComplexity(schema, query, request.variables ?? {});
|
|
29
170
|
if (maxComplexity !== undefined && complexity > maxComplexity) {
|
|
30
171
|
throw new GraphQLError(`Query is too complex: ${complexity}. Maximum allowed complexity: ${maxComplexity}`);
|
|
31
172
|
}
|
|
@@ -1,13 +1,18 @@
|
|
|
1
|
-
import { CanActivate, ExecutionContext, Logger, mixin, Optional } from '@nestjs/common';
|
|
1
|
+
import { CanActivate, ExecutionContext, Logger, mixin, Optional, UnauthorizedException } from '@nestjs/common';
|
|
2
2
|
import { ModuleRef } from '@nestjs/core';
|
|
3
3
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
4
4
|
import { AuthModuleOptions, Type } from '@nestjs/passport';
|
|
5
5
|
import passport from 'passport';
|
|
6
6
|
|
|
7
|
+
import {
|
|
8
|
+
isAgentCallContext,
|
|
9
|
+
resolveAgentCallRequest,
|
|
10
|
+
} from '../../../common/helpers/execution-context-request.helper.js';
|
|
7
11
|
import { enforceApiTokenRoute, getApiTokenContext } from '../../api-token/core-api-token.helpers.js';
|
|
8
12
|
import { BetterAuthTokenService } from '../../better-auth/better-auth-token.service.js';
|
|
9
13
|
import { BetterAuthenticatedUser } from '../../better-auth/better-auth.types.js';
|
|
10
14
|
import { CoreBetterAuthService } from '../../better-auth/core-better-auth.service.js';
|
|
15
|
+
import { ErrorCode } from '../../error-code/index.js';
|
|
11
16
|
import { AuthGuardStrategy } from '../auth-guard-strategy.enum.js';
|
|
12
17
|
import { ExpiredRefreshTokenException } from '../exceptions/expired-refresh-token.exception.js';
|
|
13
18
|
import { ExpiredTokenException } from '../exceptions/expired-token.exception.js';
|
|
@@ -165,6 +170,11 @@ function createAuthGuard(type?: AuthGuardStrategy | string | string[]): Type<IAu
|
|
|
165
170
|
|
|
166
171
|
const options = { ...defaultOptions, ...this.options };
|
|
167
172
|
const request = this.getRequest(context);
|
|
173
|
+
// An agent function / MCP call without a request is anonymous (nestjs-ai plan §1): this guard authenticates, so
|
|
174
|
+
// it refuses — Passport would otherwise be handed nothing, or the call's arguments.
|
|
175
|
+
if (!request && isAgentCallContext(context)) {
|
|
176
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
177
|
+
}
|
|
168
178
|
const existingUser = request?.[options.property || defaultOptions.property];
|
|
169
179
|
|
|
170
180
|
// An API token was already authenticated by CoreApiTokenMiddleware. Neither Passport nor
|
|
@@ -195,7 +205,9 @@ function createAuthGuard(type?: AuthGuardStrategy | string | string[]): Type<IAu
|
|
|
195
205
|
}
|
|
196
206
|
|
|
197
207
|
// Proceed with Passport authentication for other strategies
|
|
198
|
-
|
|
208
|
+
// On an agent / MCP call the second argument is the call, not a response: Passport gets the request's own
|
|
209
|
+
// response object (Express sets `req.res`).
|
|
210
|
+
const response = isAgentCallContext(context) ? request?.res : context?.switchToHttp()?.getResponse();
|
|
199
211
|
const passportFn = createPassportContext(request, response);
|
|
200
212
|
const user = await passportFn(
|
|
201
213
|
type || this.options?.defaultStrategy,
|
|
@@ -270,6 +282,11 @@ function createAuthGuard(type?: AuthGuardStrategy | string | string[]): Type<IAu
|
|
|
270
282
|
* Prepare request
|
|
271
283
|
*/
|
|
272
284
|
getRequest<T = any>(context: ExecutionContext): T {
|
|
285
|
+
// An agent function / MCP call: the request it runs in, never its arguments (nestjs-ai plan §1)
|
|
286
|
+
if (isAgentCallContext(context)) {
|
|
287
|
+
return (resolveAgentCallRequest(context) ?? null) as T;
|
|
288
|
+
}
|
|
289
|
+
|
|
273
290
|
// Try to get request GraphQL context
|
|
274
291
|
try {
|
|
275
292
|
const ctx = GqlExecutionContext.create(context)?.getContext();
|
|
@@ -2,6 +2,10 @@ import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable }
|
|
|
2
2
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
3
3
|
|
|
4
4
|
import { LegacyAuthRateLimiter } from '../services/legacy-auth-rate-limiter.service.js';
|
|
5
|
+
import {
|
|
6
|
+
isAgentCallContext,
|
|
7
|
+
resolveAgentCallRequest,
|
|
8
|
+
} from '../../../common/helpers/execution-context-request.helper.js';
|
|
5
9
|
|
|
6
10
|
/**
|
|
7
11
|
* Guard for rate limiting Legacy Auth endpoints
|
|
@@ -72,8 +76,11 @@ export class LegacyAuthRateLimitGuard implements CanActivate {
|
|
|
72
76
|
return { endpoint, ip };
|
|
73
77
|
}
|
|
74
78
|
|
|
75
|
-
// HTTP context
|
|
76
|
-
|
|
79
|
+
// HTTP context — or an agent function / MCP call, whose request is the one it runs in, never its arguments
|
|
80
|
+
// (nestjs-ai plan §1)
|
|
81
|
+
const request = isAgentCallContext(context)
|
|
82
|
+
? resolveAgentCallRequest(context)
|
|
83
|
+
: context.switchToHttp().getRequest();
|
|
77
84
|
const ip = this.getClientIp(request);
|
|
78
85
|
|
|
79
86
|
// The handler, never the URL: the URL carries the query string and the client's spelling of the path
|
|
@@ -10,7 +10,11 @@ import {
|
|
|
10
10
|
import { ModuleRef, Reflector } from '@nestjs/core';
|
|
11
11
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
12
12
|
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
isAgentCallContext,
|
|
15
|
+
resolveAgentCallRequest,
|
|
16
|
+
resolveGuardRequest,
|
|
17
|
+
} from '../../../common/helpers/execution-context-request.helper.js';
|
|
14
18
|
import { firstValueFrom, isObservable } from 'rxjs';
|
|
15
19
|
|
|
16
20
|
import { RoleEnum } from '../../../common/enums/role.enum.js';
|
|
@@ -147,6 +151,19 @@ export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
|
|
|
147
151
|
throw new ForbiddenException(ErrorCode.ACCESS_DENIED);
|
|
148
152
|
}
|
|
149
153
|
|
|
154
|
+
// An agent function / MCP tool call without a request (`@nestjs/ai`'s `caller: { user }`, a durable run, MCP over
|
|
155
|
+
// stdio) is ANONYMOUS: nothing authenticated `caller.user`, and the call's arguments are the model's. Open only
|
|
156
|
+
// where the route is public. Kept in sync with BetterAuthRolesGuard (nestjs-ai plan §1).
|
|
157
|
+
if (isAgentCallContext(context) && !this.getRequest(context)) {
|
|
158
|
+
// The method's own roles win over the class's, as CoreTenantGuard decides system roles: a class-level
|
|
159
|
+
// S_EVERYONE does not open a method that asks for S_USER
|
|
160
|
+
const effective = reflectorRoles?.[0]?.some((value) => !!value) ? reflectorRoles[0] : roles;
|
|
161
|
+
if (!effective || !effective.some((value) => !!value) || effective.includes(RoleEnum.S_EVERYONE)) {
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
165
|
+
}
|
|
166
|
+
|
|
150
167
|
// API tokens are decided BEFORE the public-route shortcut below: a token is denied on every route
|
|
151
168
|
// that does not declare @ApiTokenScopes(), public ones included (see core-api-token.helpers).
|
|
152
169
|
// A tenant token is fully decided there. A user token was authenticated by CoreApiTokenMiddleware,
|
|
@@ -289,6 +306,11 @@ export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
|
|
|
289
306
|
cookies?: Record<string, string>;
|
|
290
307
|
headers?: Record<string, string | string[] | undefined>;
|
|
291
308
|
} {
|
|
309
|
+
// An agent function / MCP call: the request it runs in, never its arguments (nestjs-ai plan §1)
|
|
310
|
+
if (isAgentCallContext(context)) {
|
|
311
|
+
return resolveAgentCallRequest(context) ?? null;
|
|
312
|
+
}
|
|
313
|
+
|
|
292
314
|
// Try GraphQL context first
|
|
293
315
|
try {
|
|
294
316
|
const gqlContext = GqlExecutionContext.create(context);
|
|
@@ -8,7 +8,11 @@ import {
|
|
|
8
8
|
} from '@nestjs/common';
|
|
9
9
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
10
10
|
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
agentCallOf,
|
|
13
|
+
isAgentCallContext,
|
|
14
|
+
resolveGuardRequest,
|
|
15
|
+
} from '../../common/helpers/execution-context-request.helper.js';
|
|
12
16
|
|
|
13
17
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
14
18
|
import { ApiTokenKind } from '../api-token/core-api-token.constants.js';
|
|
@@ -103,6 +107,20 @@ export class BetterAuthRolesGuard implements CanActivate {
|
|
|
103
107
|
// that does not declare @ApiTokenScopes(), public ones included. A tenant token is fully decided
|
|
104
108
|
// there; a user token continues through the ordinary checks as its user (see core-api-token.helpers).
|
|
105
109
|
const request = this.getRequest(context);
|
|
110
|
+
|
|
111
|
+
// An agent function / MCP tool call without a request (`@nestjs/ai`'s `caller: { user }`, a durable run, MCP over
|
|
112
|
+
// stdio) is ANONYMOUS: nothing authenticated `caller.user`, and the call's arguments are the model's. Open only
|
|
113
|
+
// where the route is public. Kept in sync with RolesGuard (nestjs-ai plan §1).
|
|
114
|
+
if (isAgentCallContext(context) && !request) {
|
|
115
|
+
// The method's own roles win over the class's, as CoreTenantGuard decides system roles: a class-level
|
|
116
|
+
// S_EVERYONE does not open a method that asks for S_USER. Kept in sync with RolesGuard.
|
|
117
|
+
const effective = handlerRoles?.some((value) => !!value) ? handlerRoles : roles;
|
|
118
|
+
if (!effective || !effective.some((value) => !!value) || effective.includes(RoleEnum.S_EVERYONE)) {
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
122
|
+
}
|
|
123
|
+
|
|
106
124
|
const apiTokenKind = enforceApiTokenRoute({
|
|
107
125
|
controllerClass: context.getClass(),
|
|
108
126
|
handler: context.getHandler(),
|
|
@@ -205,6 +223,16 @@ export class BetterAuthRolesGuard implements CanActivate {
|
|
|
205
223
|
* Get target ID from context for S_SELF checks
|
|
206
224
|
*/
|
|
207
225
|
private getTargetId(context: ExecutionContext): null | string {
|
|
226
|
+
// An agent function / MCP call: its arguments are the target, as a resolver's args are on GraphQL. Never the HTTP
|
|
227
|
+
// fallback below, which would read the same arguments as if they were a request with `params`.
|
|
228
|
+
if (isAgentCallContext(context)) {
|
|
229
|
+
if (!agentCallOf(context)) {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
const input = context.getArgByIndex(0);
|
|
233
|
+
return typeof input?.id === 'string' ? input.id : null;
|
|
234
|
+
}
|
|
235
|
+
|
|
208
236
|
// Try GraphQL args
|
|
209
237
|
try {
|
|
210
238
|
const gqlContext = GqlExecutionContext.create(context);
|
|
@@ -17,7 +17,7 @@ import { firstValueFrom, isObservable } from 'rxjs';
|
|
|
17
17
|
|
|
18
18
|
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
19
19
|
import { ROLE_GUARD } from '../auth/guards/role-guard.token.js';
|
|
20
|
-
import { resolveGuardRequest } from '../../common/helpers/execution-context-request.helper.js';
|
|
20
|
+
import { isAgentCallContext, resolveGuardRequest } from '../../common/helpers/execution-context-request.helper.js';
|
|
21
21
|
import {
|
|
22
22
|
revalidateAllWsConnections,
|
|
23
23
|
revalidateWsConnectionsForTenant,
|
|
@@ -431,6 +431,18 @@ export class CoreTenantGuard implements CanActivate, OnApplicationBootstrap, OnM
|
|
|
431
431
|
|
|
432
432
|
const request = this.getRequest(context);
|
|
433
433
|
if (!request) {
|
|
434
|
+
// An agent function / MCP call without a request is anonymous (nestjs-ai plan §1). "No request" is never
|
|
435
|
+
// permission there: only a public method runs, every other one is refused like an unauthenticated request.
|
|
436
|
+
if (isAgentCallContext(context)) {
|
|
437
|
+
const rolesMetadata = this.reflector.getAll<string[][]>('roles', [context.getHandler(), context.getClass()]);
|
|
438
|
+
const roles = mergeRolesMetadata(rolesMetadata);
|
|
439
|
+
// The method's own roles win over the class's (as `systemCheckRoles` below): a class-level S_EVERYONE does
|
|
440
|
+
// not open a method that asks for S_USER or a tenant role
|
|
441
|
+
const effective = rolesMetadata?.[0]?.some((role) => !!role) ? rolesMetadata[0] : roles;
|
|
442
|
+
if (effective?.some((role) => !!role) && !effective.includes(RoleEnum.S_EVERYONE)) {
|
|
443
|
+
throw new UnauthorizedException(ErrorCode.UNAUTHORIZED);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
434
446
|
return true;
|
|
435
447
|
}
|
|
436
448
|
|
package/src/core.module.ts
CHANGED
|
@@ -15,6 +15,7 @@ import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.mjs';
|
|
|
15
15
|
|
|
16
16
|
import { MongooseCastErrorFilter } from './core/common/filters/mongoose-cast-error.filter.js';
|
|
17
17
|
import { merge } from './core/common/helpers/config.helper.js';
|
|
18
|
+
import { processGraphQlUploadRequest } from './core/common/helpers/graphql-upload.helper.js';
|
|
18
19
|
import { refuseWsHandshake, registerWsConnection } from './core/common/helpers/graphql-ws-connection.helper.js';
|
|
19
20
|
import {
|
|
20
21
|
buildRequestContextAwareExecute,
|
|
@@ -122,7 +123,10 @@ export class CoreModule implements NestModule {
|
|
|
122
123
|
// config read here and the values there.
|
|
123
124
|
consumer.apply(SecurityHeadersMiddleware).forRoutes('*');
|
|
124
125
|
if (CoreModule.graphQlEnabled) {
|
|
125
|
-
|
|
126
|
+
// The framework's processRequest, never graphql-upload's default: the default (graphql-upload < 18.0.2) lets
|
|
127
|
+
// one anonymous multipart request crash the process (GHSA-5vm7-vc2x-p3w2) and leaks temporary files on
|
|
128
|
+
// duplicate file fields (GHSA-qwwm-252j-9whw). This middleware runs before any authentication.
|
|
129
|
+
consumer.apply(graphqlUploadExpress({ processRequest: processGraphQlUploadRequest })).forRoutes('graphql');
|
|
126
130
|
}
|
|
127
131
|
}
|
|
128
132
|
|
package/src/index.ts
CHANGED
|
@@ -44,6 +44,7 @@ export * from './core/common/helpers/execution-context-request.helper.js';
|
|
|
44
44
|
export * from './core/common/helpers/file.helper.js';
|
|
45
45
|
export * from './core/common/helpers/filter.helper.js';
|
|
46
46
|
export * from './core/common/helpers/graphql.helper.js';
|
|
47
|
+
export * from './core/common/helpers/graphql-upload.helper.js';
|
|
47
48
|
export * from './core/common/helpers/graphql-ws-connection.helper.js';
|
|
48
49
|
export * from './core/common/helpers/graphql-ws-context.helper.js';
|
|
49
50
|
export * from './core/common/helpers/idle-stream.helper.js';
|
|
@@ -4,21 +4,53 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Since graphql-upload 16 the package is ESM: its `exports` map lists only the `.mjs` deep paths, each
|
|
6
6
|
* with a default export, and it ships no declaration files (its types are JSDoc inside the `.mjs`
|
|
7
|
-
* sources, which TypeScript does not read from `node_modules`).
|
|
7
|
+
* sources, which TypeScript does not read from `node_modules`). The names below are the ones the
|
|
8
8
|
* framework imports.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
declare module 'graphql-upload/graphqlUploadExpress.mjs' {
|
|
12
12
|
import { RequestHandler } from 'express';
|
|
13
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
13
14
|
|
|
14
|
-
interface
|
|
15
|
+
interface GraphQLUploadProcessRequestOptions {
|
|
16
|
+
maxFieldSize?: number;
|
|
15
17
|
maxFiles?: number;
|
|
16
18
|
maxFileSize?: number;
|
|
17
19
|
}
|
|
18
20
|
|
|
21
|
+
interface GraphQLUploadOptions extends GraphQLUploadProcessRequestOptions {
|
|
22
|
+
/**
|
|
23
|
+
* The function that parses the multipart request. graphql-upload's default is its own `processRequest`, which is
|
|
24
|
+
* vulnerable to GHSA-5vm7-vc2x-p3w2 and GHSA-qwwm-252j-9whw below 18.0.2 — pass the framework's
|
|
25
|
+
* `processGraphQlUploadRequest`.
|
|
26
|
+
*/
|
|
27
|
+
processRequest?: (
|
|
28
|
+
request: IncomingMessage,
|
|
29
|
+
response: ServerResponse,
|
|
30
|
+
options?: GraphQLUploadProcessRequestOptions,
|
|
31
|
+
) => Promise<unknown>;
|
|
32
|
+
}
|
|
33
|
+
|
|
19
34
|
export default function graphqlUploadExpress(options?: GraphQLUploadOptions): RequestHandler;
|
|
20
35
|
}
|
|
21
36
|
|
|
37
|
+
declare module 'graphql-upload/Upload.mjs' {
|
|
38
|
+
/**
|
|
39
|
+
* A file expected in a GraphQL multipart request, placed in the operations wherever the `map` names it. The
|
|
40
|
+
* `GraphQLUpload` scalar accepts a value only if it is `instanceof` this class, of the same graphql-upload copy.
|
|
41
|
+
*/
|
|
42
|
+
export default class Upload {
|
|
43
|
+
/** The file's details once it streamed in (set by `resolve`). */
|
|
44
|
+
file?: unknown;
|
|
45
|
+
/** Resolves with the file's details; the scalar hands it to the resolver. */
|
|
46
|
+
promise: Promise<unknown>;
|
|
47
|
+
/** Rejects the upload (missing file, aborted request). */
|
|
48
|
+
reject: (error: Error) => void;
|
|
49
|
+
/** Resolves the upload with the file's details. */
|
|
50
|
+
resolve: (file: unknown) => void;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
22
54
|
declare module 'graphql-upload/GraphQLUpload.mjs' {
|
|
23
55
|
import { GraphQLScalarType } from 'graphql';
|
|
24
56
|
|