@lushly-dev/afd-server 2.3.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +277 -31
- package/dist/app-call-registry.d.ts +31 -0
- package/dist/app-call-registry.d.ts.map +1 -0
- package/dist/app-call-registry.js +56 -0
- package/dist/app-call-registry.js.map +1 -0
- package/dist/approval-admission.d.ts +93 -0
- package/dist/approval-admission.d.ts.map +1 -0
- package/dist/approval-admission.js +165 -0
- package/dist/approval-admission.js.map +1 -0
- package/dist/approval-crypto.d.ts +22 -16
- package/dist/approval-crypto.d.ts.map +1 -1
- package/dist/approval-crypto.js +41 -66
- package/dist/approval-crypto.js.map +1 -1
- package/dist/approval-process-state.d.ts +20 -0
- package/dist/approval-process-state.d.ts.map +1 -0
- package/dist/approval-process-state.js +28 -0
- package/dist/approval-process-state.js.map +1 -0
- package/dist/approval-relay.d.ts +171 -8
- package/dist/approval-relay.d.ts.map +1 -1
- package/dist/approval-relay.js +42 -3
- package/dist/approval-relay.js.map +1 -1
- package/dist/approval-up-front.d.ts +40 -0
- package/dist/approval-up-front.d.ts.map +1 -0
- package/dist/approval-up-front.js +365 -0
- package/dist/approval-up-front.js.map +1 -0
- package/dist/approval.d.ts +17 -12
- package/dist/approval.d.ts.map +1 -1
- package/dist/approval.js +178 -41
- package/dist/approval.js.map +1 -1
- package/dist/approver.d.ts +84 -0
- package/dist/approver.d.ts.map +1 -0
- package/dist/approver.js +107 -0
- package/dist/approver.js.map +1 -0
- package/dist/bootstrap/afd-docs.d.ts.map +1 -1
- package/dist/bootstrap/afd-docs.js +4 -0
- package/dist/bootstrap/afd-docs.js.map +1 -1
- package/dist/bootstrap/afd-help.d.ts +2 -1
- package/dist/bootstrap/afd-help.d.ts.map +1 -1
- package/dist/bootstrap/afd-help.js +17 -4
- package/dist/bootstrap/afd-help.js.map +1 -1
- package/dist/bootstrap/described-command.d.ts +2 -1
- package/dist/bootstrap/described-command.d.ts.map +1 -1
- package/dist/bootstrap/described-command.js.map +1 -1
- package/dist/command-timeout.d.ts +17 -0
- package/dist/command-timeout.d.ts.map +1 -0
- package/dist/command-timeout.js +92 -0
- package/dist/command-timeout.js.map +1 -0
- package/dist/context-fields.d.ts.map +1 -1
- package/dist/context-fields.js +9 -9
- package/dist/context-fields.js.map +1 -1
- package/dist/credentials.d.ts +17 -0
- package/dist/credentials.d.ts.map +1 -0
- package/dist/credentials.js +16 -0
- package/dist/credentials.js.map +1 -0
- package/dist/define-core.d.ts +27 -1
- package/dist/define-core.d.ts.map +1 -1
- package/dist/define-core.js +8 -1
- package/dist/define-core.js.map +1 -1
- package/dist/define.d.ts +3 -2
- package/dist/define.d.ts.map +1 -1
- package/dist/define.js +1 -1
- package/dist/define.js.map +1 -1
- package/dist/direct-registry.d.ts +27 -3
- package/dist/direct-registry.d.ts.map +1 -1
- package/dist/direct-registry.js +41 -6
- package/dist/direct-registry.js.map +1 -1
- package/dist/direct-tool-surface.d.ts +1 -1
- package/dist/direct-tool-surface.d.ts.map +1 -1
- package/dist/direct-tool-surface.js +14 -4
- package/dist/direct-tool-surface.js.map +1 -1
- package/dist/direct.d.ts +3 -1
- package/dist/direct.d.ts.map +1 -1
- package/dist/direct.js +2 -1
- package/dist/direct.js.map +1 -1
- package/dist/elicitation-state.d.ts +5 -1
- package/dist/elicitation-state.d.ts.map +1 -1
- package/dist/elicitation-state.js +4 -1
- package/dist/elicitation-state.js.map +1 -1
- package/dist/execution.d.ts +17 -0
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +78 -7
- package/dist/execution.js.map +1 -1
- package/dist/http-handler.d.ts +26 -2
- package/dist/http-handler.d.ts.map +1 -1
- package/dist/http-handler.js +154 -19
- package/dist/http-handler.js.map +1 -1
- package/dist/http-security.d.ts +14 -1
- package/dist/http-security.d.ts.map +1 -1
- package/dist/http-security.js +79 -17
- package/dist/http-security.js.map +1 -1
- package/dist/http-sessions.d.ts +45 -7
- package/dist/http-sessions.d.ts.map +1 -1
- package/dist/http-sessions.js +44 -12
- package/dist/http-sessions.js.map +1 -1
- package/dist/index.d.ts +18 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +18 -3
- package/dist/index.js.map +1 -1
- package/dist/instance-state.d.ts +46 -0
- package/dist/instance-state.d.ts.map +1 -0
- package/dist/instance-state.js +91 -0
- package/dist/instance-state.js.map +1 -0
- package/dist/journal-replay.d.ts.map +1 -1
- package/dist/journal-replay.js +41 -3
- package/dist/journal-replay.js.map +1 -1
- package/dist/journal.d.ts +10 -1
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +95 -10
- package/dist/journal.js.map +1 -1
- package/dist/json-rpc.d.ts +3 -2
- package/dist/json-rpc.d.ts.map +1 -1
- package/dist/json-rpc.js +5 -3
- package/dist/json-rpc.js.map +1 -1
- package/dist/lazy-tools.d.ts +16 -1
- package/dist/lazy-tools.d.ts.map +1 -1
- package/dist/lazy-tools.js +13 -2
- package/dist/lazy-tools.js.map +1 -1
- package/dist/mcp-auth-bearer.d.ts +25 -0
- package/dist/mcp-auth-bearer.d.ts.map +1 -0
- package/dist/mcp-auth-bearer.js +50 -0
- package/dist/mcp-auth-bearer.js.map +1 -0
- package/dist/mcp-auth-dispatch.d.ts +38 -0
- package/dist/mcp-auth-dispatch.d.ts.map +1 -0
- package/dist/mcp-auth-dispatch.js +113 -0
- package/dist/mcp-auth-dispatch.js.map +1 -0
- package/dist/mcp-auth-jwt.d.ts +179 -0
- package/dist/mcp-auth-jwt.d.ts.map +1 -0
- package/dist/mcp-auth-jwt.js +365 -0
- package/dist/mcp-auth-jwt.js.map +1 -0
- package/dist/mcp-auth-resource.d.ts +78 -0
- package/dist/mcp-auth-resource.d.ts.map +1 -0
- package/dist/mcp-auth-resource.js +197 -0
- package/dist/mcp-auth-resource.js.map +1 -0
- package/dist/mcp-auth-rules.d.ts +135 -0
- package/dist/mcp-auth-rules.d.ts.map +1 -0
- package/dist/mcp-auth-rules.js +306 -0
- package/dist/mcp-auth-rules.js.map +1 -0
- package/dist/mcp-auth-scopes.d.ts +84 -0
- package/dist/mcp-auth-scopes.d.ts.map +1 -0
- package/dist/mcp-auth-scopes.js +125 -0
- package/dist/mcp-auth-scopes.js.map +1 -0
- package/dist/mcp-auth-view.d.ts +50 -0
- package/dist/mcp-auth-view.d.ts.map +1 -0
- package/dist/mcp-auth-view.js +166 -0
- package/dist/mcp-auth-view.js.map +1 -0
- package/dist/mcp-auth.d.ts +157 -0
- package/dist/mcp-auth.d.ts.map +1 -0
- package/dist/mcp-auth.js +442 -0
- package/dist/mcp-auth.js.map +1 -0
- package/dist/mcp-modern.d.ts +15 -1
- package/dist/mcp-modern.d.ts.map +1 -1
- package/dist/mcp-modern.js +218 -31
- package/dist/mcp-modern.js.map +1 -1
- package/dist/meta-argument.d.ts +8 -8
- package/dist/meta-argument.d.ts.map +1 -1
- package/dist/meta-argument.js +17 -10
- package/dist/meta-argument.js.map +1 -1
- package/dist/meta-tools.js +1 -1
- package/dist/meta-tools.js.map +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +16 -6
- package/dist/middleware.js.map +1 -1
- package/dist/output-budget.d.ts +77 -0
- package/dist/output-budget.d.ts.map +1 -0
- package/dist/output-budget.js +200 -0
- package/dist/output-budget.js.map +1 -0
- package/dist/request-context.d.ts +7 -1
- package/dist/request-context.d.ts.map +1 -1
- package/dist/request-context.js +14 -3
- package/dist/request-context.js.map +1 -1
- package/dist/resources.d.ts +35 -10
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +59 -18
- package/dist/resources.js.map +1 -1
- package/dist/scope-view.d.ts +59 -0
- package/dist/scope-view.d.ts.map +1 -0
- package/dist/scope-view.js +44 -0
- package/dist/scope-view.js.map +1 -0
- package/dist/server-types.d.ts +191 -26
- package/dist/server-types.d.ts.map +1 -1
- package/dist/server-types.js.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +165 -18
- package/dist/server.js.map +1 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/skills.js +99 -3
- package/dist/skills.js.map +1 -1
- package/dist/strict-json.d.ts +17 -0
- package/dist/strict-json.d.ts.map +1 -0
- package/dist/strict-json.js +93 -0
- package/dist/strict-json.js.map +1 -0
- package/dist/task-dispatch.d.ts +34 -0
- package/dist/task-dispatch.d.ts.map +1 -0
- package/dist/task-dispatch.js +26 -0
- package/dist/task-dispatch.js.map +1 -0
- package/dist/tasks-runtime.d.ts +113 -0
- package/dist/tasks-runtime.d.ts.map +1 -0
- package/dist/tasks-runtime.js +687 -0
- package/dist/tasks-runtime.js.map +1 -0
- package/dist/tasks.d.ts +210 -0
- package/dist/tasks.d.ts.map +1 -0
- package/dist/tasks.js +289 -0
- package/dist/tasks.js.map +1 -0
- package/dist/tool-router.d.ts +4 -0
- package/dist/tool-router.d.ts.map +1 -1
- package/dist/tool-router.js +103 -26
- package/dist/tool-router.js.map +1 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +11 -18
- package/dist/tools.js.map +1 -1
- package/dist/up-front-steps.d.ts +27 -0
- package/dist/up-front-steps.d.ts.map +1 -0
- package/dist/up-front-steps.js +110 -0
- package/dist/up-front-steps.js.map +1 -0
- package/dist/validation.d.ts +24 -3
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +56 -6
- package/dist/validation.js.map +1 -1
- package/dist/verified-credentials.d.ts +42 -0
- package/dist/verified-credentials.d.ts.map +1 -0
- package/dist/verified-credentials.js +84 -0
- package/dist/verified-credentials.js.map +1 -0
- package/package.json +12 -7
package/dist/execution.js
CHANGED
|
@@ -9,10 +9,12 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { executeBatch as executeCoreBatch, executePipeline as executeCorePipeline, executeStream as executeCoreStream, executionFailure, failure, isActorKind, truncateName, withContextDefaults, } from '@lushly-dev/afd-core';
|
|
11
11
|
import { commandNotAllowed } from '@lushly-dev/afd-core/internal/direct-allow';
|
|
12
|
+
import { beginAdmission, needsAdmission, takeAdmission } from './approval-admission.js';
|
|
12
13
|
import { filterAllowed, isCommandAllowed } from './command-allow.js';
|
|
13
14
|
import { filterByContext, isAccessibleInContext, notFoundSuggestion, notInContextError, } from './command-routing.js';
|
|
14
15
|
import { applyContextFields } from './context-fields.js';
|
|
15
16
|
import { resolveContextState } from './context-scope.js';
|
|
17
|
+
import { applyOutputBudget, checkOutputBudgetResult, EFFECTIVE_OUTPUT_BUDGET, SKIP_OUTPUT_BUDGET, } from './output-budget.js';
|
|
16
18
|
import { formatEnhancedValidationError, validateInputEnhanced } from './validation.js';
|
|
17
19
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
18
20
|
// EXECUTION ENGINE FACTORY
|
|
@@ -52,14 +54,26 @@ export function createExecutionEngine(deps) {
|
|
|
52
54
|
return failure(commandNotAllowed(commandName));
|
|
53
55
|
}
|
|
54
56
|
// One context object flows through every middleware into the handler.
|
|
57
|
+
// Read the non-enumerable stream marker from callerContext before spreading defaults,
|
|
58
|
+
// so it never leaks into middleware or handlers.
|
|
59
|
+
const skipOutputBudget = Boolean(callerContext[SKIP_OUTPUT_BUDGET]);
|
|
55
60
|
const context = withContextDefaults(callerContext, deps.contextDefaults);
|
|
56
|
-
|
|
61
|
+
// A command hidden from the caller (MCP authorization, M6) is looked up as a name that
|
|
62
|
+
// does not exist, before validation, middleware or the handler.
|
|
63
|
+
const command = deps.hidden?.(commandName, callerContext)
|
|
64
|
+
? undefined
|
|
65
|
+
: commandMap.get(commandName);
|
|
57
66
|
const activeContext = resolveContextState(context, deps.contextState)?.getActive();
|
|
67
|
+
// The command's own approval policy, for the approval middleware to decide from. This
|
|
68
|
+
// call's context is a fresh object, so no other call's admission applies to it.
|
|
69
|
+
if (command)
|
|
70
|
+
beginAdmission(context, command);
|
|
58
71
|
if (!command) {
|
|
59
72
|
// A few close matches, never the whole list: in lazy mode that would load
|
|
60
73
|
// every command name into the agent's context on a single typo. Never one the call's
|
|
61
|
-
// `allow` option refuses.
|
|
62
|
-
const
|
|
74
|
+
// `allow` option refuses, nor one the caller is not shown.
|
|
75
|
+
const listed = [...commandMap.values()];
|
|
76
|
+
const candidates = filterAllowed(filterByContext(deps.shown?.(listed, callerContext) ?? listed, activeContext), callerContext);
|
|
63
77
|
return failure({
|
|
64
78
|
code: 'COMMAND_NOT_FOUND',
|
|
65
79
|
message: `Command '${truncateName(commandName)}' not found`,
|
|
@@ -74,7 +88,11 @@ export function createExecutionEngine(deps) {
|
|
|
74
88
|
// becomes a VALIDATION_ERROR result instead of rejecting.
|
|
75
89
|
let validation;
|
|
76
90
|
try {
|
|
77
|
-
|
|
91
|
+
// The MCP server validates a step of an afd-batch or afd-pipe approved up front itself,
|
|
92
|
+
// to run it on the input the human was shown (#1414).
|
|
93
|
+
validation =
|
|
94
|
+
(await deps.validated?.(commandName, input, context)) ??
|
|
95
|
+
validateInputEnhanced(command.inputSchema, input, deps.maxValidationIssues);
|
|
78
96
|
}
|
|
79
97
|
catch (error) {
|
|
80
98
|
const err = toError(error);
|
|
@@ -95,24 +113,69 @@ export function createExecutionEngine(deps) {
|
|
|
95
113
|
expectedFields: validation.expectedFields,
|
|
96
114
|
unexpectedFields: validation.unexpectedFields,
|
|
97
115
|
missingFields: validation.missingFields,
|
|
116
|
+
truncated: validation.truncated,
|
|
117
|
+
limit: validation.limit,
|
|
98
118
|
}),
|
|
99
119
|
details: {
|
|
100
120
|
errors: validation.errors,
|
|
101
121
|
expectedFields: validation.expectedFields,
|
|
102
122
|
unexpectedFields: validation.unexpectedFields,
|
|
103
123
|
missingFields: validation.missingFields,
|
|
124
|
+
...(validation.truncated
|
|
125
|
+
? {
|
|
126
|
+
truncated: true,
|
|
127
|
+
limit: validation.limit,
|
|
128
|
+
totalErrors: validation.totalErrors,
|
|
129
|
+
}
|
|
130
|
+
: {}),
|
|
104
131
|
},
|
|
105
132
|
});
|
|
106
133
|
}
|
|
107
134
|
const invalidField = applyContextFields(deps.contextFields ?? [], context, commandName);
|
|
108
135
|
if (invalidField)
|
|
109
136
|
return invalidField;
|
|
137
|
+
const invalidBudget = applyOutputBudget(command, context);
|
|
138
|
+
if (invalidBudget)
|
|
139
|
+
return invalidBudget;
|
|
140
|
+
const effectiveBudget = context.outputBudget;
|
|
141
|
+
if (effectiveBudget !== undefined) {
|
|
142
|
+
Object.defineProperty(context, EFFECTIVE_OUTPUT_BUDGET, { value: effectiveBudget });
|
|
143
|
+
}
|
|
110
144
|
const data = validation.data;
|
|
111
145
|
// Build middleware chain
|
|
112
146
|
const runHandler = async () => {
|
|
147
|
+
// A declared approval policy holds without the approval middleware: a command whose
|
|
148
|
+
// policy is not 'not-required' runs only when an approval step admitted this call. A
|
|
149
|
+
// policy function is not evaluated here; declaring one needs an approval step. The same
|
|
150
|
+
// holds for a policy given only in the middleware's `commands` list, once the middleware
|
|
151
|
+
// recorded that it gates this call.
|
|
152
|
+
// The admission must name this command and this validated input, and is taken here, so a
|
|
153
|
+
// second dispatch on the same context (a retry inside the chain) needs a second admission.
|
|
154
|
+
const admission = needsAdmission(context)
|
|
155
|
+
? takeAdmission(context, commandName, data)
|
|
156
|
+
: 'admitted';
|
|
157
|
+
if (admission !== 'admitted') {
|
|
158
|
+
// 'mismatch': an approval step ran, but this dispatch is not the one it admitted (a
|
|
159
|
+
// retry placed after it, or the input changed after it), so the operator fixes the order.
|
|
160
|
+
return failure({
|
|
161
|
+
code: 'APPROVAL_UNAVAILABLE',
|
|
162
|
+
message: `${commandName} needs a person's approval, and this server cannot ask for it`,
|
|
163
|
+
suggestion: admission === 'missing'
|
|
164
|
+
? `Tell the user that ${commandName} needs their approval and this server has no approval step; do not retry. The operator adds the approval middleware (createApprovalMiddleware) or removes the command's approval policy.`
|
|
165
|
+
: `Do not retry: this call is not the one approved. The operator moves middleware that retries or changes input before the approval middleware.`,
|
|
166
|
+
retryable: false,
|
|
167
|
+
details: { reason: admission === 'missing' ? 'no-approval-step' : 'admission-mismatch' },
|
|
168
|
+
});
|
|
169
|
+
}
|
|
113
170
|
const { clock } = context;
|
|
114
171
|
const startTime = clock.now();
|
|
115
|
-
const
|
|
172
|
+
const rawResult = await command.handler(data, context);
|
|
173
|
+
// Post-handler output budget check (spec/output-budgets.md, B5 & B6): runs before
|
|
174
|
+
// metadata stamping and before middleware or the journal see the result; skipped on
|
|
175
|
+
// buffered executeStream (B7).
|
|
176
|
+
const result = effectiveBudget !== undefined && !skipOutputBudget
|
|
177
|
+
? checkOutputBudgetResult(command, effectiveBudget, rawResult)
|
|
178
|
+
: rawResult;
|
|
116
179
|
// Build a new result rather than mutating the handler's (possibly frozen) object.
|
|
117
180
|
// Read the actor after the handler: middleware (auth) may have refined it.
|
|
118
181
|
return {
|
|
@@ -157,7 +220,11 @@ export function createExecutionEngine(deps) {
|
|
|
157
220
|
* error handling as a single call.
|
|
158
221
|
*/
|
|
159
222
|
function executeBatch(request, context = {}) {
|
|
160
|
-
return executeCoreBatch(request, executeCommand, context, {
|
|
223
|
+
return executeCoreBatch(request, executeCommand, context, {
|
|
224
|
+
devMode,
|
|
225
|
+
maxBatchSize: deps.maxBatchSize,
|
|
226
|
+
maxBatchParallelism: deps.maxBatchParallelism,
|
|
227
|
+
});
|
|
161
228
|
}
|
|
162
229
|
/**
|
|
163
230
|
* Execute a pipeline of chained commands with variable resolution.
|
|
@@ -185,7 +252,11 @@ export function createExecutionEngine(deps) {
|
|
|
185
252
|
* chunk.
|
|
186
253
|
*/
|
|
187
254
|
function executeStream(commandName, input, context = {}) {
|
|
188
|
-
|
|
255
|
+
// B7: a streamed command's chunks are not checked by B5 in this version.
|
|
256
|
+
// Non-enumerable symbol keeps `context` structurally equal to the caller's object.
|
|
257
|
+
const streamContext = { ...context };
|
|
258
|
+
Object.defineProperty(streamContext, SKIP_OUTPUT_BUDGET, { value: true });
|
|
259
|
+
return executeCoreStream(commandName, input, executeCommand, streamContext, { devMode });
|
|
189
260
|
}
|
|
190
261
|
return { executeCommand, executeBatch, executePipeline, executeStream };
|
|
191
262
|
}
|
package/dist/execution.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.js","sourceRoot":"","sources":["../src/execution.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAaH,OAAO,EACN,YAAY,IAAI,gBAAgB,EAChC,eAAe,IAAI,mBAAmB,EACtC,aAAa,IAAI,iBAAiB,EAClC,gBAAgB,EAChB,OAAO,EACP,WAAW,EACX,YAAY,EACZ,mBAAmB,GACnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAC/E,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EACN,eAAe,EACf,qBAAqB,EACrB,kBAAkB,EAClB,iBAAiB,GACjB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,kBAAkB,EAAqB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAqB,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"execution.js","sourceRoot":"","sources":["../src/execution.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAaH,OAAO,EACN,YAAY,IAAI,gBAAgB,EAChC,eAAe,IAAI,mBAAmB,EACtC,aAAa,IAAI,iBAAiB,EAClC,gBAAgB,EAChB,OAAO,EACP,WAAW,EACX,YAAY,EACZ,mBAAmB,GACnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxF,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EACN,eAAe,EACf,qBAAqB,EACrB,kBAAkB,EAClB,iBAAiB,GACjB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,kBAAkB,EAAqB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAqB,mBAAm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HANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
-
import type { BatchRequest, BatchResult, CommandContext, CommandResult, StreamChunk } from '@lushly-dev/afd-core';
|
|
2
|
+
import type { Actor, BatchRequest, BatchResult, CommandContext, CommandResult, StreamChunk } from '@lushly-dev/afd-core';
|
|
3
|
+
import { type ApproverPredicate } from './approver.js';
|
|
3
4
|
import type { ConfirmationGate } from './confirmations.js';
|
|
4
5
|
import { type ContextField } from './context-fields.js';
|
|
5
6
|
import { type HttpSecurityOptions } from './http-security.js';
|
|
6
7
|
import type { SessionStore } from './http-sessions.js';
|
|
8
|
+
import type { AuthLayer } from './mcp-auth.js';
|
|
7
9
|
import type { ModernHttpLane } from './mcp-modern.js';
|
|
8
10
|
import type { CreateRequestContext } from './server-types.js';
|
|
11
|
+
import type { TaskRuntime } from './tasks-runtime.js';
|
|
9
12
|
import { type ToolCallResult } from './tool-router.js';
|
|
10
13
|
export interface HttpHandlerDeps extends HttpSecurityOptions {
|
|
11
14
|
name: string;
|
|
12
15
|
version: string;
|
|
13
16
|
port: number;
|
|
17
|
+
/** Detailed error messages. It changes no Origin check and no CORS header. */
|
|
18
|
+
devMode: boolean;
|
|
14
19
|
cors: boolean;
|
|
15
20
|
getToolsList: (context: CommandContext) => unknown[];
|
|
16
21
|
routeToolCall: (toolName: string, args: unknown, context: CommandContext) => Promise<ToolCallResult>;
|
|
@@ -35,9 +40,28 @@ export interface HttpHandlerDeps extends HttpSecurityOptions {
|
|
|
35
40
|
modern?: ModernHttpLane;
|
|
36
41
|
/** Confirmation enforcement for `/rpc`, `/batch` and `/stream` (acknowledged by `Afd-Confirm`). */
|
|
37
42
|
confirmations?: ConfirmationGate;
|
|
43
|
+
/**
|
|
44
|
+
* MCP authorization (`spec/authorization.md`): every route but the metadata needs a verified
|
|
45
|
+
* token, and every command context carries the request's credentials.
|
|
46
|
+
*/
|
|
47
|
+
auth?: AuthLayer;
|
|
48
|
+
/**
|
|
49
|
+
* Which callers are approvers (`spec/command-metadata.md`, "Approval evidence from an approver
|
|
50
|
+
* client"). The 2025-era `/message` lane never carries an approver's token back: an approver's
|
|
51
|
+
* `_meta["dev.afd/approval"]` there is refused, and its held results carry the token.
|
|
52
|
+
*/
|
|
53
|
+
approver?: ApproverPredicate;
|
|
54
|
+
/** The actor of a call whose context has none (the server's `actor` option). */
|
|
55
|
+
actor?: Actor;
|
|
56
|
+
/** MCP Tasks runtime for refusing `task: 'required'` on the 2025 `/message` lane. */
|
|
57
|
+
tasks?: TaskRuntime;
|
|
58
|
+
/** Maximum commands accepted in a single batch (default: 500). */
|
|
59
|
+
maxBatchSize?: number;
|
|
60
|
+
/** Maximum parallelism accepted in a single batch (default: 16). */
|
|
61
|
+
maxBatchParallelism?: number;
|
|
38
62
|
}
|
|
39
63
|
export declare function createHttpHandler(deps: HttpHandlerDeps): {
|
|
40
|
-
handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
64
|
+
handler: (req: IncomingMessage, res: ServerResponse, body?: Uint8Array | string) => Promise<void>;
|
|
41
65
|
sseClients: Map<string, import("./http-sse.js").SseClient>;
|
|
42
66
|
dispose: () => void;
|
|
43
67
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http-handler.d.ts","sourceRoot":"","sources":["../src/http-handler.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,KAAK,EACX,YAAY,EACZ,WAAW,EACX,cAAc,
|
|
1
|
+
{"version":3,"file":"http-handler.d.ts","sourceRoot":"","sources":["../src/http-handler.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,KAAK,EACX,KAAK,EACL,YAAY,EACZ,WAAW,EACX,cAAc,EAEd,aAAa,EACb,WAAW,EACX,MAAM,sBAAsB,CAA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SE, and REST endpoints. */
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { once } from 'node:events';
|
|
4
|
-
import { createErrorChunk, createFailedBatchResult, failedBatchRequest, failure, isBatchRequest, truncateName, } from '@lushly-dev/afd-core';
|
|
4
|
+
import { checkBatchLimits, createErrorChunk, createFailedBatchResult, failedBatchRequest, failure, isBatchRequest, truncateName, } from '@lushly-dev/afd-core';
|
|
5
|
+
import { approvalKeyInInput, bindApprover, decideApprover, } from './approver.js';
|
|
5
6
|
import { createHttpConfirmationCheck } from './confirmation-gate.js';
|
|
6
7
|
import { contextFieldValues } from './context-fields.js';
|
|
7
8
|
import { bindContextState } from './context-scope.js';
|
|
8
|
-
import { HttpRequestError, readJsonBody, validateHttpRequest, } from './http-security.js';
|
|
9
|
+
import { assertAllowedOrigins, HttpRequestError, readJsonBody, setPrereadBody, validateHttpRequest, } from './http-security.js';
|
|
9
10
|
import { createSseHub } from './http-sse.js';
|
|
10
11
|
import { JsonRpcError, JsonRpcErrorCode, jsonRpcError, jsonRpcResult, methodNotFound, parseJsonRpcMessage, } from './json-rpc.js';
|
|
11
12
|
import { liftMetaArgument, metaArgumentKeys } from './meta-argument.js';
|
|
13
|
+
import { withMetaOutputBudget } from './output-budget.js';
|
|
14
|
+
import { credentialsBinding } from './principal-binding.js';
|
|
12
15
|
import { requestContextValues } from './request-context.js';
|
|
16
|
+
import { bindScopeView } from './scope-view.js';
|
|
17
|
+
import { bindTaskDispatch } from './task-dispatch.js';
|
|
13
18
|
import { resultContent } from './tool-router.js';
|
|
19
|
+
/** Seconds a refused `initialize` is told to wait (`Retry-After`) when the session store is full. */
|
|
20
|
+
const SESSION_RETRY_AFTER_S = 60;
|
|
14
21
|
/** Routes whose errors are JSON-RPC error objects rather than AFD failures. */
|
|
15
22
|
const JSON_RPC_PATHS = new Set(['/message', '/rpc', '/mcp']);
|
|
16
23
|
function json(res, status, body) {
|
|
@@ -24,9 +31,10 @@ function afdFailure(code, message, suggestion) {
|
|
|
24
31
|
return { success: false, error: { code, message, suggestion } };
|
|
25
32
|
}
|
|
26
33
|
export function createHttpHandler(deps) {
|
|
27
|
-
const { name, version, cors, devMode, getToolsList, routeToolCall, executeCommand, executeBatch, executeStream, isMutation, sessions, createContext, contextFields, onError, modern, confirmations, } = deps;
|
|
34
|
+
const { name, version, cors, devMode, getToolsList, routeToolCall, executeCommand, executeBatch, executeStream, isMutation, sessions, createContext, contextFields, onError, modern, confirmations, auth, } = deps;
|
|
28
35
|
const unconfirmed = createHttpConfirmationCheck(confirmations);
|
|
29
36
|
const metaKeys = metaArgumentKeys(contextFields);
|
|
37
|
+
assertAllowedOrigins(deps.allowedOrigins);
|
|
30
38
|
const maxBodyBytes = deps.maxBodyBytes ?? 1024 * 1024;
|
|
31
39
|
if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes <= 0)
|
|
32
40
|
throw new Error('maxBodyBytes must be a positive integer');
|
|
@@ -54,7 +62,7 @@ export function createHttpHandler(deps) {
|
|
|
54
62
|
const id = req.headers['mcp-session-id'];
|
|
55
63
|
if (id === undefined)
|
|
56
64
|
return null;
|
|
57
|
-
const state = sessions.get(String(id));
|
|
65
|
+
const state = sessions.get(String(id), sessionOwner(req));
|
|
58
66
|
if (state)
|
|
59
67
|
return state;
|
|
60
68
|
throw new HttpRequestError(404, 'Unknown or expired MCP session', {
|
|
@@ -62,6 +70,39 @@ export function createHttpHandler(deps) {
|
|
|
62
70
|
suggestion: 'Send a new initialize request without Mcp-Session-Id to start a new session',
|
|
63
71
|
});
|
|
64
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Who owns the sessions `req` creates and may use: with MCP authorization, its verified
|
|
75
|
+
* credentials' issuer, subject and client, so one caller's session is unknown to another and
|
|
76
|
+
* no caller's `initialize` displaces another's session. Without it the transport carries no
|
|
77
|
+
* identity: every caller is one owner, and the unguessable session ID is the only binding.
|
|
78
|
+
*/
|
|
79
|
+
function sessionOwner(req) {
|
|
80
|
+
return auth ? credentialsBinding(auth.credentialsFor(req)) : undefined;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Whose quota a session `req` creates counts against: with MCP authorization, the verified
|
|
84
|
+
* issuer and subject, so one subject with many client IDs shares one `maxSessionsPerOwner`.
|
|
85
|
+
*/
|
|
86
|
+
function sessionQuotaKey(req) {
|
|
87
|
+
const credentials = auth?.credentialsFor(req);
|
|
88
|
+
return credentials ? JSON.stringify([credentials.issuer, credentials.subject]) : undefined;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* `INSUFFICIENT_SCOPE` when the request's credentials lack a scope these calls need, decided
|
|
92
|
+
* after routing and before the confirmation gate (M6); none without MCP authorization.
|
|
93
|
+
*/
|
|
94
|
+
function scopeRefusal(req, calls) {
|
|
95
|
+
const view = auth?.viewFor(req);
|
|
96
|
+
const decision = view?.decideCommands(calls);
|
|
97
|
+
return view && decision && decision !== 'proceed'
|
|
98
|
+
? view.insufficientScope(decision.forbidden)
|
|
99
|
+
: undefined;
|
|
100
|
+
}
|
|
101
|
+
/** The steps naming commands that exist for the caller: a confirmation never names another. */
|
|
102
|
+
function existing(req, steps) {
|
|
103
|
+
const view = auth?.viewFor(req);
|
|
104
|
+
return view ? steps.filter((step) => view.known(step.command)) : steps;
|
|
105
|
+
}
|
|
65
106
|
function scoped(context, state) {
|
|
66
107
|
return state === undefined ? context : bindContextState(context, state);
|
|
67
108
|
}
|
|
@@ -75,10 +116,10 @@ export function createHttpHandler(deps) {
|
|
|
75
116
|
if (!res.writableFinished)
|
|
76
117
|
controller.abort(new Error('Client disconnected'));
|
|
77
118
|
});
|
|
78
|
-
const custom = await requestContextValues(createContext, req);
|
|
119
|
+
const custom = await requestContextValues(createContext, req, auth?.credentialsFor(req));
|
|
79
120
|
// Declared fields from `_meta` first, so a value `createContext` sets wins.
|
|
80
121
|
const declared = contextFieldValues(contextFields, meta);
|
|
81
|
-
return scoped({ ...declared, ...custom, signal: controller.signal, interface: 'mcp' }, state);
|
|
122
|
+
return bindScopeView(scoped(withMetaOutputBudget({ ...declared, ...custom, signal: controller.signal, interface: 'mcp' }, meta, custom), state), auth?.viewFor(req));
|
|
82
123
|
}
|
|
83
124
|
/** An input object without its `_meta` member, which carries request values, not input. */
|
|
84
125
|
function splitMeta(input) {
|
|
@@ -94,7 +135,7 @@ export function createHttpHandler(deps) {
|
|
|
94
135
|
}
|
|
95
136
|
catch (error) {
|
|
96
137
|
if (error instanceof JsonRpcError) {
|
|
97
|
-
return jsonRpcError(message.id, error.code, error.message, error.suggestion);
|
|
138
|
+
return jsonRpcError(message.id, error.code, error.message, error.suggestion, error.data);
|
|
98
139
|
}
|
|
99
140
|
report(error);
|
|
100
141
|
return jsonRpcError(message.id, JsonRpcErrorCode.INTERNAL_ERROR, devMode && error instanceof Error ? error.message : 'Internal error', 'Retry the request or contact the server operator');
|
|
@@ -105,13 +146,25 @@ export function createHttpHandler(deps) {
|
|
|
105
146
|
case 'ping':
|
|
106
147
|
case 'notifications/initialized':
|
|
107
148
|
return {};
|
|
108
|
-
case 'tools/list':
|
|
109
|
-
|
|
149
|
+
case 'tools/list': {
|
|
150
|
+
const view = auth?.viewFor(req);
|
|
151
|
+
// M6, "Other methods": a listing needs the required scopes.
|
|
152
|
+
const decision = view?.decideRequest();
|
|
153
|
+
if (view && decision && decision !== 'proceed') {
|
|
154
|
+
const error = view.insufficientScope(decision.forbidden);
|
|
155
|
+
throw new JsonRpcError(JsonRpcErrorCode.INVALID_REQUEST, error.message, error.suggestion);
|
|
156
|
+
}
|
|
157
|
+
return { tools: getToolsList(bindScopeView(scoped({}, state), view)) };
|
|
158
|
+
}
|
|
110
159
|
case 'tools/call': {
|
|
111
160
|
const params = message.params;
|
|
112
161
|
if (!isRecord(params) || typeof params.name !== 'string') {
|
|
113
162
|
throw new JsonRpcError(JsonRpcErrorCode.INVALID_PARAMS, 'tools/call requires params.name', 'Send params as { "name": "<tool>", "arguments": { ... } }');
|
|
114
163
|
}
|
|
164
|
+
// Approval evidence is never input, from any caller.
|
|
165
|
+
const keyed = approvalKeyInInput(params.arguments);
|
|
166
|
+
if (keyed)
|
|
167
|
+
return resultContent(failure(keyed), true);
|
|
115
168
|
const lifted = liftMetaArgument(params.name, params.arguments, params._meta, metaKeys);
|
|
116
169
|
if (!lifted.ok)
|
|
117
170
|
return resultContent(failure(lifted.error), true);
|
|
@@ -119,7 +172,25 @@ export function createHttpHandler(deps) {
|
|
|
119
172
|
if (!isRecord(args)) {
|
|
120
173
|
throw new JsonRpcError(JsonRpcErrorCode.INVALID_PARAMS, 'tools/call params.arguments must be an object', 'Send the tool arguments as a JSON object');
|
|
121
174
|
}
|
|
122
|
-
|
|
175
|
+
const context = await commandContext(req, res, state, undefined, lifted.meta);
|
|
176
|
+
// A 2025-era request: an approver gets its token but cannot carry it back here.
|
|
177
|
+
const actor = (context.actor ?? deps.actor);
|
|
178
|
+
const carrier = decideApprover({
|
|
179
|
+
approver: deps.approver,
|
|
180
|
+
context: { ...context, actor },
|
|
181
|
+
actor,
|
|
182
|
+
credentials: context.credentials,
|
|
183
|
+
meta: params._meta,
|
|
184
|
+
tool: params.name,
|
|
185
|
+
modern: false,
|
|
186
|
+
});
|
|
187
|
+
if (carrier.kind === 'refuse')
|
|
188
|
+
return resultContent(failure(carrier.error), true);
|
|
189
|
+
let routedContext = carrier.approver ? bindApprover(context, carrier.approver) : context;
|
|
190
|
+
if (deps.tasks) {
|
|
191
|
+
routedContext = bindTaskDispatch(routedContext, deps.tasks.legacyHttpDispatchFor(auth?.credentialsFor(req)));
|
|
192
|
+
}
|
|
193
|
+
return routeToolCall(params.name, args, routedContext);
|
|
123
194
|
}
|
|
124
195
|
default:
|
|
125
196
|
throw methodNotFound(message.method);
|
|
@@ -128,8 +199,29 @@ export function createHttpHandler(deps) {
|
|
|
128
199
|
async function handleMessage(req, res) {
|
|
129
200
|
const message = parseJsonRpcMessage(await readJsonBody(req, maxBodyBytes));
|
|
130
201
|
if (message.method === 'initialize' && !message.notification) {
|
|
131
|
-
if (sessions)
|
|
132
|
-
|
|
202
|
+
if (sessions) {
|
|
203
|
+
const id = sessions.create(sessionOwner(req), sessionQuotaKey(req));
|
|
204
|
+
if (id === undefined) {
|
|
205
|
+
// `-32000` with an AFD `data.code`, never `-32002`: that is MCP's deprecated
|
|
206
|
+
// SERVER_NOT_INITIALIZED, which servers must not emit.
|
|
207
|
+
res.setHeader('Retry-After', String(SESSION_RETRY_AFTER_S));
|
|
208
|
+
json(res, 503, {
|
|
209
|
+
jsonrpc: '2.0',
|
|
210
|
+
id: message.id,
|
|
211
|
+
error: {
|
|
212
|
+
code: JsonRpcErrorCode.SERVER_ERROR,
|
|
213
|
+
message: 'Too many live MCP sessions',
|
|
214
|
+
data: {
|
|
215
|
+
code: 'SESSION_LIMIT_REACHED',
|
|
216
|
+
suggestion: `Retry after ${SESSION_RETRY_AFTER_S} seconds (Retry-After), when idle sessions have expired, or reuse a session you hold by sending its Mcp-Session-Id`,
|
|
217
|
+
retryAfter: SESSION_RETRY_AFTER_S,
|
|
218
|
+
},
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
res.setHeader('Mcp-Session-Id', id);
|
|
224
|
+
}
|
|
133
225
|
json(res, 200, jsonRpcResult(message.id, {
|
|
134
226
|
protocolVersion: '2024-11-05',
|
|
135
227
|
capabilities: { tools: {} },
|
|
@@ -152,7 +244,11 @@ export function createHttpHandler(deps) {
|
|
|
152
244
|
const state = sessionState(req);
|
|
153
245
|
const body = await answer(message, async () => {
|
|
154
246
|
const { input, meta } = splitMeta(message.params ?? {});
|
|
155
|
-
const
|
|
247
|
+
const keyed = approvalKeyInInput(input);
|
|
248
|
+
if (keyed)
|
|
249
|
+
return { success: false, error: keyed };
|
|
250
|
+
const steps = [{ command: message.method, input }];
|
|
251
|
+
const refused = scopeRefusal(req, steps) ?? (await unconfirmed(req, existing(req, steps)));
|
|
156
252
|
if (refused)
|
|
157
253
|
return { success: false, error: refused };
|
|
158
254
|
return executeCommand(message.method, input, {
|
|
@@ -177,7 +273,10 @@ export function createHttpHandler(deps) {
|
|
|
177
273
|
throw new HttpRequestError(400, 'Invalid stream command name');
|
|
178
274
|
}
|
|
179
275
|
// GET is a safe method: link prefetchers and crawlers must not be able to trigger writes.
|
|
180
|
-
|
|
276
|
+
// A command hidden from this caller is not one here (M6), so it falls through to the
|
|
277
|
+
// engine's `COMMAND_NOT_FOUND`, the answer a server without it gives.
|
|
278
|
+
const shown = auth?.viewFor(req)?.known(commandName) ?? true;
|
|
279
|
+
if (req.method === 'GET' && shown && isMutation?.(commandName)) {
|
|
181
280
|
res.setHeader('Allow', 'POST');
|
|
182
281
|
json(res, 405, afdFailure('METHOD_NOT_ALLOWED', `Command '${truncateName(commandName)}' changes state and cannot be streamed with GET`, `POST /stream/${encodeURIComponent(commandName)} with the input as a JSON body`));
|
|
183
282
|
return;
|
|
@@ -203,7 +302,10 @@ export function createHttpHandler(deps) {
|
|
|
203
302
|
}
|
|
204
303
|
const split = splitMeta(input);
|
|
205
304
|
input = split.input;
|
|
206
|
-
const
|
|
305
|
+
const steps = [{ command: commandName, input }];
|
|
306
|
+
const refused = approvalKeyInInput(input) ??
|
|
307
|
+
scopeRefusal(req, steps) ??
|
|
308
|
+
(await unconfirmed(req, existing(req, steps)));
|
|
207
309
|
if (refused) {
|
|
208
310
|
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
|
|
209
311
|
res.end(`event: chunk\ndata: ${JSON.stringify(createErrorChunk(refused, 0, false))}\n\n`);
|
|
@@ -251,18 +353,23 @@ export function createHttpHandler(deps) {
|
|
|
251
353
|
}
|
|
252
354
|
async function route(req, res) {
|
|
253
355
|
const url = validateHttpRequest(req, deps);
|
|
356
|
+
// Only an origin `validateHttpRequest` accepted reaches here, and it is echoed, never `*`.
|
|
254
357
|
if (cors && req.headers.origin) {
|
|
255
|
-
res.setHeader('Access-Control-Allow-Origin',
|
|
358
|
+
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
|
|
256
359
|
res.setHeader('Vary', 'Origin');
|
|
257
360
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
258
361
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, Mcp-Session-Id, MCP-Protocol-Version, Mcp-Method, Mcp-Name, Afd-Confirm');
|
|
259
|
-
res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id');
|
|
362
|
+
res.setHeader('Access-Control-Expose-Headers', auth ? 'Mcp-Session-Id, WWW-Authenticate' : 'Mcp-Session-Id');
|
|
260
363
|
}
|
|
364
|
+
// A CORS preflight carries no token and reaches nothing.
|
|
261
365
|
if (req.method === 'OPTIONS') {
|
|
262
366
|
res.writeHead(204);
|
|
263
367
|
res.end();
|
|
264
368
|
return;
|
|
265
369
|
}
|
|
370
|
+
// M1, M2 and M7: the metadata is public; every other route needs a verified token.
|
|
371
|
+
if (auth && !(await auth.admit(req, res, url)))
|
|
372
|
+
return;
|
|
266
373
|
if (url.pathname === '/mcp' && modern) {
|
|
267
374
|
await modern.handle(req, res);
|
|
268
375
|
return;
|
|
@@ -272,6 +379,15 @@ export function createHttpHandler(deps) {
|
|
|
272
379
|
return;
|
|
273
380
|
}
|
|
274
381
|
if (url.pathname === '/sse' && req.method === 'GET') {
|
|
382
|
+
const scopeDecision = auth?.viewFor(req)?.decideRequest();
|
|
383
|
+
if (auth && scopeDecision && scopeDecision !== 'proceed') {
|
|
384
|
+
res.writeHead(403, {
|
|
385
|
+
'Content-Type': 'application/json',
|
|
386
|
+
'WWW-Authenticate': auth.protectedResource.forbiddenChallenge(scopeDecision.forbidden),
|
|
387
|
+
});
|
|
388
|
+
res.end(JSON.stringify(auth.protectedResource.forbiddenBody(scopeDecision.forbidden)));
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
275
391
|
if (sse.isFull()) {
|
|
276
392
|
res.setHeader('Retry-After', '5');
|
|
277
393
|
json(res, 503, afdFailure('SSE_CAPACITY_REACHED', 'Too many open SSE connections', 'Close idle SSE connections or retry later'));
|
|
@@ -300,7 +416,22 @@ export function createHttpHandler(deps) {
|
|
|
300
416
|
json(res, 400, failedBatchRequest());
|
|
301
417
|
return;
|
|
302
418
|
}
|
|
303
|
-
const
|
|
419
|
+
const limitError = checkBatchLimits(request, {
|
|
420
|
+
maxBatchSize: deps.maxBatchSize,
|
|
421
|
+
maxBatchParallelism: deps.maxBatchParallelism,
|
|
422
|
+
});
|
|
423
|
+
if (limitError) {
|
|
424
|
+
json(res, 400, createFailedBatchResult(limitError, {}));
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
const steps = request.commands.map((item) => ({
|
|
428
|
+
command: item.command,
|
|
429
|
+
input: item.input ?? {},
|
|
430
|
+
}));
|
|
431
|
+
// A batch fails as a whole before its first step (M6), as a confirmation does.
|
|
432
|
+
const refused = approvalKeyInInput(steps.map((step) => step.input)) ??
|
|
433
|
+
scopeRefusal(req, steps) ??
|
|
434
|
+
(await unconfirmed(req, existing(req, steps)));
|
|
304
435
|
if (refused) {
|
|
305
436
|
json(res, 200, createFailedBatchResult(refused, {}));
|
|
306
437
|
return;
|
|
@@ -316,7 +447,11 @@ export function createHttpHandler(deps) {
|
|
|
316
447
|
}
|
|
317
448
|
json(res, 404, { error: 'Not found' });
|
|
318
449
|
}
|
|
319
|
-
const handler = async (req, res) => {
|
|
450
|
+
const handler = async (req, res, body) => {
|
|
451
|
+
// A host's own layer read the body to decide it (M6): the routes read that instead.
|
|
452
|
+
if (body !== undefined) {
|
|
453
|
+
setPrereadBody(req, typeof body === 'string' ? Buffer.from(body, 'utf8') : Buffer.from(body));
|
|
454
|
+
}
|
|
320
455
|
// Rejected/unconsumed uploads can emit a late socket error after the response.
|
|
321
456
|
const observeRequestError = () => { };
|
|
322
457
|
req.on('error', observeRequestError);
|