@lenne.tech/nest-server 12.9.3 → 12.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/rules/configurable-features.md +4 -0
- package/.claude/rules/package-management.md +35 -6
- package/.claude/rules/role-system.md +12 -0
- package/.claude/rules/testing.md +4 -4
- package/CLAUDE.md +10 -1
- package/FRAMEWORK-API.md +2 -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 +3 -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 +14 -1
- package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
- package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +8 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +206 -0
- package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
- 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/interfaces/server-options.interface.d.ts +11 -0
- package/dist/core/common/middleware/request-context.middleware.js +3 -0
- package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
- package/dist/core/common/services/request-context.service.d.ts +2 -0
- package/dist/core/common/services/request-context.service.js +3 -0
- package/dist/core/common/services/request-context.service.js.map +1 -1
- package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
- package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
- package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
- package/dist/core/modules/ai/core-ai.constants.js +1 -0
- package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
- package/dist/core/modules/ai/core-ai.module.js +2 -0
- package/dist/core/modules/ai/core-ai.module.js.map +1 -1
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
- package/dist/core/modules/ai/index.d.ts +8 -0
- package/dist/core/modules/ai/index.js +8 -0
- package/dist/core/modules/ai/index.js.map +1 -1
- package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
- package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
- package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
- package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
- package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
- package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
- package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
- package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
- package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
- package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
- package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
- package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai.service.js +2 -7
- package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
- package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
- package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
- package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
- package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
- package/dist/core/modules/ai/tools/ai-tool.registry.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/better-auth/better-auth.config.js +78 -0
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/file/core-file.controller.js +8 -0
- package/dist/core/modules/file/core-file.controller.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 +46 -9
- package/docs/security-overrides.md +44 -10
- package/migration-guides/12.9.3-to-12.9.4.md +137 -0
- package/migration-guides/12.9.x-to-12.10.x.md +271 -0
- package/package.json +62 -37
- package/src/core/common/decorators/rest-user.decorator.ts +6 -0
- package/src/core/common/filters/http-exception-log.filter.ts +8 -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 +97 -1
- package/src/core/common/helpers/graphql-upload.helper.ts +427 -0
- package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
- package/src/core/common/interfaces/server-options.interface.ts +98 -0
- package/src/core/common/middleware/request-context.middleware.ts +3 -0
- package/src/core/common/services/request-context.service.ts +11 -0
- package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
- package/src/core/modules/ai/README.md +101 -0
- package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
- package/src/core/modules/ai/core-ai.constants.ts +4 -0
- package/src/core/modules/ai/core-ai.module.ts +3 -0
- package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
- package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
- package/src/core/modules/ai/index.ts +8 -0
- package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
- package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
- package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
- package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
- package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
- package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
- package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
- package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
- package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
- package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
- package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
- package/src/core/modules/ai/services/core-ai.service.ts +5 -7
- package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
- package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
- package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
- 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/INTEGRATION-CHECKLIST.md +11 -0
- package/src/core/modules/better-auth/README.md +204 -0
- package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
- package/src/core/modules/better-auth/better-auth.config.ts +138 -1
- package/src/core/modules/file/README.md +1 -0
- package/src/core/modules/file/core-file.controller.ts +17 -0
- 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
|
@@ -2,6 +2,8 @@ import { ExecutionContext } from '@nestjs/common';
|
|
|
2
2
|
import { GqlExecutionContext } from '@nestjs/graphql';
|
|
3
3
|
import { Request as RequestType } from 'express';
|
|
4
4
|
|
|
5
|
+
import { isAgentCallContext, resolveAgentCallRequest } from './execution-context-request.helper.js';
|
|
6
|
+
|
|
5
7
|
/**
|
|
6
8
|
* Helper for context processing
|
|
7
9
|
* @deprecated use functions directly
|
|
@@ -33,6 +35,18 @@ export function getContextData(context: ExecutionContext): {
|
|
|
33
35
|
return { args: null, currentUser: null, request: null };
|
|
34
36
|
}
|
|
35
37
|
|
|
38
|
+
// An agent function / MCP call (nestjs-ai plan §1): the user is the one of the request the call runs in — never a
|
|
39
|
+
// `user` in the call's arguments, which the model or the MCP client wrote. A request-less call has no user, so the
|
|
40
|
+
// interceptors filter its result for an anonymous caller (the strictest view).
|
|
41
|
+
if (isAgentCallContext(context)) {
|
|
42
|
+
const agentRequest = resolveAgentCallRequest(context);
|
|
43
|
+
return {
|
|
44
|
+
args: context.getArgByIndex(0),
|
|
45
|
+
currentUser: agentRequest?.user,
|
|
46
|
+
request: (agentRequest ?? null) as RequestType,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
36
50
|
// Init data
|
|
37
51
|
let user: { [key: string]: any };
|
|
38
52
|
let rawContext: any = null;
|
|
@@ -3,12 +3,17 @@ import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql';
|
|
|
3
3
|
import type { PopulateOptions } from 'mongoose';
|
|
4
4
|
|
|
5
5
|
import { getPopulateOptions } from './db.helper.js';
|
|
6
|
+
import { isAgentCallContext, resolveAgentCallRequest } from './execution-context-request.helper.js';
|
|
6
7
|
import { removePropertiesDeep } from './input.helper.js';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Decorator function to get current user for Controller (http context) and Resolver (graphql context)
|
|
10
11
|
*/
|
|
11
12
|
export function currentUserDec(data, ctx: ExecutionContext) {
|
|
13
|
+
// An agent function / MCP call: the request's user, never one in the call's arguments (nestjs-ai plan §1)
|
|
14
|
+
if (isAgentCallContext(ctx)) {
|
|
15
|
+
return resolveAgentCallRequest(ctx)?.user;
|
|
16
|
+
}
|
|
12
17
|
if (ctx.getType<GqlContextType>() === 'graphql') {
|
|
13
18
|
const gqlContext = GqlExecutionContext.create(ctx);
|
|
14
19
|
return gqlContext.getContext().req.user;
|
|
@@ -28,7 +28,97 @@
|
|
|
28
28
|
* `src/core/common/**` and from `src/core/modules/**` alike without adding an import edge between
|
|
29
29
|
* them. See `.claude/rules/architecture.md` → "DI Token Placement (SWC-Safe)".
|
|
30
30
|
*/
|
|
31
|
-
import type { ExecutionContext } from '@nestjs/common';
|
|
31
|
+
import type { ArgumentsHost, ExecutionContext } from '@nestjs/common';
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The execution context types of an agent function call (`@nestjs/ai`, `'ai'`) and of an MCP primitive call
|
|
35
|
+
* (`@nestjs/mcp`, `'mcp'`). nestjs-ai plan §1.
|
|
36
|
+
*
|
|
37
|
+
* Both packages wrap a method with Nest's `ExternalContextCreator`, so EVERY global guard, interceptor and filter of
|
|
38
|
+
* the application runs around it — ours included, in any project that installs either package, whether or not it uses
|
|
39
|
+
* the framework's own AI module. Their arguments are `[input, call]`:
|
|
40
|
+
*
|
|
41
|
+
* | Index | `'ai'` (`AgentFunctionContext`) | `'mcp'` (`McpContext`) | Trust |
|
|
42
|
+
* |-------|---------------------------------|------------------------|-------|
|
|
43
|
+
* | 0 | the tool arguments the MODEL wrote | the tool arguments the MCP CLIENT sent | none — attacker-controlled |
|
|
44
|
+
* | 1 | built by `@nestjs/ai` from the call's `caller` (`request`, `user`, `scopes`) | built by `@nestjs/mcp` (`request`, `authInfo`) | server code |
|
|
45
|
+
*
|
|
46
|
+
* Before 12.10.0 every guard fell back to `switchToHttp().getRequest()` on such a context — which is index 0, the
|
|
47
|
+
* MODEL's arguments. A tool call `{ "user": { "roles": ["admin"] } }` was then the request a guard decided on. The
|
|
48
|
+
* resolvers below are duck-typed against that argument layout on purpose: `src/core/common/` imports neither package,
|
|
49
|
+
* so a project without them loads nothing new.
|
|
50
|
+
*/
|
|
51
|
+
export const AGENT_CALL_CONTEXT_TYPES: ReadonlySet<string> = new Set(['ai', 'mcp']);
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The second argument of an agent or MCP call, as far as the framework reads it. Everything else on it belongs to the
|
|
55
|
+
* package that built it.
|
|
56
|
+
*/
|
|
57
|
+
export interface AgentCallLike {
|
|
58
|
+
/** `'mcp'` only: the verified access token, when `@nestjs/mcp`'s `auth` option is configured. */
|
|
59
|
+
authInfo?: { [key: string]: unknown; extra?: Record<PropertyKey, unknown> };
|
|
60
|
+
/** The agent function's / tool's name. */
|
|
61
|
+
name?: string;
|
|
62
|
+
/** The HTTP platform's request the call runs in; `undefined` for a queue job, a durable run, stdio. */
|
|
63
|
+
request?: GuardRequestLike;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Symbol under which `CoreAiMcpOAuthService.createMcpTokenVerifier()` (AI module) records the user an MCP OAuth access token belongs to,
|
|
68
|
+
* in the `extra` of the `AuthInfo` it returns to `@nestjs/mcp`. A symbol rather than a string key, so a verifier of
|
|
69
|
+
* another identity provider cannot name it by accident and a JSON payload cannot carry it at all. `Symbol.for`, so a
|
|
70
|
+
* second copy of the framework in one process (npm and vendored) agrees on it.
|
|
71
|
+
*/
|
|
72
|
+
export const MCP_VERIFIED_USER = Symbol.for('lt.nest-server.mcp-verified-user');
|
|
73
|
+
|
|
74
|
+
/** Whether `context` is an agent function call (`'ai'`) or an MCP primitive call (`'mcp'`). */
|
|
75
|
+
export function isAgentCallContext(context: ArgumentsHost | undefined): boolean {
|
|
76
|
+
let type: unknown;
|
|
77
|
+
try {
|
|
78
|
+
type = context?.getType?.();
|
|
79
|
+
} catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
return typeof type === 'string' && AGENT_CALL_CONTEXT_TYPES.has(type);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The call object (`args[1]`) of an agent or MCP call; `undefined` for any other context. */
|
|
86
|
+
export function agentCallOf(context: ArgumentsHost | undefined): AgentCallLike | undefined {
|
|
87
|
+
if (!isAgentCallContext(context)) {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
const call = context.getArgByIndex(1);
|
|
91
|
+
return call && typeof call === 'object' ? (call as AgentCallLike) : undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The request an agent or MCP call runs in — never its arguments.
|
|
96
|
+
*
|
|
97
|
+
* `undefined` for a REQUEST-LESS caller: `@nestjs/ai`'s `caller: { user, scopes }` (a queue job, a durable run) or MCP
|
|
98
|
+
* over stdio. The framework treats such a caller as ANONYMOUS (nestjs-ai plan §1, owner decision recorded there): its
|
|
99
|
+
* `caller.user` is data the calling code put there — a job payload read back from Redis, a workflow's stored input —
|
|
100
|
+
* that nothing authenticated, and the tenant scope of the data layer (`RequestContext`) has no request to come from.
|
|
101
|
+
* So a role-gated agent function or tool refuses it with 401; one open to `S_EVERYONE` runs. A project that runs a
|
|
102
|
+
* role-gated agent function from a job authenticates first and passes the request (`caller: { request }`).
|
|
103
|
+
*
|
|
104
|
+
* MCP: when the request carries no user but `@nestjs/mcp`'s `authInfo` was produced by the framework's own MCP OAuth
|
|
105
|
+
* verifier (`CoreAiMcpOAuthService.createMcpTokenVerifier()`), the user that verifier loaded becomes `request.user` — the same step
|
|
106
|
+
* `CoreAiMcpController.scopeLateResolvedUser()` takes for `/ai/mcp`, so the data layer sees the caller too.
|
|
107
|
+
*/
|
|
108
|
+
export function resolveAgentCallRequest(context: ArgumentsHost | undefined): GuardRequestLike | undefined {
|
|
109
|
+
const call = agentCallOf(context);
|
|
110
|
+
const request = call?.request;
|
|
111
|
+
if (!request || typeof request !== 'object') {
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
if (!request.user) {
|
|
115
|
+
const verified = call.authInfo?.extra?.[MCP_VERIFIED_USER];
|
|
116
|
+
if (verified && typeof verified === 'object') {
|
|
117
|
+
request.user = verified;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return request;
|
|
121
|
+
}
|
|
32
122
|
|
|
33
123
|
/**
|
|
34
124
|
* The shape a guard reads and writes. It is deliberately loose: on HTTP this IS the Express request,
|
|
@@ -61,6 +151,8 @@ function isSubscriptionContext(value: any): boolean {
|
|
|
61
151
|
* Resolve the object a guard should decide on.
|
|
62
152
|
*
|
|
63
153
|
* Order matters:
|
|
154
|
+
* 0. An agent function or MCP call (`'ai'` / `'mcp'`): the request the call runs in, or `undefined` — never the
|
|
155
|
+
* call's arguments, which the HTTP fallback below would return (see {@link resolveAgentCallRequest}).
|
|
64
156
|
* 1. `ctx.getContext().req` — HTTP GraphQL, and the shape every existing consumer expects.
|
|
65
157
|
* 2. The graphql-ws subscription context itself, when it looks like one (see above).
|
|
66
158
|
* 3. `switchToHttp().getRequest()` — REST controllers. On a GraphQL context this returns the
|
|
@@ -73,6 +165,10 @@ export function resolveGuardRequest(
|
|
|
73
165
|
context: ExecutionContext,
|
|
74
166
|
gqlContextOf: (context: ExecutionContext) => any,
|
|
75
167
|
): GuardRequestLike | undefined {
|
|
168
|
+
if (isAgentCallContext(context)) {
|
|
169
|
+
return resolveAgentCallRequest(context);
|
|
170
|
+
}
|
|
171
|
+
|
|
76
172
|
let gqlContext: any;
|
|
77
173
|
try {
|
|
78
174
|
gqlContext = gqlContextOf(context);
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GraphQL multipart request processing for `graphqlUploadExpress()`: graphql-upload's `processRequest` with the
|
|
3
|
+
* fixes for GHSA-5vm7-vc2x-p3w2 (high) and GHSA-qwwm-252j-9whw (medium) applied.
|
|
4
|
+
*
|
|
5
|
+
* Source: package `graphql-upload` 17.1.0, file `processRequest.mjs`
|
|
6
|
+
* (https://github.com/jaydenseric/graphql-upload), ported to TypeScript. Upstream fixed both advisories in
|
|
7
|
+
* graphql-upload 18.0.2, which requires graphql 17 — this framework runs graphql 16 (Apollo Server 5,
|
|
8
|
+
* @nestjs/graphql 14), so the fix is carried here instead. Both hunks of the upstream fix are applied unchanged:
|
|
9
|
+
*
|
|
10
|
+
* 1. GHSA-5vm7-vc2x-p3w2: a `map` path with a `__proto__` key, or one that goes through an already placed
|
|
11
|
+
* `Upload`, is refused with the existing 400 "Invalid object path". Without it one anonymous request crashed the
|
|
12
|
+
* process: `{"1":["variables.file"],"2":["variables.file.reject"]}` without file fields replaces the first
|
|
13
|
+
* upload's `reject`, and the parser's `finish` handler throws `TypeError: upload.reject is not a function` outside
|
|
14
|
+
* any request — an uncaught exception, which `installProcessDiagnostics()` (and Node itself) answers with exit 1.
|
|
15
|
+
* `variables.file.__proto__` gave a client-supplied object an `Upload` prototype, so it passed the scalar's
|
|
16
|
+
* `instanceof Upload` check.
|
|
17
|
+
* 2. GHSA-qwwm-252j-9whw: a second file field with the name of an already resolved upload is ignored. Before, each
|
|
18
|
+
* duplicate created a new temporary file whose reference replaced the previous one, so only the last was released
|
|
19
|
+
* when the response closed — temporary files and file descriptors leaked per request (with `maxFiles` > 1; the
|
|
20
|
+
* default is unlimited).
|
|
21
|
+
*
|
|
22
|
+
* `CoreModule` passes this function to `graphqlUploadExpress({ processRequest })`. A project that registers
|
|
23
|
+
* `graphqlUploadExpress()` itself must pass it too — graphql-upload's own default is the unpatched function.
|
|
24
|
+
*
|
|
25
|
+
* `Upload` comes from graphql-upload's own `Upload.mjs`, the class the `GraphQLUpload` scalar checks with
|
|
26
|
+
* `instanceof`: an `Upload` of any other class would be refused as an invalid upload. `ignoreStream` is not exported
|
|
27
|
+
* by graphql-upload and is re-implemented below.
|
|
28
|
+
*
|
|
29
|
+
* ---------------------------------------------------------------------------------------------------------------
|
|
30
|
+
* MIT License
|
|
31
|
+
*
|
|
32
|
+
* Copyright Jayden Seric
|
|
33
|
+
*
|
|
34
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
|
35
|
+
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
|
|
36
|
+
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
|
|
37
|
+
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
38
|
+
*
|
|
39
|
+
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
|
|
40
|
+
* the Software.
|
|
41
|
+
*
|
|
42
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
|
|
43
|
+
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
44
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
45
|
+
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
46
|
+
* SOFTWARE.
|
|
47
|
+
* ---------------------------------------------------------------------------------------------------------------
|
|
48
|
+
*/
|
|
49
|
+
import busboy from 'busboy';
|
|
50
|
+
import { WriteStream } from 'fs-capacitor';
|
|
51
|
+
import Upload from 'graphql-upload/Upload.mjs';
|
|
52
|
+
import createError from 'http-errors';
|
|
53
|
+
import objectPath from 'object-path';
|
|
54
|
+
|
|
55
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
56
|
+
import type { Readable } from 'node:stream';
|
|
57
|
+
|
|
58
|
+
/** graphql-upload's `GRAPHQL_MULTIPART_REQUEST_SPEC_URL`, used in the error messages exactly as upstream does. */
|
|
59
|
+
const GRAPHQL_MULTIPART_REQUEST_SPEC_URL = 'https://github.com/jaydenseric/graphql-multipart-request-spec';
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Options of {@link processGraphQlUploadRequest} — the same as graphql-upload's `ProcessRequestOptions`, so
|
|
63
|
+
* `graphqlUploadExpress({ processRequest, ...options })` forwards them unchanged.
|
|
64
|
+
*/
|
|
65
|
+
export interface GraphQlUploadProcessRequestOptions {
|
|
66
|
+
/** Maximum size of a non-file multipart field (`operations`, `map`) in bytes. Defaults to `1000000` (1 MB). */
|
|
67
|
+
maxFieldSize?: number;
|
|
68
|
+
/** Maximum size of one file in bytes. Defaults to `Infinity`. */
|
|
69
|
+
maxFileSize?: number;
|
|
70
|
+
/** Maximum number of files. Defaults to `Infinity`. */
|
|
71
|
+
maxFiles?: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The GraphQL operation (or batch of operations) a multipart request resolves to, with `Upload` instances placed. */
|
|
75
|
+
export type GraphQlUploadOperations = Array<Record<string, unknown>> | Record<string, unknown>;
|
|
76
|
+
|
|
77
|
+
/** File details an `Upload` resolves with (graphql-upload's `FileUpload`). */
|
|
78
|
+
interface ProcessedFileUpload {
|
|
79
|
+
capacitor: WriteStream;
|
|
80
|
+
createReadStream: (options?: { encoding?: BufferEncoding; highWaterMark?: number }) => Readable;
|
|
81
|
+
encoding: string;
|
|
82
|
+
filename: string;
|
|
83
|
+
mimetype: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** An error created with `http-errors` (or any other error the parser reports). */
|
|
87
|
+
type ProcessRequestError = Error & { expose?: boolean; status?: number };
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Safely ignores a readable stream (graphql-upload's `ignoreStream`, which the package does not export): an error
|
|
91
|
+
* on it must not crash the process, and its data is drained so the parser can go on.
|
|
92
|
+
*/
|
|
93
|
+
function ignoreStream(stream: Readable): void {
|
|
94
|
+
// Prevent an unhandled error from crashing the process.
|
|
95
|
+
stream.on('error', () => {});
|
|
96
|
+
|
|
97
|
+
// Waste the stream.
|
|
98
|
+
stream.resume();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Processes an incoming GraphQL multipart request
|
|
103
|
+
* (https://github.com/jaydenseric/graphql-multipart-request-spec): parses the `operations` and `map` fields, places
|
|
104
|
+
* an `Upload` wherever the `map` names one and resolves each with its file once that file streams in.
|
|
105
|
+
*
|
|
106
|
+
* graphql-upload 17.1.0's `processRequest` with the fixes of graphql-upload 18.0.2 (see the file header). Pass it to
|
|
107
|
+
* `graphqlUploadExpress({ processRequest: processGraphQlUploadRequest })`; `CoreModule` does so for `/graphql`.
|
|
108
|
+
*
|
|
109
|
+
* @returns The operation(s), with an `Upload` at every mapped path — resolved once the `map` is parsed. Rejects with
|
|
110
|
+
* an `http-errors` error (400 for a malformed request, 413 above a limit, 499 on a disconnect).
|
|
111
|
+
*/
|
|
112
|
+
export function processGraphQlUploadRequest(
|
|
113
|
+
request: IncomingMessage,
|
|
114
|
+
response: ServerResponse,
|
|
115
|
+
{ maxFieldSize = 1000000, maxFileSize = Infinity, maxFiles = Infinity }: GraphQlUploadProcessRequestOptions = {},
|
|
116
|
+
): Promise<GraphQlUploadOperations> {
|
|
117
|
+
return new Promise((resolve, reject) => {
|
|
118
|
+
let released: boolean;
|
|
119
|
+
let exitError: ProcessRequestError;
|
|
120
|
+
let operations: GraphQlUploadOperations;
|
|
121
|
+
let operationsPath: ReturnType<typeof objectPath>;
|
|
122
|
+
let map: Map<string, Upload>;
|
|
123
|
+
|
|
124
|
+
const parser = busboy({
|
|
125
|
+
headers: request.headers,
|
|
126
|
+
defParamCharset: 'utf8',
|
|
127
|
+
limits: {
|
|
128
|
+
fieldSize: maxFieldSize,
|
|
129
|
+
fields: 2, // Only operations and map.
|
|
130
|
+
fileSize: maxFileSize,
|
|
131
|
+
files: maxFiles,
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Exits request processing with an error. Successive calls have no effect.
|
|
137
|
+
*/
|
|
138
|
+
function exit(error: ProcessRequestError, isParserError = false): void {
|
|
139
|
+
if (exitError) {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
exitError = error;
|
|
144
|
+
|
|
145
|
+
if (map) {
|
|
146
|
+
for (const upload of map.values()) {
|
|
147
|
+
if (!upload.file) {
|
|
148
|
+
upload.reject(exitError);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// If the error came from the parser, don't cause it to be emitted again.
|
|
154
|
+
if (isParserError) {
|
|
155
|
+
parser.destroy();
|
|
156
|
+
} else {
|
|
157
|
+
parser.destroy(exitError);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
request.unpipe(parser);
|
|
161
|
+
|
|
162
|
+
// With a sufficiently large request body, subsequent events in the same event frame cause the stream to pause
|
|
163
|
+
// after the parser is destroyed. To ensure that the request resumes, the call to .resume() is scheduled for
|
|
164
|
+
// later in the event loop.
|
|
165
|
+
setImmediate(() => {
|
|
166
|
+
request.resume();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
reject(exitError);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
parser.on('field', (fieldName: string, value: string, { valueTruncated }: { valueTruncated: boolean }) => {
|
|
173
|
+
if (valueTruncated) {
|
|
174
|
+
return exit(
|
|
175
|
+
createError(413, `The ‘${fieldName}’ multipart field value exceeds the ${maxFieldSize} byte size limit.`),
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
switch (fieldName) {
|
|
180
|
+
case 'operations':
|
|
181
|
+
try {
|
|
182
|
+
operations = JSON.parse(value);
|
|
183
|
+
} catch {
|
|
184
|
+
return exit(
|
|
185
|
+
createError(
|
|
186
|
+
400,
|
|
187
|
+
`Invalid JSON in the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
|
|
188
|
+
),
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// `operations` should be an object or an array. Note that arrays and `null` have an `object` type.
|
|
193
|
+
if (typeof operations !== 'object' || !operations) {
|
|
194
|
+
return exit(
|
|
195
|
+
createError(
|
|
196
|
+
400,
|
|
197
|
+
`Invalid type for the ‘operations’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
|
|
198
|
+
),
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
operationsPath = objectPath(operations);
|
|
203
|
+
|
|
204
|
+
break;
|
|
205
|
+
case 'map': {
|
|
206
|
+
if (!operations) {
|
|
207
|
+
return exit(
|
|
208
|
+
createError(
|
|
209
|
+
400,
|
|
210
|
+
`Misordered multipart fields; ‘map’ should follow ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
|
|
211
|
+
),
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
let parsedMap: unknown;
|
|
216
|
+
try {
|
|
217
|
+
parsedMap = JSON.parse(value);
|
|
218
|
+
} catch {
|
|
219
|
+
return exit(
|
|
220
|
+
createError(400, `Invalid JSON in the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`),
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// `map` should be an object.
|
|
225
|
+
if (typeof parsedMap !== 'object' || !parsedMap || Array.isArray(parsedMap)) {
|
|
226
|
+
return exit(
|
|
227
|
+
createError(400, `Invalid type for the ‘map’ multipart field (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`),
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const mapEntries = Object.entries(parsedMap);
|
|
232
|
+
|
|
233
|
+
// Check max files is not exceeded, even though the number of files to parse might not match the map
|
|
234
|
+
// provided by the client.
|
|
235
|
+
if (mapEntries.length > maxFiles) {
|
|
236
|
+
return exit(createError(413, `${maxFiles} max file uploads exceeded.`));
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
map = new Map();
|
|
240
|
+
for (const [mapFieldName, paths] of mapEntries) {
|
|
241
|
+
if (!Array.isArray(paths)) {
|
|
242
|
+
return exit(
|
|
243
|
+
createError(
|
|
244
|
+
400,
|
|
245
|
+
`Invalid type for the ‘map’ multipart field entry key ‘${mapFieldName}’ array (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
|
|
246
|
+
),
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
map.set(mapFieldName, new Upload());
|
|
251
|
+
|
|
252
|
+
for (const [index, path] of paths.entries()) {
|
|
253
|
+
if (typeof path !== 'string') {
|
|
254
|
+
return exit(
|
|
255
|
+
createError(
|
|
256
|
+
400,
|
|
257
|
+
`Invalid type for the ‘map’ multipart field entry key ‘${mapFieldName}’ array index ‘${index}’ value (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
|
|
258
|
+
),
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
try {
|
|
263
|
+
// GHSA-5vm7-vc2x-p3w2 (graphql-upload 18.0.2): check the upload's mapped path in the operations is
|
|
264
|
+
// safe before setting it.
|
|
265
|
+
const keys = path.split('.');
|
|
266
|
+
|
|
267
|
+
let pathValue: unknown = operations;
|
|
268
|
+
|
|
269
|
+
for (const [keyIndex, key] of keys.entries()) {
|
|
270
|
+
// Forbid `__proto__` keys to prevent prototype manipulation that could make client-supplied
|
|
271
|
+
// objects pass `instanceof Upload` checks.
|
|
272
|
+
if (key === '__proto__') {
|
|
273
|
+
throw new TypeError('Object path has a `__proto__` key.');
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Forbid setting an upload within an already set upload, but allow a total replacement. Resolved
|
|
277
|
+
// with object-path's own `get`, so it sees what `set` will reach, inherited array elements included.
|
|
278
|
+
if (keyIndex < keys.length - 1) {
|
|
279
|
+
pathValue = objectPath.get(pathValue as object, [key]);
|
|
280
|
+
|
|
281
|
+
if (pathValue instanceof Upload) {
|
|
282
|
+
throw new TypeError('Object path traverses an upload.');
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
operationsPath.set(path, map.get(mapFieldName));
|
|
288
|
+
} catch {
|
|
289
|
+
return exit(
|
|
290
|
+
createError(
|
|
291
|
+
400,
|
|
292
|
+
`Invalid object path for the ‘map’ multipart field entry key ‘${mapFieldName}’ array index ‘${index}’ value ‘${path}’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
|
|
293
|
+
),
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
resolve(operations);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
parser.on(
|
|
305
|
+
'file',
|
|
306
|
+
(
|
|
307
|
+
fieldName: string,
|
|
308
|
+
stream: Readable,
|
|
309
|
+
{ encoding, filename, mimeType: mimetype }: { encoding: string; filename: string; mimeType: string },
|
|
310
|
+
) => {
|
|
311
|
+
if (!map) {
|
|
312
|
+
ignoreStream(stream);
|
|
313
|
+
return exit(
|
|
314
|
+
createError(
|
|
315
|
+
400,
|
|
316
|
+
`Misordered multipart fields; files should follow ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`,
|
|
317
|
+
),
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const upload = map.get(fieldName);
|
|
322
|
+
|
|
323
|
+
// GHSA-qwwm-252j-9whw (graphql-upload 18.0.2): `|| upload.file` — a duplicate file field would create a new
|
|
324
|
+
// capacitor and replace the reference to the first one, which then never gets released.
|
|
325
|
+
if (!upload || upload.file) {
|
|
326
|
+
// The file is extraneous or a duplicate. As the rest can still be processed, just ignore it and don't
|
|
327
|
+
// exit with an error.
|
|
328
|
+
ignoreStream(stream);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
let fileError: ProcessRequestError;
|
|
333
|
+
|
|
334
|
+
const capacitor = new WriteStream();
|
|
335
|
+
|
|
336
|
+
capacitor.on('error', () => {
|
|
337
|
+
stream.unpipe();
|
|
338
|
+
stream.resume();
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
stream.on('limit', () => {
|
|
342
|
+
fileError = createError(413, `File truncated as it exceeds the ${maxFileSize} byte size limit.`);
|
|
343
|
+
stream.unpipe();
|
|
344
|
+
capacitor.destroy(fileError);
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
stream.on('error', (error: Error) => {
|
|
348
|
+
fileError = error;
|
|
349
|
+
stream.unpipe();
|
|
350
|
+
capacitor.destroy(fileError);
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
const file: ProcessedFileUpload = {
|
|
354
|
+
filename,
|
|
355
|
+
mimetype,
|
|
356
|
+
encoding,
|
|
357
|
+
createReadStream(options) {
|
|
358
|
+
const error = fileError || (released ? exitError : null);
|
|
359
|
+
if (error) {
|
|
360
|
+
throw error;
|
|
361
|
+
}
|
|
362
|
+
return capacitor.createReadStream(options);
|
|
363
|
+
},
|
|
364
|
+
capacitor,
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
Object.defineProperty(file, 'capacitor', {
|
|
368
|
+
enumerable: false,
|
|
369
|
+
configurable: false,
|
|
370
|
+
writable: false,
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
stream.pipe(capacitor);
|
|
374
|
+
upload.resolve(file);
|
|
375
|
+
},
|
|
376
|
+
);
|
|
377
|
+
|
|
378
|
+
parser.once('filesLimit', () => exit(createError(413, `${maxFiles} max file uploads exceeded.`)));
|
|
379
|
+
|
|
380
|
+
parser.once('finish', () => {
|
|
381
|
+
request.unpipe(parser);
|
|
382
|
+
request.resume();
|
|
383
|
+
|
|
384
|
+
if (!operations) {
|
|
385
|
+
return exit(createError(400, `Missing multipart field ‘operations’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`));
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (!map) {
|
|
389
|
+
return exit(createError(400, `Missing multipart field ‘map’ (${GRAPHQL_MULTIPART_REQUEST_SPEC_URL}).`));
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
for (const upload of map.values()) {
|
|
393
|
+
if (!upload.file) {
|
|
394
|
+
upload.reject(createError(400, 'File missing in the request.'));
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
// Use the `on` method instead of `once` as in edge cases the same parser could have multiple `error` events and
|
|
400
|
+
// all must be handled to prevent the Node.js process exiting with an error. One edge case is if there is a
|
|
401
|
+
// malformed part header as well as an unexpected end of the form.
|
|
402
|
+
parser.on('error', (error: Error) => {
|
|
403
|
+
exit(error, true);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
response.once('close', () => {
|
|
407
|
+
released = true;
|
|
408
|
+
|
|
409
|
+
if (map) {
|
|
410
|
+
for (const upload of map.values()) {
|
|
411
|
+
if (upload.file) {
|
|
412
|
+
// Release resources and clean up temporary files.
|
|
413
|
+
(upload.file as ProcessedFileUpload).capacitor.release();
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
request.once('close', () => {
|
|
420
|
+
if (!request.readableEnded) {
|
|
421
|
+
exit(createError(499, 'Request disconnected during file upload stream parsing.'));
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
|
|
425
|
+
request.pipe(parser);
|
|
426
|
+
});
|
|
427
|
+
}
|
|
@@ -4,6 +4,7 @@ import { Observable } from 'rxjs';
|
|
|
4
4
|
import { map } from 'rxjs/operators';
|
|
5
5
|
|
|
6
6
|
import { applyTranslationsRecursively } from '../helpers/service.helper.js';
|
|
7
|
+
import { isAgentCallContext } from '../helpers/execution-context-request.helper.js';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Interceptor that automatically applies translations from _translations
|
|
@@ -82,6 +83,13 @@ export class TranslateResponseInterceptor implements NestInterceptor {
|
|
|
82
83
|
}
|
|
83
84
|
|
|
84
85
|
private getLanguage(context: ExecutionContext): string | null {
|
|
86
|
+
// An agent function / MCP call (nestjs-ai plan §1): this interceptor shapes HTTP and GraphQL responses for a
|
|
87
|
+
// reader's language; a model reads the result as it is. Without this the HTTP fallback below read
|
|
88
|
+
// `accept-language` from the call's ARGUMENTS.
|
|
89
|
+
if (isAgentCallContext(context)) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
|
|
85
93
|
// GraphQL context
|
|
86
94
|
try {
|
|
87
95
|
if (context.getType<GqlContextType>() === 'graphql') {
|