@frontmcp/plugin-approval 1.10.9-rc.1 → 1.10.9-rc.2

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/esm/index.mjs CHANGED
@@ -1,1532 +1,4 @@
1
1
  var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : undefined;
2
2
  const require = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || 'file:///') : undefined;
3
3
  // __frontmcpCreateRequire
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined") return require.apply(this, arguments);
11
- throw Error('Dynamic require of "' + x + '" is not supported');
12
- });
13
- var __decorateClass = (decorators, target, key, kind) => {
14
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
15
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
16
- if (decorator = decorators[i])
17
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
18
- if (kind && result) __defProp(target, key, result);
19
- return result;
20
- };
21
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
-
23
- // plugins/plugin-approval/src/approval.plugin.ts
24
- import {
25
- DynamicPlugin as DynamicPlugin2,
26
- FRONTMCP_CONTEXT,
27
- Plugin as Plugin2,
28
- ProviderScope as ProviderScope4,
29
- ScopeEntry as ScopeEntry2
30
- } from "@frontmcp/sdk";
31
-
32
- // plugins/plugin-approval/src/approval.identity.ts
33
- import { randomUUID } from "@frontmcp/utils";
34
- function nonEmptyString(value) {
35
- return typeof value === "string" && value.length > 0 ? value : void 0;
36
- }
37
- function resolveApprovalIdentity(ctx) {
38
- const extra = ctx?.authInfo?.extra;
39
- const userId = nonEmptyString(extra?.["userId"]) ?? nonEmptyString(extra?.["sub"]) ?? nonEmptyString(ctx?.authInfo?.clientId);
40
- const sessionId = nonEmptyString(ctx?.verifiedSessionId);
41
- if (sessionId) {
42
- return { sessionId, userId };
43
- }
44
- return { sessionId: userId ? `stateless-user:${userId}` : `unidentified:${randomUUID()}`, userId };
45
- }
46
-
47
- // plugins/plugin-approval/src/approval.symbols.ts
48
- var ApprovalStoreToken = /* @__PURE__ */ Symbol.for(
49
- "plugin:approval:store"
50
- );
51
- var ApprovalServiceToken = /* @__PURE__ */ Symbol.for(
52
- "plugin:approval:service"
53
- );
54
- var ChallengeServiceToken = /* @__PURE__ */ Symbol.for(
55
- "plugin:approval:challenge-service"
56
- );
57
-
58
- // plugins/plugin-approval/src/approval/errors.ts
59
- import { PublicMcpError } from "@frontmcp/sdk";
60
- var ApprovalError = class extends PublicMcpError {
61
- constructor(message, code = "APPROVAL_REQUIRED", statusCode = 403) {
62
- super(message, code, statusCode);
63
- this.name = "ApprovalError";
64
- }
65
- };
66
- var ApprovalRequiredError = class extends ApprovalError {
67
- constructor(details) {
68
- super(details.message);
69
- this.details = details;
70
- this.name = "ApprovalRequiredError";
71
- }
72
- details;
73
- /**
74
- * Convert to a JSON-RPC compatible error structure.
75
- */
76
- toJsonRpcError() {
77
- return {
78
- code: -32600,
79
- // Invalid Request
80
- message: this.details.message,
81
- data: {
82
- type: "approval_required",
83
- toolId: this.details.toolId,
84
- state: this.details.state,
85
- options: this.details.approvalOptions
86
- }
87
- };
88
- }
89
- };
90
- var ApprovalOperationError = class extends ApprovalError {
91
- constructor(operation, reason) {
92
- super(`Approval ${operation} failed: ${reason}`, "APPROVAL_OPERATION_FAILED", 400);
93
- this.operation = operation;
94
- this.reason = reason;
95
- this.name = "ApprovalOperationError";
96
- }
97
- operation;
98
- reason;
99
- /**
100
- * Convert to a JSON-RPC compatible error structure.
101
- */
102
- toJsonRpcError() {
103
- return {
104
- code: -32603,
105
- // Internal Error
106
- message: "Approval operation failed",
107
- data: {
108
- type: "approval_operation_error",
109
- operation: this.operation
110
- }
111
- };
112
- }
113
- };
114
- var ApprovalScopeNotAllowedError = class extends ApprovalError {
115
- constructor(requestedScope, allowedScopes) {
116
- super(
117
- `Approval scope '${requestedScope}' is not allowed for this tool. Allowed scopes: ${allowedScopes.join(", ")}`,
118
- "APPROVAL_SCOPE_NOT_ALLOWED",
119
- 400
120
- );
121
- this.requestedScope = requestedScope;
122
- this.allowedScopes = allowedScopes;
123
- this.name = "ApprovalScopeNotAllowedError";
124
- }
125
- requestedScope;
126
- allowedScopes;
127
- /**
128
- * Convert to a JSON-RPC compatible error structure.
129
- */
130
- toJsonRpcError() {
131
- return {
132
- code: -32602,
133
- // Invalid Params
134
- message: this.message,
135
- data: {
136
- type: "approval_scope_not_allowed",
137
- requestedScope: this.requestedScope,
138
- allowedScopes: this.allowedScopes
139
- }
140
- };
141
- }
142
- };
143
- var ApprovalExpiredError = class extends ApprovalError {
144
- constructor(toolId, expiredAt) {
145
- super(`Approval for tool '${toolId}' expired at ${new Date(expiredAt).toISOString()}`, "APPROVAL_EXPIRED", 403);
146
- this.toolId = toolId;
147
- this.expiredAt = expiredAt;
148
- this.name = "ApprovalExpiredError";
149
- }
150
- toolId;
151
- expiredAt;
152
- /**
153
- * Convert to a JSON-RPC compatible error structure.
154
- */
155
- toJsonRpcError() {
156
- return {
157
- code: -32600,
158
- // Invalid Request
159
- message: this.message,
160
- data: {
161
- type: "approval_expired",
162
- toolId: this.toolId,
163
- expiredAt: this.expiredAt
164
- }
165
- };
166
- }
167
- };
168
- var ChallengeValidationError = class extends ApprovalError {
169
- constructor(reason = "invalid", message) {
170
- super(message ?? `PKCE challenge validation failed: ${reason}`, "CHALLENGE_VALIDATION_FAILED", 400);
171
- this.reason = reason;
172
- this.name = "ChallengeValidationError";
173
- }
174
- reason;
175
- /**
176
- * Convert to a JSON-RPC compatible error structure.
177
- */
178
- toJsonRpcError() {
179
- return {
180
- code: -32600,
181
- // Invalid Request
182
- message: this.message,
183
- data: {
184
- type: "challenge_validation_error",
185
- reason: this.reason
186
- }
187
- };
188
- }
189
- };
190
-
191
- // plugins/plugin-approval/src/approval/types.ts
192
- var ApprovalScope = /* @__PURE__ */ ((ApprovalScope2) => {
193
- ApprovalScope2["SESSION"] = "session";
194
- ApprovalScope2["USER"] = "user";
195
- ApprovalScope2["TIME_LIMITED"] = "time_limited";
196
- ApprovalScope2["TOOL_SPECIFIC"] = "tool_specific";
197
- ApprovalScope2["CONTEXT_SPECIFIC"] = "context_specific";
198
- return ApprovalScope2;
199
- })(ApprovalScope || {});
200
- var ApprovalState = /* @__PURE__ */ ((ApprovalState2) => {
201
- ApprovalState2["PENDING"] = "pending";
202
- ApprovalState2["APPROVED"] = "approved";
203
- ApprovalState2["DENIED"] = "denied";
204
- ApprovalState2["EXPIRED"] = "expired";
205
- return ApprovalState2;
206
- })(ApprovalState || {});
207
-
208
- // plugins/plugin-approval/src/approval/policy.ts
209
- function resolveApprovalRequirement(config) {
210
- if (config === true) {
211
- return { required: true, defaultScope: "session" /* SESSION */ };
212
- }
213
- if (config === false || config === void 0) {
214
- return { required: false };
215
- }
216
- return {
217
- ...config,
218
- required: config.required ?? true,
219
- defaultScope: config.defaultScope ?? "session" /* SESSION */
220
- };
221
- }
222
- function effectiveExpiresAt(record, requirement) {
223
- const capped = requirement.maxTtlMs !== void 0 ? record.grantedAt + requirement.maxTtlMs : void 0;
224
- if (record.expiresAt === void 0) return capped;
225
- return capped === void 0 ? record.expiresAt : Math.min(record.expiresAt, capped);
226
- }
227
- function isApprovalExpired(record, requirement, now) {
228
- const expiresAt = effectiveExpiresAt(record, requirement);
229
- return expiresAt !== void 0 && now > expiresAt;
230
- }
231
- function isApprovalUsable(record, requirement, now) {
232
- if (record.state !== "approved" /* APPROVED */) return false;
233
- if (requirement.allowedScopes?.length && !requirement.allowedScopes.includes(record.scope)) return false;
234
- return !isApprovalExpired(record, requirement, now);
235
- }
236
- function assertValidTtl(ttlMs) {
237
- if (ttlMs === void 0) return;
238
- if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
239
- throw new ApprovalOperationError("grant", `ttlMs must be a positive number of milliseconds, got ${ttlMs}`);
240
- }
241
- }
242
- function checkGrantAgainstPolicy(toolId, scope, ttlMs, requirement) {
243
- assertValidTtl(ttlMs);
244
- if (!requirement) return ttlMs;
245
- if (requirement.allowedScopes?.length && !requirement.allowedScopes.includes(scope)) {
246
- throw new ApprovalScopeNotAllowedError(scope, requirement.allowedScopes);
247
- }
248
- const { maxTtlMs } = requirement;
249
- if (maxTtlMs === void 0) return ttlMs;
250
- if (ttlMs === void 0) return maxTtlMs;
251
- if (ttlMs > maxTtlMs) {
252
- throw new ApprovalOperationError(
253
- "grant",
254
- `ttlMs ${ttlMs} exceeds the maximum of ${maxTtlMs} ms that tool "${toolId}" allows`
255
- );
256
- }
257
- return ttlMs;
258
- }
259
-
260
- // plugins/plugin-approval/src/hooks/approval-check.hook.ts
261
- import { DynamicPlugin, isEntryGatedBy, Plugin, ScopeEntry, ToolHook } from "@frontmcp/sdk";
262
-
263
- // plugins/plugin-approval/src/approval/schemas.ts
264
- import { z } from "@frontmcp/lazy-zod";
265
- var approvalScopeSchema = z.nativeEnum(ApprovalScope);
266
- var approvalStateSchema = z.nativeEnum(ApprovalState);
267
- var approvalMethodSchema = z.enum(["interactive", "implicit", "delegation", "batch", "api"]);
268
- var approvalSourceTypeSchema = z.string().min(1);
269
- var revocationMethodSchema = z.enum(["interactive", "implicit", "policy", "expiry"]);
270
- var approvalCategorySchema = z.enum(["read", "write", "delete", "execute", "admin"]);
271
- var riskLevelSchema = z.enum(["low", "medium", "high", "critical"]);
272
- var approvalContextSchema = z.object({
273
- type: z.string().min(1),
274
- identifier: z.string().min(1),
275
- metadata: z.record(z.string(), z.unknown()).optional()
276
- });
277
- var delegationContextSchema = z.object({
278
- delegatorId: z.string().min(1),
279
- delegateId: z.string().min(1),
280
- purpose: z.string().optional(),
281
- constraints: z.record(z.string(), z.unknown()).optional()
282
- });
283
- var approvalGrantorSchema = z.object({
284
- source: approvalSourceTypeSchema,
285
- identifier: z.string().optional(),
286
- displayName: z.string().optional(),
287
- method: approvalMethodSchema.optional(),
288
- origin: z.string().optional(),
289
- delegationContext: delegationContextSchema.optional()
290
- });
291
- var approvalRevokerSchema = z.object({
292
- source: z.string().min(1),
293
- identifier: z.string().optional(),
294
- displayName: z.string().optional(),
295
- method: revocationMethodSchema.optional()
296
- });
297
- var approvalRecordSchema = z.object({
298
- toolId: z.string().min(1),
299
- state: approvalStateSchema,
300
- scope: approvalScopeSchema,
301
- grantedAt: z.number(),
302
- expiresAt: z.number().optional(),
303
- ttlMs: z.number().optional(),
304
- sessionId: z.string().optional(),
305
- userId: z.string().optional(),
306
- context: approvalContextSchema.optional(),
307
- grantedBy: approvalGrantorSchema,
308
- approvalChain: z.array(approvalGrantorSchema).optional(),
309
- reason: z.string().optional(),
310
- metadata: z.record(z.string(), z.unknown()).optional(),
311
- revokedAt: z.number().optional(),
312
- revokedBy: approvalRevokerSchema.optional(),
313
- revocationReason: z.string().optional()
314
- });
315
- var toolApprovalRequirementSchema = z.object({
316
- required: z.boolean().optional(),
317
- defaultScope: approvalScopeSchema.optional(),
318
- allowedScopes: z.array(approvalScopeSchema).optional(),
319
- maxTtlMs: z.number().positive().optional(),
320
- alwaysPrompt: z.boolean().optional(),
321
- skipApproval: z.boolean().optional(),
322
- approvalMessage: z.string().optional(),
323
- category: approvalCategorySchema.optional(),
324
- riskLevel: riskLevelSchema.optional(),
325
- preApprovedContexts: z.array(approvalContextSchema).optional()
326
- });
327
-
328
- // plugins/plugin-approval/src/approval/factories.ts
329
- function userGrantor(userId, displayName, options) {
330
- return {
331
- source: "user",
332
- identifier: userId,
333
- displayName,
334
- method: options?.method ?? "interactive",
335
- origin: options?.origin
336
- };
337
- }
338
- function policyGrantor(policyId, policyName) {
339
- return {
340
- source: "policy",
341
- identifier: policyId,
342
- displayName: policyName,
343
- method: "implicit"
344
- };
345
- }
346
- function adminGrantor(adminId, displayName, options) {
347
- return {
348
- source: "admin",
349
- identifier: adminId,
350
- displayName,
351
- method: options?.method ?? "interactive",
352
- origin: options?.origin
353
- };
354
- }
355
- function systemGrantor(systemId = "system") {
356
- return {
357
- source: "system",
358
- identifier: systemId,
359
- method: "implicit"
360
- };
361
- }
362
- function agentGrantor(agentId, delegationContext, displayName) {
363
- return {
364
- source: "agent",
365
- identifier: agentId,
366
- displayName,
367
- method: "delegation",
368
- delegationContext
369
- };
370
- }
371
- function apiGrantor(apiKeyPrefix, serviceName) {
372
- return {
373
- source: "api",
374
- identifier: apiKeyPrefix,
375
- displayName: serviceName,
376
- method: "api",
377
- origin: "api"
378
- };
379
- }
380
- function oauthGrantor(tokenId, provider) {
381
- return {
382
- source: "oauth",
383
- identifier: tokenId,
384
- displayName: provider,
385
- method: "api",
386
- origin: "oauth"
387
- };
388
- }
389
- function testGrantor() {
390
- return {
391
- source: "test",
392
- identifier: "test",
393
- method: "implicit"
394
- };
395
- }
396
- function customGrantor(source, identifier, options) {
397
- return {
398
- source,
399
- identifier,
400
- displayName: options?.displayName,
401
- method: options?.method,
402
- origin: options?.origin,
403
- delegationContext: options?.delegationContext
404
- };
405
- }
406
- function userRevoker(userId, displayName) {
407
- return {
408
- source: "user",
409
- identifier: userId,
410
- displayName,
411
- method: "interactive"
412
- };
413
- }
414
- function adminRevoker(adminId, displayName) {
415
- return {
416
- source: "admin",
417
- identifier: adminId,
418
- displayName,
419
- method: "interactive"
420
- };
421
- }
422
- function expiryRevoker() {
423
- return {
424
- source: "expiry",
425
- method: "expiry"
426
- };
427
- }
428
- function sessionEndRevoker(sessionId) {
429
- return {
430
- source: "session_end",
431
- identifier: sessionId,
432
- method: "implicit"
433
- };
434
- }
435
- function policyRevoker(policyId, policyName) {
436
- return {
437
- source: "policy",
438
- identifier: policyId,
439
- displayName: policyName,
440
- method: "policy"
441
- };
442
- }
443
- function normalizeGrantor(input) {
444
- if (!input) {
445
- return { source: "user" };
446
- }
447
- if (typeof input === "string") {
448
- return { source: input };
449
- }
450
- return input;
451
- }
452
- function normalizeRevoker(input) {
453
- if (!input) {
454
- return { source: "user" };
455
- }
456
- if (typeof input === "string") {
457
- return { source: input };
458
- }
459
- return input;
460
- }
461
-
462
- // plugins/plugin-approval/src/approval/guards.ts
463
- function isGrantorSource(grantor, source) {
464
- return grantor.source === source;
465
- }
466
- function isHumanGrantor(grantor) {
467
- return grantor.source === "user" || grantor.source === "admin";
468
- }
469
- function isAutoGrantor(grantor) {
470
- return grantor.source === "policy" || grantor.source === "system" || grantor.source === "test";
471
- }
472
- function isDelegatedGrantor(grantor) {
473
- return grantor.source === "agent" && !!grantor.delegationContext;
474
- }
475
- function isApiGrantor(grantor) {
476
- return grantor.source === "api" || grantor.source === "oauth";
477
- }
478
-
479
- // plugins/plugin-approval/src/hooks/approval-check.hook.ts
480
- var decidedCalls = /* @__PURE__ */ new WeakSet();
481
- var ApprovalCheckPlugin = class extends DynamicPlugin {
482
- async checkApproval(flowCtx) {
483
- const { tool, toolContext } = flowCtx.state;
484
- if (!tool || !toolContext) return;
485
- const metadata = tool.metadata;
486
- const approvalConfig = resolveApprovalRequirement(
487
- metadata["approval"]
488
- );
489
- if (!approvalConfig.required) {
490
- return;
491
- }
492
- if (approvalConfig.skipApproval) {
493
- return;
494
- }
495
- if (decidedCalls.has(toolContext)) return;
496
- await this.enforceApproval(flowCtx, tool, toolContext, approvalConfig, this.coveringStores(tool));
497
- decidedCalls.add(toolContext);
498
- }
499
- async enforceApproval(flowCtx, tool, toolContext, approvalConfig, stores) {
500
- const { sessionId, userId } = resolveApprovalIdentity(toolContext.tryGetContext?.());
501
- const currentContext = this.getCurrentContext(flowCtx);
502
- const stored = [];
503
- for (const store of stores) {
504
- const records2 = await this.readApprovals(store, tool.fullName, sessionId, userId, currentContext);
505
- stored.push(...records2.map((record) => ({ store, record })));
506
- }
507
- const records = stored.map(({ record }) => record);
508
- if (records.some((record) => record.state === "denied" /* DENIED */)) {
509
- throw new ApprovalRequiredError({
510
- toolId: tool.fullName,
511
- state: "denied",
512
- message: `Tool "${tool.fullName}" execution denied.`
513
- });
514
- }
515
- if (!approvalConfig.alwaysPrompt && this.isPreApprovedContext(approvalConfig, currentContext)) {
516
- return;
517
- }
518
- const approved = records.filter((record) => record.state === "approved" /* APPROVED */);
519
- const now = Date.now();
520
- const usable = stored.filter(({ record }) => isApprovalUsable(record, approvalConfig, now));
521
- if (approvalConfig.alwaysPrompt) {
522
- for (const { store, record } of usable) {
523
- if (await this.consumeApproval(store, record, sessionId, userId, currentContext)) return;
524
- }
525
- } else if (usable.length > 0) {
526
- return;
527
- }
528
- await this.handleApprovalRequired(
529
- flowCtx,
530
- approvalConfig,
531
- approved.find((record) => isApprovalExpired(record, approvalConfig, now)) ?? approved[0]
532
- );
533
- }
534
- /**
535
- * The stores of every approval gate that runs for the tool: this plugin's, and that of each other
536
- * `ApprovalCheckPlugin` whose hook the scope runs for it (an `ApprovalPlugin` on the server and
537
- * one on the tool's app, say). One store shared by two gates counts once.
538
- */
539
- coveringStores(tool) {
540
- const stores = /* @__PURE__ */ new Set([this.get(ApprovalStoreToken)]);
541
- let scope;
542
- try {
543
- scope = this.get(ScopeEntry);
544
- } catch {
545
- scope = void 0;
546
- }
547
- if (!scope?.hooks) return [...stores];
548
- for (const hook of scope.hooks.getFlowHooks("tools:call-tool")) {
549
- const gate = hook.metadata.target;
550
- if (gate instanceof ApprovalCheckPlugin && isEntryGatedBy(scope, { tool }, gate)) {
551
- stores.add(gate.get(ApprovalStoreToken));
552
- }
553
- }
554
- return [...stores];
555
- }
556
- /**
557
- * Use up an approval of an `alwaysPrompt` tool, reporting whether this call got it.
558
- *
559
- * `consumeApproval()` deletes exactly that record, and only one of two calls racing for it wins.
560
- * A store without it has the caller's approvals of the tool revoked instead, which leaves none
561
- * standing but cannot tell two concurrent calls apart.
562
- */
563
- async consumeApproval(store, record, sessionId, userId, context) {
564
- if (store.consumeApproval) {
565
- return store.consumeApproval(record, sessionId, userId, context);
566
- }
567
- return store.revokeApproval({
568
- toolId: record.toolId,
569
- sessionId,
570
- userId,
571
- revokedBy: "system",
572
- reason: "Used by a call of an alwaysPrompt tool"
573
- });
574
- }
575
- /**
576
- * The caller's approvals and denials of the tool, from the context it runs in too. Stores
577
- * without `getApprovals()` give the one record `getApproval()` picks.
578
- */
579
- async readApprovals(store, toolId, sessionId, userId, context) {
580
- if (store.getApprovals) {
581
- return store.getApprovals(toolId, sessionId, userId, context);
582
- }
583
- const record = await store.getApproval(toolId, sessionId, userId, context);
584
- return record ? [record] : [];
585
- }
586
- /**
587
- * The context this call is running in, as established by the SESSION (GHSA-r848-p7wf-96rc).
588
- *
589
- * Deliberately ignores `toolContext.input.context`. The only consumer of this value is
590
- * `isPreApprovedContext`, which skips the approval prompt outright, so reading it from the
591
- * arguments of the call being gated let a caller name its own pre-approved context and walk
592
- * straight past the gate. Only `authInfo.extra.approvalContext`, which the server sets
593
- * while authenticating, can say what context a call belongs to.
594
- */
595
- getCurrentContext(flowCtx) {
596
- const ctx = flowCtx.state.toolContext?.tryGetContext?.();
597
- const sessionContext = ctx?.authInfo?.extra?.["approvalContext"];
598
- return this.isApprovalContext(sessionContext) ? sessionContext : void 0;
599
- }
600
- isApprovalContext(value) {
601
- return typeof value === "object" && value !== null && "type" in value && "identifier" in value && typeof value.type === "string" && typeof value.identifier === "string";
602
- }
603
- isPreApprovedContext(config, currentContext) {
604
- if (!currentContext || !config.preApprovedContexts?.length) {
605
- return false;
606
- }
607
- return config.preApprovedContexts.some(
608
- (preApproved) => preApproved.type === currentContext.type && preApproved.identifier === currentContext.identifier
609
- );
610
- }
611
- async handleApprovalRequired(flowCtx, config, existingApproval) {
612
- const { tool } = flowCtx.state;
613
- const message = config.approvalMessage ?? `Tool "${tool?.fullName}" requires approval to execute. Allow?`;
614
- const isExpiredApproval = existingApproval ? isApprovalExpired(existingApproval, config, Date.now()) : false;
615
- throw new ApprovalRequiredError({
616
- toolId: tool?.fullName ?? "unknown",
617
- state: isExpiredApproval ? "expired" : "pending",
618
- message,
619
- approvalOptions: {
620
- allowedScopes: config.allowedScopes,
621
- defaultScope: config.defaultScope,
622
- maxTtlMs: config.maxTtlMs,
623
- category: config.category,
624
- riskLevel: config.riskLevel
625
- }
626
- });
627
- }
628
- };
629
- __decorateClass([
630
- ToolHook.Will("execute", { priority: 100, appliesTo: "uncovered-apps" })
631
- ], ApprovalCheckPlugin.prototype, "checkApproval", 1);
632
- ApprovalCheckPlugin = __decorateClass([
633
- Plugin({
634
- name: "approval:check",
635
- description: "Checks tool approval state before execution",
636
- // A server where a tool or agent declares `approval` and this gate does not reach it refuses to start.
637
- enforcesMetadata: ["approval"]
638
- })
639
- ], ApprovalCheckPlugin);
640
-
641
- // plugins/plugin-approval/src/services/approval.service.ts
642
- import { isAnonymousSubject, Provider, ProviderScope } from "@frontmcp/sdk";
643
- var ApprovalService = class {
644
- constructor(store, sessionId, userId, requirementOf = () => void 0) {
645
- this.store = store;
646
- this.sessionId = sessionId;
647
- this.userId = userId;
648
- this.requirementOf = requirementOf;
649
- }
650
- store;
651
- sessionId;
652
- userId;
653
- requirementOf;
654
- /** Checks a grant against the tool's `allowedScopes` and `maxTtlMs`; returns the ttl to store. */
655
- checkGrant(toolId, scope, ttlMs) {
656
- return checkGrantAgainstPolicy(toolId, scope, ttlMs, this.requirementOf(toolId));
657
- }
658
- /** The caller's user id, when it names a principal: an anonymous subject (`anon:…`) names no one. */
659
- get signedInUserId() {
660
- return this.userId && !isAnonymousSubject(this.userId) ? this.userId : void 0;
661
- }
662
- /**
663
- * Who a grant is recorded as when the call names no one: the signed-in user whose tool call made it.
664
- * It used to be `'policy'`, so an audit trail showed every approval a user gave as a policy's.
665
- * Without a signed-in user it is a user with no identifier.
666
- *
667
- * The method is `'implicit'`: a tool that grants through `this.approval` asked no one, so the grant
668
- * is not an `'interactive'` answer. A tool that did ask passes `grantedBy: userGrantor(id)`.
669
- */
670
- defaultGrantor() {
671
- const userId = this.signedInUserId;
672
- return userId ? userGrantor(userId, void 0, { method: "implicit" }) : { source: "user", method: "implicit" };
673
- }
674
- /** Who a revocation is recorded as when the call names no one, by the same rule as a grant. */
675
- defaultRevoker() {
676
- const userId = this.signedInUserId;
677
- return userId ? { source: "user", identifier: userId, method: "implicit" } : { source: "user", method: "implicit" };
678
- }
679
- // ─────────────────────────────────────────────────────────────────────────────
680
- // Query Methods
681
- // ─────────────────────────────────────────────────────────────────────────────
682
- /**
683
- * Check if a tool is approved for current session/user.
684
- */
685
- async isApproved(toolId, context) {
686
- const requirement = this.requirementOf(toolId);
687
- if (!requirement || !this.store.getApprovals) {
688
- return this.store.isApproved(toolId, this.sessionId, this.userId, context);
689
- }
690
- const records = await this.store.getApprovals(toolId, this.sessionId, this.userId, context);
691
- if (records.some((record) => record.state === "denied" /* DENIED */)) return false;
692
- const now = Date.now();
693
- return records.some((record) => isApprovalUsable(record, requirement, now));
694
- }
695
- /**
696
- * Get approval record for a tool.
697
- */
698
- async getApproval(toolId) {
699
- return this.store.getApproval(toolId, this.sessionId, this.userId);
700
- }
701
- /**
702
- * Get all approvals for current session.
703
- */
704
- async getSessionApprovals() {
705
- return this.store.queryApprovals({
706
- sessionId: this.sessionId,
707
- states: ["approved" /* APPROVED */],
708
- includeExpired: false
709
- });
710
- }
711
- /**
712
- * Get all approvals for current user (across sessions).
713
- */
714
- async getUserApprovals() {
715
- if (!this.userId) return [];
716
- return this.store.queryApprovals({
717
- userId: this.userId,
718
- scope: "user" /* USER */,
719
- states: ["approved" /* APPROVED */],
720
- includeExpired: false
721
- });
722
- }
723
- /**
724
- * Query the current caller's approvals (those of its session and those of its user) with custom
725
- * filters. A `sessionId` or `userId` in the query narrows the result further; it never reaches
726
- * another caller's records. Read the store directly for administrative queries.
727
- */
728
- async queryApprovals(query) {
729
- const records = await this.store.queryApprovals(query);
730
- return records.filter(
731
- (record) => record.sessionId === this.sessionId || this.userId !== void 0 && record.userId === this.userId
732
- );
733
- }
734
- /**
735
- * The caller's recent revocations of a tool, newest last: each is the approval that was revoked,
736
- * with `revokedBy`, `revokedAt` and `revocationReason`. Empty when the store keeps no revocations.
737
- */
738
- async getRevocations(toolId) {
739
- return await this.store.getRevocations?.(toolId, this.sessionId, this.userId) ?? [];
740
- }
741
- // ─────────────────────────────────────────────────────────────────────────────
742
- // Grant Methods
743
- // ─────────────────────────────────────────────────────────────────────────────
744
- /**
745
- * Grant session-scoped approval for a tool.
746
- */
747
- async grantSessionApproval(toolId, options = {}) {
748
- const ttlMs = this.checkGrant(toolId, "session" /* SESSION */);
749
- return this.store.grantApproval({
750
- toolId,
751
- scope: "session" /* SESSION */,
752
- ttlMs,
753
- sessionId: this.sessionId,
754
- grantedBy: options.grantedBy ?? this.defaultGrantor(),
755
- reason: options.reason,
756
- metadata: options.metadata
757
- });
758
- }
759
- /**
760
- * Grant user-scoped approval for a tool.
761
- */
762
- async grantUserApproval(toolId, options = {}) {
763
- if (!this.userId) {
764
- throw new Error("Cannot grant user approval without userId");
765
- }
766
- const ttlMs = this.checkGrant(toolId, "user" /* USER */);
767
- return this.store.grantApproval({
768
- toolId,
769
- scope: "user" /* USER */,
770
- ttlMs,
771
- userId: this.userId,
772
- grantedBy: options.grantedBy ?? this.defaultGrantor(),
773
- reason: options.reason,
774
- metadata: options.metadata
775
- });
776
- }
777
- /**
778
- * Grant time-limited approval for a tool.
779
- */
780
- async grantTimeLimitedApproval(toolId, ttlMs, options = {}) {
781
- this.checkGrant(toolId, "time_limited" /* TIME_LIMITED */, ttlMs);
782
- return this.store.grantApproval({
783
- toolId,
784
- scope: "time_limited" /* TIME_LIMITED */,
785
- ttlMs,
786
- sessionId: this.sessionId,
787
- userId: this.userId,
788
- grantedBy: options.grantedBy ?? this.defaultGrantor(),
789
- reason: options.reason,
790
- metadata: options.metadata
791
- });
792
- }
793
- /**
794
- * Grant context-specific approval for a tool.
795
- */
796
- async grantContextApproval(toolId, context, options = {}) {
797
- const ttlMs = this.checkGrant(toolId, "context_specific" /* CONTEXT_SPECIFIC */);
798
- return this.store.grantApproval({
799
- toolId,
800
- scope: "context_specific" /* CONTEXT_SPECIFIC */,
801
- ttlMs,
802
- context,
803
- sessionId: this.sessionId,
804
- userId: this.userId,
805
- grantedBy: options.grantedBy ?? this.defaultGrantor(),
806
- reason: options.reason,
807
- metadata: options.metadata
808
- });
809
- }
810
- // ─────────────────────────────────────────────────────────────────────────────
811
- // Revoke Methods
812
- // ─────────────────────────────────────────────────────────────────────────────
813
- /**
814
- * Revoke the caller's approvals of a tool: its session, user, time-limited and context
815
- * approvals. Returns whether anything was revoked. Recorded denials are kept.
816
- */
817
- async revokeApproval(toolId, options = {}) {
818
- return this.store.revokeApproval({
819
- toolId,
820
- sessionId: this.sessionId,
821
- userId: this.userId,
822
- revokedBy: options.revokedBy ?? this.defaultRevoker(),
823
- reason: options.reason
824
- });
825
- }
826
- /**
827
- * Clear all session approvals.
828
- */
829
- async clearSessionApprovals() {
830
- return this.store.clearSessionApprovals(this.sessionId);
831
- }
832
- };
833
- ApprovalService = __decorateClass([
834
- Provider({
835
- name: "provider:approval:service",
836
- description: "Service for managing tool approvals",
837
- scope: ProviderScope.CONTEXT
838
- })
839
- ], ApprovalService);
840
- function createApprovalService(store, sessionId, userId, requirementOf) {
841
- return new ApprovalService(store, sessionId, userId, requirementOf);
842
- }
843
-
844
- // plugins/plugin-approval/src/services/challenge.service.ts
845
- import { Provider as Provider2, ProviderScope as ProviderScope2 } from "@frontmcp/sdk";
846
- import {
847
- generatePkcePair,
848
- generateCodeChallenge,
849
- createStorage,
850
- createMemoryStorage
851
- } from "@frontmcp/utils";
852
- var ChallengeService = class {
853
- storage;
854
- options;
855
- initialized = false;
856
- ownedStorage = false;
857
- constructor(options = {}) {
858
- this.options = {
859
- storage: options.storage ?? { type: "auto" },
860
- storageInstance: options.storageInstance,
861
- namespace: options.namespace ?? "approval:challenge",
862
- defaultTtlSeconds: options.defaultTtlSeconds ?? 300
863
- };
864
- }
865
- /**
866
- * Initialize the service.
867
- */
868
- async initialize() {
869
- if (this.initialized) return;
870
- if (this.options.storageInstance) {
871
- this.storage = this.options.storageInstance.namespace(this.options.namespace);
872
- this.ownedStorage = false;
873
- } else {
874
- const rootStorage = await createStorage(this.options.storage);
875
- this.storage = rootStorage.namespace(this.options.namespace);
876
- this.ownedStorage = true;
877
- }
878
- this.initialized = true;
879
- }
880
- ensureInitialized() {
881
- if (!this.initialized) {
882
- throw new Error("ChallengeService not initialized. Call initialize() first.");
883
- }
884
- }
885
- /**
886
- * Create a new PKCE challenge for a tool approval request.
887
- *
888
- * @returns Object containing code_verifier (keep secret) and code_challenge (send to webhook)
889
- */
890
- async createChallenge(options) {
891
- this.ensureInitialized();
892
- const { codeVerifier, codeChallenge } = generatePkcePair();
893
- const now = Date.now();
894
- const ttlSeconds = options.ttlSeconds ?? this.options.defaultTtlSeconds;
895
- const expiresAt = now + ttlSeconds * 1e3;
896
- const record = {
897
- toolId: options.toolId,
898
- sessionId: options.sessionId,
899
- userId: options.userId,
900
- requestedScope: options.requestedScope,
901
- requestInfo: options.requestInfo,
902
- createdAt: now,
903
- expiresAt,
904
- webhookSent: false
905
- };
906
- await this.storage.set(codeChallenge, JSON.stringify(record), { ttlSeconds });
907
- return { codeVerifier, codeChallenge, expiresAt };
908
- }
909
- /**
910
- * Verify a code verifier and retrieve the challenge record.
911
- *
912
- * @throws ChallengeValidationError if verification fails
913
- */
914
- async verifyAndConsume(codeVerifier) {
915
- this.ensureInitialized();
916
- const { codeChallenge } = generatePkcePairFromVerifier(codeVerifier);
917
- const recordJson = await this.storage.get(codeChallenge);
918
- if (!recordJson) {
919
- throw new ChallengeValidationError("not_found", "Invalid or expired challenge");
920
- }
921
- const record = JSON.parse(recordJson);
922
- if (Date.now() > record.expiresAt) {
923
- await this.storage.delete(codeChallenge);
924
- throw new ChallengeValidationError("expired", "Challenge expired");
925
- }
926
- await this.storage.delete(codeChallenge);
927
- return record;
928
- }
929
- /**
930
- * Mark a challenge as having been sent to webhook.
931
- */
932
- async markWebhookSent(codeChallenge) {
933
- this.ensureInitialized();
934
- const recordJson = await this.storage.get(codeChallenge);
935
- if (!recordJson) return false;
936
- const record = JSON.parse(recordJson);
937
- record.webhookSent = true;
938
- const remainingMs = record.expiresAt - Date.now();
939
- if (remainingMs <= 0) {
940
- await this.storage.delete(codeChallenge);
941
- return false;
942
- }
943
- const ttlSeconds = Math.ceil(remainingMs / 1e3);
944
- await this.storage.set(codeChallenge, JSON.stringify(record), { ttlSeconds });
945
- return true;
946
- }
947
- /**
948
- * Get a challenge record without consuming it.
949
- */
950
- async getChallenge(codeChallenge) {
951
- this.ensureInitialized();
952
- const recordJson = await this.storage.get(codeChallenge);
953
- if (!recordJson) return null;
954
- const record = JSON.parse(recordJson);
955
- if (Date.now() > record.expiresAt) {
956
- await this.storage.delete(codeChallenge);
957
- return null;
958
- }
959
- return record;
960
- }
961
- /**
962
- * Delete a challenge.
963
- */
964
- async deleteChallenge(codeChallenge) {
965
- this.ensureInitialized();
966
- const exists = await this.storage.exists(codeChallenge);
967
- if (exists) {
968
- await this.storage.delete(codeChallenge);
969
- return true;
970
- }
971
- return false;
972
- }
973
- /**
974
- * Close the service.
975
- */
976
- async close() {
977
- if (this.ownedStorage && this.storage) {
978
- await this.storage.root.disconnect();
979
- }
980
- this.initialized = false;
981
- }
982
- };
983
- ChallengeService = __decorateClass([
984
- Provider2({
985
- name: "provider:approval:challenge-service",
986
- description: "PKCE challenge service for webhook approval flows",
987
- scope: ProviderScope2.GLOBAL
988
- })
989
- ], ChallengeService);
990
- function generatePkcePairFromVerifier(codeVerifier) {
991
- return {
992
- codeVerifier,
993
- codeChallenge: generateCodeChallenge(codeVerifier)
994
- };
995
- }
996
- function createMemoryChallengeService(options = {}) {
997
- const memoryStorage = createMemoryStorage();
998
- return new ChallengeService({
999
- ...options,
1000
- storageInstance: memoryStorage
1001
- });
1002
- }
1003
-
1004
- // plugins/plugin-approval/src/stores/approval-storage.store.ts
1005
- import { Provider as Provider3, ProviderScope as ProviderScope3 } from "@frontmcp/sdk";
1006
- import {
1007
- createMemoryStorage as createMemoryStorage2,
1008
- createNamespacedStorage,
1009
- createStorage as createStorage2,
1010
- StorageNotSupportedError
1011
- } from "@frontmcp/utils";
1012
- function escapePattern(str) {
1013
- return str.replace(/[*?[\]\\]/g, "\\$&");
1014
- }
1015
- function isSameRecord(a, b) {
1016
- return a.toolId === b.toolId && a.state === b.state && a.scope === b.scope && a.grantedAt === b.grantedAt && a.sessionId === b.sessionId && a.userId === b.userId && a.context?.type === b.context?.type && a.context?.identifier === b.context?.identifier;
1017
- }
1018
- var REVOCATION_RETENTION_SECONDS = 24 * 60 * 60;
1019
- var TIME_LIMITED_KEY_SEGMENT = `scope:${"time_limited" /* TIME_LIMITED */}`;
1020
- var ApprovalStorageStore = class {
1021
- storage;
1022
- /** Revoked approvals live beside the live ones, in a namespace no live-approval query scans. */
1023
- revocationStorage;
1024
- options;
1025
- cleanupInterval;
1026
- initialized = false;
1027
- ownedStorage = false;
1028
- constructor(options = {}) {
1029
- this.options = {
1030
- storage: options.storage ?? { type: "auto" },
1031
- storageInstance: options.storageInstance,
1032
- namespace: options.namespace ?? "approval",
1033
- cleanupIntervalSeconds: options.cleanupIntervalSeconds ?? 60
1034
- };
1035
- }
1036
- /**
1037
- * Initialize the storage connection.
1038
- */
1039
- async initialize() {
1040
- if (this.initialized) {
1041
- return;
1042
- }
1043
- if (this.options.storageInstance) {
1044
- this.storage = this.options.storageInstance.namespace(this.options.namespace);
1045
- this.ownedStorage = false;
1046
- } else {
1047
- const rootStorage = await createStorage2(this.options.storage);
1048
- this.storage = rootStorage.namespace(this.options.namespace);
1049
- this.ownedStorage = true;
1050
- }
1051
- if (this.options.cleanupIntervalSeconds > 0) {
1052
- this.cleanupInterval = setInterval(() => {
1053
- void this.clearExpiredApprovals();
1054
- }, this.options.cleanupIntervalSeconds * 1e3);
1055
- this.cleanupInterval.unref?.();
1056
- }
1057
- this.initialized = true;
1058
- }
1059
- get revocations() {
1060
- this.revocationStorage ??= createNamespacedStorage(
1061
- this.storage.root,
1062
- `${this.storage.prefix.replace(/:$/, "")}-revoked`
1063
- );
1064
- return this.revocationStorage;
1065
- }
1066
- ensureInitialized() {
1067
- if (!this.initialized) {
1068
- throw new Error("ApprovalStorageStore not initialized. Call initialize() first.");
1069
- }
1070
- }
1071
- buildKey(toolId, sessionId, userId, context) {
1072
- const parts = [toolId];
1073
- if (sessionId) parts.push(`session:${sessionId}`);
1074
- if (userId) parts.push(`user:${userId}`);
1075
- if (context) parts.push(`ctx:${context.type}:${context.identifier}`);
1076
- return parts.join(":");
1077
- }
1078
- /**
1079
- * The key of a time-limited approval granted to a session alone or a user alone. Kept apart from
1080
- * that session's or user's own key, so a time-limited grant never replaces the session or user
1081
- * approval, or a denial recorded there. (With both a session and a user, `buildKey` is already distinct.)
1082
- */
1083
- timeLimitedKey(toolId, sessionId, userId) {
1084
- return `${this.buildKey(toolId, sessionId, userId)}:${TIME_LIMITED_KEY_SEGMENT}`;
1085
- }
1086
- /** The key a new record is stored under. */
1087
- recordKey(options) {
1088
- const { toolId, scope, sessionId, userId, context } = options;
1089
- if (scope === "time_limited" /* TIME_LIMITED */ && !context && !(sessionId && userId)) {
1090
- return this.timeLimitedKey(toolId, sessionId, userId);
1091
- }
1092
- return this.buildKey(toolId, sessionId, userId, context);
1093
- }
1094
- parseRecord(value) {
1095
- if (!value) return void 0;
1096
- try {
1097
- const parsed = JSON.parse(value);
1098
- const result = approvalRecordSchema.safeParse(parsed);
1099
- if (!result.success) {
1100
- return void 0;
1101
- }
1102
- return result.data;
1103
- } catch {
1104
- return void 0;
1105
- }
1106
- }
1107
- isExpired(approval) {
1108
- return approval.expiresAt !== void 0 && Date.now() > approval.expiresAt;
1109
- }
1110
- /**
1111
- * The keys a caller's approvals of a tool can be stored under: its session, its user, both
1112
- * (time-limited and context grants made through `ApprovalService`), the time-limited keys of its
1113
- * session and its user, and, for a call in a server-established context, that context (granted
1114
- * to the session and the user, or to the session before it had a user, the way a session approval
1115
- * stays in force once the caller's user is known). Records written by 1.8.2 sit under the same
1116
- * keys (a time-limited grant without a user under the session key), so they are still read.
1117
- */
1118
- callerKeys(toolId, sessionId, userId, context) {
1119
- const keys = [this.buildKey(toolId, sessionId), this.timeLimitedKey(toolId, sessionId)];
1120
- if (userId) {
1121
- keys.push(
1122
- this.buildKey(toolId, void 0, userId),
1123
- this.timeLimitedKey(toolId, void 0, userId),
1124
- this.buildKey(toolId, sessionId, userId)
1125
- );
1126
- }
1127
- if (context) {
1128
- keys.push(this.buildKey(toolId, sessionId, void 0, context));
1129
- if (userId) keys.push(this.buildKey(toolId, sessionId, userId, context));
1130
- }
1131
- return [...new Set(keys)];
1132
- }
1133
- /**
1134
- * Every unexpired record that applies to this caller: session, user, time-limited and, when
1135
- * `context` is given, context-specific approvals and denials.
1136
- */
1137
- async getApprovals(toolId, sessionId, userId, context) {
1138
- this.ensureInitialized();
1139
- const records = [];
1140
- for (const key of this.callerKeys(toolId, sessionId, userId, context)) {
1141
- const record = this.parseRecord(await this.storage.get(key));
1142
- if (record && record.toolId === toolId && !this.isExpired(record)) {
1143
- records.push(record);
1144
- }
1145
- }
1146
- return records;
1147
- }
1148
- /**
1149
- * The caller's record for a tool; a denial in any of its scopes wins, so an approval in one
1150
- * scope cannot mask a denial in another.
1151
- */
1152
- async getApproval(toolId, sessionId, userId, context) {
1153
- const records = await this.getApprovals(toolId, sessionId, userId, context);
1154
- return records.find((record) => record.state === "denied" /* DENIED */) ?? records[0];
1155
- }
1156
- async queryApprovals(query) {
1157
- this.ensureInitialized();
1158
- const results = [];
1159
- const pattern = query.toolId ? `${escapePattern(query.toolId)}:*` : "*";
1160
- const keys = await this.storage.keys(pattern);
1161
- const values = await this.storage.mget(keys);
1162
- for (const value of values) {
1163
- const approval = this.parseRecord(value);
1164
- if (!approval) continue;
1165
- if (!query.includeExpired && this.isExpired(approval)) {
1166
- continue;
1167
- }
1168
- if (query.toolId && approval.toolId !== query.toolId) continue;
1169
- if (query.toolIds && !query.toolIds.includes(approval.toolId)) continue;
1170
- if (query.scope && approval.scope !== query.scope) continue;
1171
- if (query.scopes && !query.scopes.includes(approval.scope)) continue;
1172
- if (query.state && approval.state !== query.state) continue;
1173
- if (query.states && !query.states.includes(approval.state)) continue;
1174
- if (query.sessionId && approval.sessionId !== query.sessionId) continue;
1175
- if (query.userId && approval.userId !== query.userId) continue;
1176
- if (query.context) {
1177
- if (!approval.context || approval.context.type !== query.context.type || approval.context.identifier !== query.context.identifier) {
1178
- continue;
1179
- }
1180
- }
1181
- results.push(approval);
1182
- }
1183
- return results;
1184
- }
1185
- async grantApproval(options) {
1186
- this.ensureInitialized();
1187
- assertValidTtl(options.ttlMs);
1188
- if (options.scope === "time_limited" /* TIME_LIMITED */ && options.ttlMs === void 0) {
1189
- throw new ApprovalOperationError("grant", "a time-limited approval needs ttlMs");
1190
- }
1191
- const now = Date.now();
1192
- const expiresAt = options.ttlMs !== void 0 ? now + options.ttlMs : void 0;
1193
- const grantedBy = normalizeGrantor(options.grantedBy);
1194
- const record = {
1195
- toolId: options.toolId,
1196
- state: "approved" /* APPROVED */,
1197
- scope: options.scope,
1198
- grantedAt: now,
1199
- expiresAt,
1200
- ttlMs: options.ttlMs,
1201
- sessionId: options.sessionId,
1202
- userId: options.userId,
1203
- context: options.context,
1204
- grantedBy,
1205
- reason: options.reason,
1206
- metadata: options.metadata
1207
- };
1208
- const key = this.recordKey(options);
1209
- const ttlSeconds = options.ttlMs !== void 0 ? Math.ceil(options.ttlMs / 1e3) : void 0;
1210
- await this.storage.set(key, JSON.stringify(record), { ttlSeconds });
1211
- return record;
1212
- }
1213
- /**
1214
- * Deletes the approvals of a tool that belong to the given session or user: with a context, only
1215
- * that context's approval; otherwise every approval of the tool stored for that session or user
1216
- * (session, user, time-limited and context approvals alike). Recorded denials are kept.
1217
- */
1218
- async revokeApproval(options) {
1219
- this.ensureInitialized();
1220
- const { toolId, sessionId, userId, context } = options;
1221
- if (!sessionId && !userId && !context) {
1222
- return false;
1223
- }
1224
- const keys = await this.storage.keys(`${escapePattern(toolId)}:*`);
1225
- const values = await this.storage.mget(keys);
1226
- const keysToDelete = [];
1227
- const revoked = /* @__PURE__ */ new Map();
1228
- for (let i = 0; i < keys.length; i++) {
1229
- const record = this.parseRecord(values[i]);
1230
- if (!record || record.toolId !== toolId || record.state === "denied" /* DENIED */) continue;
1231
- const matches = keysToDelete.length;
1232
- if (context) {
1233
- const sameSession = sessionId !== void 0 && record.sessionId === sessionId;
1234
- if (record.context?.type === context.type && record.context.identifier === context.identifier && (!sessionId || sameSession) && // A context approval granted to the session before it had a user applies to that user too.
1235
- (!userId || record.userId === userId || sameSession && record.userId === void 0)) {
1236
- keysToDelete.push(keys[i]);
1237
- }
1238
- } else if (sessionId && record.sessionId === sessionId || userId && record.userId === userId) {
1239
- keysToDelete.push(keys[i]);
1240
- }
1241
- if (keysToDelete.length > matches) revoked.set(keys[i], record);
1242
- }
1243
- if (keysToDelete.length === 0) {
1244
- return false;
1245
- }
1246
- const revokedAt = Date.now();
1247
- const revokedBy = normalizeRevoker(options.revokedBy);
1248
- for (const [key, record] of revoked) {
1249
- const entry = { ...record, revokedAt, revokedBy, revocationReason: options.reason };
1250
- await this.revocations.set(key, JSON.stringify(entry), { ttlSeconds: REVOCATION_RETENTION_SECONDS });
1251
- }
1252
- await this.storage.mdelete(keysToDelete);
1253
- return true;
1254
- }
1255
- /**
1256
- * Deletes the key that holds `record`, if it still does, and reports whether this call deleted
1257
- * it. Two calls racing for one approval both find it, but only one deletes it, and a denial or
1258
- * approval written to the key after it was read is kept.
1259
- */
1260
- async consumeApproval(record, sessionId, userId, context) {
1261
- this.ensureInitialized();
1262
- for (const key of this.callerKeys(record.toolId, sessionId, userId, context)) {
1263
- const storedValue = await this.storage.get(key);
1264
- const stored = this.parseRecord(storedValue);
1265
- if (storedValue !== null && stored && isSameRecord(stored, record)) {
1266
- return this.deleteIfUnchanged(key, storedValue);
1267
- }
1268
- }
1269
- return false;
1270
- }
1271
- /** Deletes `key` only while it still holds `storedValue`, in one step where the backend allows. */
1272
- async deleteIfUnchanged(key, storedValue) {
1273
- try {
1274
- return await this.storage.deleteIfEquals(key, storedValue);
1275
- } catch (error) {
1276
- if (!(error instanceof StorageNotSupportedError)) throw error;
1277
- return this.storage.delete(key);
1278
- }
1279
- }
1280
- async getRevocations(toolId, sessionId, userId, context) {
1281
- this.ensureInitialized();
1282
- const records = [];
1283
- for (const key of this.callerKeys(toolId, sessionId, userId, context)) {
1284
- const record = this.parseRecord(await this.revocations.get(key));
1285
- if (record && record.toolId === toolId) records.push(record);
1286
- }
1287
- return records.sort((a, b) => (a.revokedAt ?? 0) - (b.revokedAt ?? 0));
1288
- }
1289
- async isApproved(toolId, sessionId, userId, context) {
1290
- const approval = await this.getApproval(toolId, sessionId, userId, context);
1291
- return approval?.state === "approved" /* APPROVED */;
1292
- }
1293
- async clearSessionApprovals(sessionId) {
1294
- this.ensureInitialized();
1295
- const escapedSessionId = escapePattern(sessionId);
1296
- const keys = [
1297
- .../* @__PURE__ */ new Set([
1298
- ...await this.storage.keys(`*:session:${escapedSessionId}`),
1299
- ...await this.storage.keys(`*:session:${escapedSessionId}:*`)
1300
- ])
1301
- ];
1302
- if (keys.length === 0) {
1303
- return 0;
1304
- }
1305
- return await this.storage.mdelete(keys);
1306
- }
1307
- async clearExpiredApprovals() {
1308
- this.ensureInitialized();
1309
- const now = Date.now();
1310
- const keys = await this.storage.keys("*");
1311
- const values = await this.storage.mget(keys);
1312
- const keysToDelete = [];
1313
- for (let i = 0; i < keys.length; i++) {
1314
- const approval = this.parseRecord(values[i]);
1315
- if (approval && approval.expiresAt && approval.expiresAt <= now) {
1316
- keysToDelete.push(keys[i]);
1317
- }
1318
- }
1319
- if (keysToDelete.length > 0) {
1320
- return await this.storage.mdelete(keysToDelete);
1321
- }
1322
- return 0;
1323
- }
1324
- async getStats() {
1325
- this.ensureInitialized();
1326
- const byScope = {
1327
- ["session" /* SESSION */]: 0,
1328
- ["user" /* USER */]: 0,
1329
- ["time_limited" /* TIME_LIMITED */]: 0,
1330
- ["tool_specific" /* TOOL_SPECIFIC */]: 0,
1331
- ["context_specific" /* CONTEXT_SPECIFIC */]: 0
1332
- };
1333
- const byState = {
1334
- ["pending" /* PENDING */]: 0,
1335
- ["approved" /* APPROVED */]: 0,
1336
- ["denied" /* DENIED */]: 0,
1337
- ["expired" /* EXPIRED */]: 0
1338
- };
1339
- const keys = await this.storage.keys("*");
1340
- const values = await this.storage.mget(keys);
1341
- let total = 0;
1342
- for (const value of values) {
1343
- const approval = this.parseRecord(value);
1344
- if (approval) {
1345
- total++;
1346
- byScope[approval.scope]++;
1347
- byState[approval.state]++;
1348
- }
1349
- }
1350
- return {
1351
- totalApprovals: total,
1352
- byScope,
1353
- byState
1354
- };
1355
- }
1356
- async close() {
1357
- if (this.cleanupInterval) {
1358
- clearInterval(this.cleanupInterval);
1359
- this.cleanupInterval = void 0;
1360
- }
1361
- if (this.ownedStorage && this.storage) {
1362
- await this.storage.root.disconnect();
1363
- }
1364
- this.revocationStorage = void 0;
1365
- this.initialized = false;
1366
- }
1367
- };
1368
- ApprovalStorageStore = __decorateClass([
1369
- Provider3({
1370
- name: "provider:approval:store:storage",
1371
- description: "Storage-backed approval store (supports Memory, Redis, Vercel KV, Upstash)",
1372
- scope: ProviderScope3.GLOBAL
1373
- })
1374
- ], ApprovalStorageStore);
1375
- function createApprovalMemoryStore(options = {}) {
1376
- const memoryStorage = createMemoryStorage2();
1377
- return new ApprovalStorageStore({
1378
- ...options,
1379
- storageInstance: memoryStorage
1380
- });
1381
- }
1382
-
1383
- // plugins/plugin-approval/src/approval.plugin.ts
1384
- var ApprovalPlugin = class extends DynamicPlugin2 {
1385
- options;
1386
- constructor(options = {}) {
1387
- super();
1388
- this.options = {
1389
- ...ApprovalPlugin.defaultOptions,
1390
- ...options
1391
- };
1392
- }
1393
- };
1394
- __publicField(ApprovalPlugin, "defaultOptions", {
1395
- namespace: "approval",
1396
- mode: "recheck",
1397
- enableAudit: true,
1398
- maxDelegationDepth: 3,
1399
- cleanupIntervalSeconds: 60
1400
- });
1401
- /**
1402
- * Dynamic providers based on plugin options.
1403
- */
1404
- __publicField(ApprovalPlugin, "dynamicProviders", (options) => {
1405
- const providers = [];
1406
- const config = {
1407
- ...ApprovalPlugin.defaultOptions,
1408
- ...options
1409
- };
1410
- providers.push({
1411
- name: "approval:store",
1412
- provide: ApprovalStoreToken,
1413
- inject: () => [],
1414
- useFactory: async () => {
1415
- const store = new ApprovalStorageStore({
1416
- storage: config.storage,
1417
- storageInstance: config.storageInstance,
1418
- namespace: config.namespace,
1419
- cleanupIntervalSeconds: config.cleanupIntervalSeconds
1420
- });
1421
- await store.initialize();
1422
- return store;
1423
- }
1424
- });
1425
- if (config.mode === "webhook") {
1426
- providers.push({
1427
- name: "approval:challenge-service",
1428
- provide: ChallengeServiceToken,
1429
- inject: () => [],
1430
- useFactory: async () => {
1431
- const service = new ChallengeService({
1432
- storage: config.storage,
1433
- storageInstance: config.storageInstance,
1434
- namespace: `${config.namespace}:challenge`,
1435
- defaultTtlSeconds: config.webhook?.challengeTtl ?? 300
1436
- });
1437
- await service.initialize();
1438
- return service;
1439
- }
1440
- });
1441
- }
1442
- providers.push({
1443
- name: "approval:service",
1444
- provide: ApprovalServiceToken,
1445
- scope: ProviderScope4.CONTEXT,
1446
- inject: () => [ApprovalStoreToken, FRONTMCP_CONTEXT, ScopeEntry2],
1447
- useFactory: (store, ctx, scope) => {
1448
- const { sessionId, userId } = resolveApprovalIdentity(ctx);
1449
- const requirementOf = (toolId) => {
1450
- const tool = scope.tools.getTools(true).find((entry) => entry.fullName === toolId);
1451
- if (!tool) return void 0;
1452
- const approval = tool.metadata.approval;
1453
- return resolveApprovalRequirement(approval);
1454
- };
1455
- return createApprovalService(store, sessionId, userId, requirementOf);
1456
- }
1457
- });
1458
- return providers;
1459
- });
1460
- ApprovalPlugin = __decorateClass([
1461
- Plugin2({
1462
- name: "approval",
1463
- description: "Tool authorization workflow with PKCE webhook security",
1464
- plugins: [ApprovalCheckPlugin],
1465
- contextExtensions: [
1466
- {
1467
- property: "approval",
1468
- token: ApprovalServiceToken,
1469
- errorMessage: "ApprovalPlugin is not installed. Add ApprovalPlugin.init() to your plugins array."
1470
- }
1471
- ]
1472
- })
1473
- ], ApprovalPlugin);
1474
-
1475
- // plugins/plugin-approval/src/approval.context-extension.ts
1476
- var installed = false;
1477
- function installApprovalContextExtension() {
1478
- if (installed) return;
1479
- const { ExecutionContextBase } = __require("@frontmcp/sdk");
1480
- Object.defineProperty(ExecutionContextBase.prototype, "approval", {
1481
- get: function() {
1482
- return this.get(ApprovalServiceToken);
1483
- },
1484
- configurable: true,
1485
- enumerable: false
1486
- });
1487
- installed = true;
1488
- }
1489
- export {
1490
- ApprovalCheckPlugin,
1491
- ApprovalError,
1492
- ApprovalExpiredError,
1493
- ApprovalOperationError,
1494
- ApprovalPlugin,
1495
- ApprovalPlugin as ApprovalPluginClass,
1496
- ApprovalRequiredError,
1497
- ApprovalScope,
1498
- ApprovalScopeNotAllowedError,
1499
- ApprovalService,
1500
- ApprovalServiceToken,
1501
- ApprovalState,
1502
- ApprovalStorageStore,
1503
- ApprovalStoreToken,
1504
- ChallengeService,
1505
- ChallengeServiceToken,
1506
- ChallengeValidationError,
1507
- adminGrantor,
1508
- adminRevoker,
1509
- agentGrantor,
1510
- apiGrantor,
1511
- createApprovalMemoryStore,
1512
- createApprovalService,
1513
- createMemoryChallengeService,
1514
- customGrantor,
1515
- expiryRevoker,
1516
- installApprovalContextExtension,
1517
- isApiGrantor,
1518
- isAutoGrantor,
1519
- isDelegatedGrantor,
1520
- isGrantorSource,
1521
- isHumanGrantor,
1522
- normalizeGrantor,
1523
- normalizeRevoker,
1524
- oauthGrantor,
1525
- policyGrantor,
1526
- policyRevoker,
1527
- sessionEndRevoker,
1528
- systemGrantor,
1529
- testGrantor,
1530
- userGrantor,
1531
- userRevoker
1532
- };
4
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);import{DynamicPlugin as DynamicPlugin2,FRONTMCP_CONTEXT,Plugin as Plugin2,ProviderScope as ProviderScope4,ScopeEntry as ScopeEntry2}from"@frontmcp/sdk";import{randomUUID}from"@frontmcp/utils";function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function resolveApprovalIdentity(ctx){const extra=ctx?.authInfo?.extra;const userId=nonEmptyString(extra?.["userId"])??nonEmptyString(extra?.["sub"])??nonEmptyString(ctx?.authInfo?.clientId);const sessionId=nonEmptyString(ctx?.verifiedSessionId);if(sessionId){return{sessionId,userId}}return{sessionId:userId?`stateless-user:${userId}`:`unidentified:${randomUUID()}`,userId}}var ApprovalStoreToken=Symbol.for("plugin:approval:store");var ApprovalServiceToken=Symbol.for("plugin:approval:service");var ChallengeServiceToken=Symbol.for("plugin:approval:challenge-service");import{PublicMcpError}from"@frontmcp/sdk";var ApprovalError=class extends PublicMcpError{constructor(message,code="APPROVAL_REQUIRED",statusCode=403){super(message,code,statusCode);this.name="ApprovalError"}};var ApprovalRequiredError=class extends ApprovalError{constructor(details){super(details.message);this.details=details;this.name="ApprovalRequiredError"}details;toJsonRpcError(){return{code:-32600,message:this.details.message,data:{type:"approval_required",toolId:this.details.toolId,state:this.details.state,options:this.details.approvalOptions}}}};var ApprovalOperationError=class extends ApprovalError{constructor(operation,reason){super(`Approval ${operation} failed: ${reason}`,"APPROVAL_OPERATION_FAILED",400);this.operation=operation;this.reason=reason;this.name="ApprovalOperationError"}operation;reason;toJsonRpcError(){return{code:-32603,message:"Approval operation failed",data:{type:"approval_operation_error",operation:this.operation}}}};var ApprovalScopeNotAllowedError=class extends ApprovalError{constructor(requestedScope,allowedScopes){super(`Approval scope '${requestedScope}' is not allowed for this tool. Allowed scopes: ${allowedScopes.join(", ")}`,"APPROVAL_SCOPE_NOT_ALLOWED",400);this.requestedScope=requestedScope;this.allowedScopes=allowedScopes;this.name="ApprovalScopeNotAllowedError"}requestedScope;allowedScopes;toJsonRpcError(){return{code:-32602,message:this.message,data:{type:"approval_scope_not_allowed",requestedScope:this.requestedScope,allowedScopes:this.allowedScopes}}}};var ApprovalExpiredError=class extends ApprovalError{constructor(toolId,expiredAt){super(`Approval for tool '${toolId}' expired at ${new Date(expiredAt).toISOString()}`,"APPROVAL_EXPIRED",403);this.toolId=toolId;this.expiredAt=expiredAt;this.name="ApprovalExpiredError"}toolId;expiredAt;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"approval_expired",toolId:this.toolId,expiredAt:this.expiredAt}}}};var ChallengeValidationError=class extends ApprovalError{constructor(reason="invalid",message){super(message??`PKCE challenge validation failed: ${reason}`,"CHALLENGE_VALIDATION_FAILED",400);this.reason=reason;this.name="ChallengeValidationError"}reason;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"challenge_validation_error",reason:this.reason}}}};var ApprovalScope=(ApprovalScope2=>{ApprovalScope2["SESSION"]="session";ApprovalScope2["USER"]="user";ApprovalScope2["TIME_LIMITED"]="time_limited";ApprovalScope2["TOOL_SPECIFIC"]="tool_specific";ApprovalScope2["CONTEXT_SPECIFIC"]="context_specific";return ApprovalScope2})(ApprovalScope||{});var ApprovalState=(ApprovalState2=>{ApprovalState2["PENDING"]="pending";ApprovalState2["APPROVED"]="approved";ApprovalState2["DENIED"]="denied";ApprovalState2["EXPIRED"]="expired";return ApprovalState2})(ApprovalState||{});function resolveApprovalRequirement(config){if(config===true){return{required:true,defaultScope:"session"}}if(config===false||config===void 0){return{required:false}}return{...config,required:config.required??true,defaultScope:config.defaultScope??"session"}}function effectiveExpiresAt(record,requirement){const capped=requirement.maxTtlMs!==void 0?record.grantedAt+requirement.maxTtlMs:void 0;if(record.expiresAt===void 0)return capped;return capped===void 0?record.expiresAt:Math.min(record.expiresAt,capped)}function isApprovalExpired(record,requirement,now){const expiresAt=effectiveExpiresAt(record,requirement);return expiresAt!==void 0&&now>expiresAt}function isApprovalUsable(record,requirement,now){if(record.state!=="approved")return false;if(requirement.allowedScopes?.length&&!requirement.allowedScopes.includes(record.scope))return false;return!isApprovalExpired(record,requirement,now)}function assertValidTtl(ttlMs){if(ttlMs===void 0)return;if(!Number.isFinite(ttlMs)||ttlMs<=0){throw new ApprovalOperationError("grant",`ttlMs must be a positive number of milliseconds, got ${ttlMs}`)}}function checkGrantAgainstPolicy(toolId,scope,ttlMs,requirement){assertValidTtl(ttlMs);if(!requirement)return ttlMs;if(requirement.allowedScopes?.length&&!requirement.allowedScopes.includes(scope)){throw new ApprovalScopeNotAllowedError(scope,requirement.allowedScopes)}const{maxTtlMs}=requirement;if(maxTtlMs===void 0)return ttlMs;if(ttlMs===void 0)return maxTtlMs;if(ttlMs>maxTtlMs){throw new ApprovalOperationError("grant",`ttlMs ${ttlMs} exceeds the maximum of ${maxTtlMs} ms that tool "${toolId}" allows`)}return ttlMs}import{DynamicPlugin,isEntryGatedBy,Plugin,ScopeEntry,ToolHook}from"@frontmcp/sdk";import{z}from"@frontmcp/lazy-zod";var approvalScopeSchema=z.nativeEnum(ApprovalScope);var approvalStateSchema=z.nativeEnum(ApprovalState);var approvalMethodSchema=z.enum(["interactive","implicit","delegation","batch","api"]);var approvalSourceTypeSchema=z.string().min(1);var revocationMethodSchema=z.enum(["interactive","implicit","policy","expiry"]);var approvalCategorySchema=z.enum(["read","write","delete","execute","admin"]);var riskLevelSchema=z.enum(["low","medium","high","critical"]);var approvalContextSchema=z.object({type:z.string().min(1),identifier:z.string().min(1),metadata:z.record(z.string(),z.unknown()).optional()});var delegationContextSchema=z.object({delegatorId:z.string().min(1),delegateId:z.string().min(1),purpose:z.string().optional(),constraints:z.record(z.string(),z.unknown()).optional()});var approvalGrantorSchema=z.object({source:approvalSourceTypeSchema,identifier:z.string().optional(),displayName:z.string().optional(),method:approvalMethodSchema.optional(),origin:z.string().optional(),delegationContext:delegationContextSchema.optional()});var approvalRevokerSchema=z.object({source:z.string().min(1),identifier:z.string().optional(),displayName:z.string().optional(),method:revocationMethodSchema.optional()});var approvalRecordSchema=z.object({toolId:z.string().min(1),state:approvalStateSchema,scope:approvalScopeSchema,grantedAt:z.number(),expiresAt:z.number().optional(),ttlMs:z.number().optional(),sessionId:z.string().optional(),userId:z.string().optional(),context:approvalContextSchema.optional(),grantedBy:approvalGrantorSchema,approvalChain:z.array(approvalGrantorSchema).optional(),reason:z.string().optional(),metadata:z.record(z.string(),z.unknown()).optional(),revokedAt:z.number().optional(),revokedBy:approvalRevokerSchema.optional(),revocationReason:z.string().optional()});var toolApprovalRequirementSchema=z.object({required:z.boolean().optional(),defaultScope:approvalScopeSchema.optional(),allowedScopes:z.array(approvalScopeSchema).optional(),maxTtlMs:z.number().positive().optional(),alwaysPrompt:z.boolean().optional(),skipApproval:z.boolean().optional(),approvalMessage:z.string().optional(),category:approvalCategorySchema.optional(),riskLevel:riskLevelSchema.optional(),preApprovedContexts:z.array(approvalContextSchema).optional()});function userGrantor(userId,displayName,options){return{source:"user",identifier:userId,displayName,method:options?.method??"interactive",origin:options?.origin}}function policyGrantor(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"implicit"}}function adminGrantor(adminId,displayName,options){return{source:"admin",identifier:adminId,displayName,method:options?.method??"interactive",origin:options?.origin}}function systemGrantor(systemId="system"){return{source:"system",identifier:systemId,method:"implicit"}}function agentGrantor(agentId,delegationContext,displayName){return{source:"agent",identifier:agentId,displayName,method:"delegation",delegationContext}}function apiGrantor(apiKeyPrefix,serviceName){return{source:"api",identifier:apiKeyPrefix,displayName:serviceName,method:"api",origin:"api"}}function oauthGrantor(tokenId,provider){return{source:"oauth",identifier:tokenId,displayName:provider,method:"api",origin:"oauth"}}function testGrantor(){return{source:"test",identifier:"test",method:"implicit"}}function customGrantor(source,identifier,options){return{source,identifier,displayName:options?.displayName,method:options?.method,origin:options?.origin,delegationContext:options?.delegationContext}}function userRevoker(userId,displayName){return{source:"user",identifier:userId,displayName,method:"interactive"}}function adminRevoker(adminId,displayName){return{source:"admin",identifier:adminId,displayName,method:"interactive"}}function expiryRevoker(){return{source:"expiry",method:"expiry"}}function sessionEndRevoker(sessionId){return{source:"session_end",identifier:sessionId,method:"implicit"}}function policyRevoker(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"policy"}}function normalizeGrantor(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function normalizeRevoker(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function isGrantorSource(grantor,source){return grantor.source===source}function isHumanGrantor(grantor){return grantor.source==="user"||grantor.source==="admin"}function isAutoGrantor(grantor){return grantor.source==="policy"||grantor.source==="system"||grantor.source==="test"}function isDelegatedGrantor(grantor){return grantor.source==="agent"&&!!grantor.delegationContext}function isApiGrantor(grantor){return grantor.source==="api"||grantor.source==="oauth"}var decidedCalls=new WeakSet;var ApprovalCheckPlugin=class extends DynamicPlugin{async checkApproval(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;const metadata=tool.metadata;const approvalConfig=resolveApprovalRequirement(metadata["approval"]);if(!approvalConfig.required){return}if(approvalConfig.skipApproval){return}if(decidedCalls.has(toolContext))return;await this.enforceApproval(flowCtx,tool,toolContext,approvalConfig,this.coveringStores(tool));decidedCalls.add(toolContext)}async enforceApproval(flowCtx,tool,toolContext,approvalConfig,stores){const{sessionId,userId}=resolveApprovalIdentity(toolContext.tryGetContext?.());const currentContext=this.getCurrentContext(flowCtx);const stored=[];for(const store of stores){const records2=await this.readApprovals(store,tool.fullName,sessionId,userId,currentContext);stored.push(...records2.map(record=>({store,record})))}const records=stored.map(({record})=>record);if(records.some(record=>record.state==="denied")){throw new ApprovalRequiredError({toolId:tool.fullName,state:"denied",message:`Tool "${tool.fullName}" execution denied.`})}if(!approvalConfig.alwaysPrompt&&this.isPreApprovedContext(approvalConfig,currentContext)){return}const approved=records.filter(record=>record.state==="approved");const now=Date.now();const usable=stored.filter(({record})=>isApprovalUsable(record,approvalConfig,now));if(approvalConfig.alwaysPrompt){for(const{store,record}of usable){if(await this.consumeApproval(store,record,sessionId,userId,currentContext))return}}else if(usable.length>0){return}await this.handleApprovalRequired(flowCtx,approvalConfig,approved.find(record=>isApprovalExpired(record,approvalConfig,now))??approved[0])}coveringStores(tool){const stores=new Set([this.get(ApprovalStoreToken)]);let scope;try{scope=this.get(ScopeEntry)}catch{scope=void 0}if(!scope?.hooks)return[...stores];for(const hook of scope.hooks.getFlowHooks("tools:call-tool")){const gate=hook.metadata.target;if(gate instanceof ApprovalCheckPlugin&&isEntryGatedBy(scope,{tool},gate)){stores.add(gate.get(ApprovalStoreToken))}}return[...stores]}async consumeApproval(store,record,sessionId,userId,context){if(store.consumeApproval){return store.consumeApproval(record,sessionId,userId,context)}return store.revokeApproval({toolId:record.toolId,sessionId,userId,revokedBy:"system",reason:"Used by a call of an alwaysPrompt tool"})}async readApprovals(store,toolId,sessionId,userId,context){if(store.getApprovals){return store.getApprovals(toolId,sessionId,userId,context)}const record=await store.getApproval(toolId,sessionId,userId,context);return record?[record]:[]}getCurrentContext(flowCtx){const ctx=flowCtx.state.toolContext?.tryGetContext?.();const sessionContext=ctx?.authInfo?.extra?.["approvalContext"];return this.isApprovalContext(sessionContext)?sessionContext:void 0}isApprovalContext(value){return typeof value==="object"&&value!==null&&"type"in value&&"identifier"in value&&typeof value.type==="string"&&typeof value.identifier==="string"}isPreApprovedContext(config,currentContext){if(!currentContext||!config.preApprovedContexts?.length){return false}return config.preApprovedContexts.some(preApproved=>preApproved.type===currentContext.type&&preApproved.identifier===currentContext.identifier)}async handleApprovalRequired(flowCtx,config,existingApproval){const{tool}=flowCtx.state;const message=config.approvalMessage??`Tool "${tool?.fullName}" requires approval to execute. Allow?`;const isExpiredApproval=existingApproval?isApprovalExpired(existingApproval,config,Date.now()):false;throw new ApprovalRequiredError({toolId:tool?.fullName??"unknown",state:isExpiredApproval?"expired":"pending",message,approvalOptions:{allowedScopes:config.allowedScopes,defaultScope:config.defaultScope,maxTtlMs:config.maxTtlMs,category:config.category,riskLevel:config.riskLevel}})}};__decorateClass([ToolHook.Will("execute",{priority:100,appliesTo:"uncovered-apps"})],ApprovalCheckPlugin.prototype,"checkApproval",1);ApprovalCheckPlugin=__decorateClass([Plugin({name:"approval:check",description:"Checks tool approval state before execution",enforcesMetadata:["approval"]})],ApprovalCheckPlugin);import{isAnonymousSubject,Provider,ProviderScope}from"@frontmcp/sdk";var ApprovalService=class{constructor(store,sessionId,userId,requirementOf=()=>void 0){this.store=store;this.sessionId=sessionId;this.userId=userId;this.requirementOf=requirementOf}store;sessionId;userId;requirementOf;checkGrant(toolId,scope,ttlMs){return checkGrantAgainstPolicy(toolId,scope,ttlMs,this.requirementOf(toolId))}get signedInUserId(){return this.userId&&!isAnonymousSubject(this.userId)?this.userId:void 0}defaultGrantor(){const userId=this.signedInUserId;return userId?userGrantor(userId,void 0,{method:"implicit"}):{source:"user",method:"implicit"}}defaultRevoker(){const userId=this.signedInUserId;return userId?{source:"user",identifier:userId,method:"implicit"}:{source:"user",method:"implicit"}}async isApproved(toolId,context){const requirement=this.requirementOf(toolId);if(!requirement||!this.store.getApprovals){return this.store.isApproved(toolId,this.sessionId,this.userId,context)}const records=await this.store.getApprovals(toolId,this.sessionId,this.userId,context);if(records.some(record=>record.state==="denied"))return false;const now=Date.now();return records.some(record=>isApprovalUsable(record,requirement,now))}async getApproval(toolId){return this.store.getApproval(toolId,this.sessionId,this.userId)}async getSessionApprovals(){return this.store.queryApprovals({sessionId:this.sessionId,states:["approved"],includeExpired:false})}async getUserApprovals(){if(!this.userId)return[];return this.store.queryApprovals({userId:this.userId,scope:"user",states:["approved"],includeExpired:false})}async queryApprovals(query){const records=await this.store.queryApprovals(query);return records.filter(record=>record.sessionId===this.sessionId||this.userId!==void 0&&record.userId===this.userId)}async getRevocations(toolId){return await this.store.getRevocations?.(toolId,this.sessionId,this.userId)??[]}async grantSessionApproval(toolId,options={}){const ttlMs=this.checkGrant(toolId,"session");return this.store.grantApproval({toolId,scope:"session",ttlMs,sessionId:this.sessionId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantUserApproval(toolId,options={}){if(!this.userId){throw new Error("Cannot grant user approval without userId")}const ttlMs=this.checkGrant(toolId,"user");return this.store.grantApproval({toolId,scope:"user",ttlMs,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantTimeLimitedApproval(toolId,ttlMs,options={}){this.checkGrant(toolId,"time_limited",ttlMs);return this.store.grantApproval({toolId,scope:"time_limited",ttlMs,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantContextApproval(toolId,context,options={}){const ttlMs=this.checkGrant(toolId,"context_specific");return this.store.grantApproval({toolId,scope:"context_specific",ttlMs,context,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async revokeApproval(toolId,options={}){return this.store.revokeApproval({toolId,sessionId:this.sessionId,userId:this.userId,revokedBy:options.revokedBy??this.defaultRevoker(),reason:options.reason})}async clearSessionApprovals(){return this.store.clearSessionApprovals(this.sessionId)}};ApprovalService=__decorateClass([Provider({name:"provider:approval:service",description:"Service for managing tool approvals",scope:ProviderScope.CONTEXT})],ApprovalService);function createApprovalService(store,sessionId,userId,requirementOf){return new ApprovalService(store,sessionId,userId,requirementOf)}import{Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";import{generatePkcePair,generateCodeChallenge,createStorage,createMemoryStorage}from"@frontmcp/utils";var ChallengeService=class{storage;options;initialized=false;ownedStorage=false;constructor(options={}){this.options={storage:options.storage??{type:"auto"},storageInstance:options.storageInstance,namespace:options.namespace??"approval:challenge",defaultTtlSeconds:options.defaultTtlSeconds??300}}async initialize(){if(this.initialized)return;if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await createStorage(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}this.initialized=true}ensureInitialized(){if(!this.initialized){throw new Error("ChallengeService not initialized. Call initialize() first.")}}async createChallenge(options){this.ensureInitialized();const{codeVerifier,codeChallenge}=generatePkcePair();const now=Date.now();const ttlSeconds=options.ttlSeconds??this.options.defaultTtlSeconds;const expiresAt=now+ttlSeconds*1e3;const record={toolId:options.toolId,sessionId:options.sessionId,userId:options.userId,requestedScope:options.requestedScope,requestInfo:options.requestInfo,createdAt:now,expiresAt,webhookSent:false};await this.storage.set(codeChallenge,JSON.stringify(record),{ttlSeconds});return{codeVerifier,codeChallenge,expiresAt}}async verifyAndConsume(codeVerifier){this.ensureInitialized();const{codeChallenge}=generatePkcePairFromVerifier(codeVerifier);const recordJson=await this.storage.get(codeChallenge);if(!recordJson){throw new ChallengeValidationError("not_found","Invalid or expired challenge")}const record=JSON.parse(recordJson);if(Date.now()>record.expiresAt){await this.storage.delete(codeChallenge);throw new ChallengeValidationError("expired","Challenge expired")}await this.storage.delete(codeChallenge);return record}async markWebhookSent(codeChallenge){this.ensureInitialized();const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return false;const record=JSON.parse(recordJson);record.webhookSent=true;const remainingMs=record.expiresAt-Date.now();if(remainingMs<=0){await this.storage.delete(codeChallenge);return false}const ttlSeconds=Math.ceil(remainingMs/1e3);await this.storage.set(codeChallenge,JSON.stringify(record),{ttlSeconds});return true}async getChallenge(codeChallenge){this.ensureInitialized();const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return null;const record=JSON.parse(recordJson);if(Date.now()>record.expiresAt){await this.storage.delete(codeChallenge);return null}return record}async deleteChallenge(codeChallenge){this.ensureInitialized();const exists=await this.storage.exists(codeChallenge);if(exists){await this.storage.delete(codeChallenge);return true}return false}async close(){if(this.ownedStorage&&this.storage){await this.storage.root.disconnect()}this.initialized=false}};ChallengeService=__decorateClass([Provider2({name:"provider:approval:challenge-service",description:"PKCE challenge service for webhook approval flows",scope:ProviderScope2.GLOBAL})],ChallengeService);function generatePkcePairFromVerifier(codeVerifier){return{codeVerifier,codeChallenge:generateCodeChallenge(codeVerifier)}}function createMemoryChallengeService(options={}){const memoryStorage=createMemoryStorage();return new ChallengeService({...options,storageInstance:memoryStorage})}import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{createMemoryStorage as createMemoryStorage2,createNamespacedStorage,createStorage as createStorage2,StorageNotSupportedError}from"@frontmcp/utils";function escapePattern(str){return str.replace(/[*?[\]\\]/g,"\\$&")}function isSameRecord(a,b){return a.toolId===b.toolId&&a.state===b.state&&a.scope===b.scope&&a.grantedAt===b.grantedAt&&a.sessionId===b.sessionId&&a.userId===b.userId&&a.context?.type===b.context?.type&&a.context?.identifier===b.context?.identifier}var REVOCATION_RETENTION_SECONDS=24*60*60;var TIME_LIMITED_KEY_SEGMENT=`scope:${"time_limited"}`;var ApprovalStorageStore=class{storage;revocationStorage;options;cleanupInterval;initialized=false;ownedStorage=false;constructor(options={}){this.options={storage:options.storage??{type:"auto"},storageInstance:options.storageInstance,namespace:options.namespace??"approval",cleanupIntervalSeconds:options.cleanupIntervalSeconds??60}}async initialize(){if(this.initialized){return}if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await createStorage2(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}if(this.options.cleanupIntervalSeconds>0){this.cleanupInterval=setInterval(()=>{void this.clearExpiredApprovals()},this.options.cleanupIntervalSeconds*1e3);this.cleanupInterval.unref?.()}this.initialized=true}get revocations(){this.revocationStorage??=createNamespacedStorage(this.storage.root,`${this.storage.prefix.replace(/:$/,"")}-revoked`);return this.revocationStorage}ensureInitialized(){if(!this.initialized){throw new Error("ApprovalStorageStore not initialized. Call initialize() first.")}}buildKey(toolId,sessionId,userId,context){const parts=[toolId];if(sessionId)parts.push(`session:${sessionId}`);if(userId)parts.push(`user:${userId}`);if(context)parts.push(`ctx:${context.type}:${context.identifier}`);return parts.join(":")}timeLimitedKey(toolId,sessionId,userId){return`${this.buildKey(toolId,sessionId,userId)}:${TIME_LIMITED_KEY_SEGMENT}`}recordKey(options){const{toolId,scope,sessionId,userId,context}=options;if(scope==="time_limited"&&!context&&!(sessionId&&userId)){return this.timeLimitedKey(toolId,sessionId,userId)}return this.buildKey(toolId,sessionId,userId,context)}parseRecord(value){if(!value)return void 0;try{const parsed=JSON.parse(value);const result=approvalRecordSchema.safeParse(parsed);if(!result.success){return void 0}return result.data}catch{return void 0}}isExpired(approval){return approval.expiresAt!==void 0&&Date.now()>approval.expiresAt}callerKeys(toolId,sessionId,userId,context){const keys=[this.buildKey(toolId,sessionId),this.timeLimitedKey(toolId,sessionId)];if(userId){keys.push(this.buildKey(toolId,void 0,userId),this.timeLimitedKey(toolId,void 0,userId),this.buildKey(toolId,sessionId,userId))}if(context){keys.push(this.buildKey(toolId,sessionId,void 0,context));if(userId)keys.push(this.buildKey(toolId,sessionId,userId,context))}return[...new Set(keys)]}async getApprovals(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const key of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.storage.get(key));if(record&&record.toolId===toolId&&!this.isExpired(record)){records.push(record)}}return records}async getApproval(toolId,sessionId,userId,context){const records=await this.getApprovals(toolId,sessionId,userId,context);return records.find(record=>record.state==="denied")??records[0]}async queryApprovals(query){this.ensureInitialized();const results=[];const pattern=query.toolId?`${escapePattern(query.toolId)}:*`:"*";const keys=await this.storage.keys(pattern);const values=await this.storage.mget(keys);for(const value of values){const approval=this.parseRecord(value);if(!approval)continue;if(!query.includeExpired&&this.isExpired(approval)){continue}if(query.toolId&&approval.toolId!==query.toolId)continue;if(query.toolIds&&!query.toolIds.includes(approval.toolId))continue;if(query.scope&&approval.scope!==query.scope)continue;if(query.scopes&&!query.scopes.includes(approval.scope))continue;if(query.state&&approval.state!==query.state)continue;if(query.states&&!query.states.includes(approval.state))continue;if(query.sessionId&&approval.sessionId!==query.sessionId)continue;if(query.userId&&approval.userId!==query.userId)continue;if(query.context){if(!approval.context||approval.context.type!==query.context.type||approval.context.identifier!==query.context.identifier){continue}}results.push(approval)}return results}async grantApproval(options){this.ensureInitialized();assertValidTtl(options.ttlMs);if(options.scope==="time_limited"&&options.ttlMs===void 0){throw new ApprovalOperationError("grant","a time-limited approval needs ttlMs")}const now=Date.now();const expiresAt=options.ttlMs!==void 0?now+options.ttlMs:void 0;const grantedBy=normalizeGrantor(options.grantedBy);const record={toolId:options.toolId,state:"approved",scope:options.scope,grantedAt:now,expiresAt,ttlMs:options.ttlMs,sessionId:options.sessionId,userId:options.userId,context:options.context,grantedBy,reason:options.reason,metadata:options.metadata};const key=this.recordKey(options);const ttlSeconds=options.ttlMs!==void 0?Math.ceil(options.ttlMs/1e3):void 0;await this.storage.set(key,JSON.stringify(record),{ttlSeconds});return record}async revokeApproval(options){this.ensureInitialized();const{toolId,sessionId,userId,context}=options;if(!sessionId&&!userId&&!context){return false}const keys=await this.storage.keys(`${escapePattern(toolId)}:*`);const values=await this.storage.mget(keys);const keysToDelete=[];const revoked=new Map;for(let i=0;i<keys.length;i++){const record=this.parseRecord(values[i]);if(!record||record.toolId!==toolId||record.state==="denied")continue;const matches=keysToDelete.length;if(context){const sameSession=sessionId!==void 0&&record.sessionId===sessionId;if(record.context?.type===context.type&&record.context.identifier===context.identifier&&(!sessionId||sameSession)&&(!userId||record.userId===userId||sameSession&&record.userId===void 0)){keysToDelete.push(keys[i])}}else if(sessionId&&record.sessionId===sessionId||userId&&record.userId===userId){keysToDelete.push(keys[i])}if(keysToDelete.length>matches)revoked.set(keys[i],record)}if(keysToDelete.length===0){return false}const revokedAt=Date.now();const revokedBy=normalizeRevoker(options.revokedBy);for(const[key,record]of revoked){const entry={...record,revokedAt,revokedBy,revocationReason:options.reason};await this.revocations.set(key,JSON.stringify(entry),{ttlSeconds:REVOCATION_RETENTION_SECONDS})}await this.storage.mdelete(keysToDelete);return true}async consumeApproval(record,sessionId,userId,context){this.ensureInitialized();for(const key of this.callerKeys(record.toolId,sessionId,userId,context)){const storedValue=await this.storage.get(key);const stored=this.parseRecord(storedValue);if(storedValue!==null&&stored&&isSameRecord(stored,record)){return this.deleteIfUnchanged(key,storedValue)}}return false}async deleteIfUnchanged(key,storedValue){try{return await this.storage.deleteIfEquals(key,storedValue)}catch(error){if(!(error instanceof StorageNotSupportedError))throw error;return this.storage.delete(key)}}async getRevocations(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const key of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.revocations.get(key));if(record&&record.toolId===toolId)records.push(record)}return records.sort((a,b)=>(a.revokedAt??0)-(b.revokedAt??0))}async isApproved(toolId,sessionId,userId,context){const approval=await this.getApproval(toolId,sessionId,userId,context);return approval?.state==="approved"}async clearSessionApprovals(sessionId){this.ensureInitialized();const escapedSessionId=escapePattern(sessionId);const keys=[...new Set([...await this.storage.keys(`*:session:${escapedSessionId}`),...await this.storage.keys(`*:session:${escapedSessionId}:*`)])];if(keys.length===0){return 0}return await this.storage.mdelete(keys)}async clearExpiredApprovals(){this.ensureInitialized();const now=Date.now();const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);const keysToDelete=[];for(let i=0;i<keys.length;i++){const approval=this.parseRecord(values[i]);if(approval&&approval.expiresAt&&approval.expiresAt<=now){keysToDelete.push(keys[i])}}if(keysToDelete.length>0){return await this.storage.mdelete(keysToDelete)}return 0}async getStats(){this.ensureInitialized();const byScope={["session"]:0,["user"]:0,["time_limited"]:0,["tool_specific"]:0,["context_specific"]:0};const byState={["pending"]:0,["approved"]:0,["denied"]:0,["expired"]:0};const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);let total=0;for(const value of values){const approval=this.parseRecord(value);if(approval){total++;byScope[approval.scope]++;byState[approval.state]++}}return{totalApprovals:total,byScope,byState}}async close(){if(this.cleanupInterval){clearInterval(this.cleanupInterval);this.cleanupInterval=void 0}if(this.ownedStorage&&this.storage){await this.storage.root.disconnect()}this.revocationStorage=void 0;this.initialized=false}};ApprovalStorageStore=__decorateClass([Provider3({name:"provider:approval:store:storage",description:"Storage-backed approval store (supports Memory, Redis, Vercel KV, Upstash)",scope:ProviderScope3.GLOBAL})],ApprovalStorageStore);function createApprovalMemoryStore(options={}){const memoryStorage=createMemoryStorage2();return new ApprovalStorageStore({...options,storageInstance:memoryStorage})}var ApprovalPlugin=class extends DynamicPlugin2{options;constructor(options={}){super();this.options={...ApprovalPlugin.defaultOptions,...options}}};__publicField(ApprovalPlugin,"defaultOptions",{namespace:"approval",mode:"recheck",enableAudit:true,maxDelegationDepth:3,cleanupIntervalSeconds:60});__publicField(ApprovalPlugin,"dynamicProviders",options=>{const providers=[];const config={...ApprovalPlugin.defaultOptions,...options};providers.push({name:"approval:store",provide:ApprovalStoreToken,inject:()=>[],useFactory:async()=>{const store=new ApprovalStorageStore({storage:config.storage,storageInstance:config.storageInstance,namespace:config.namespace,cleanupIntervalSeconds:config.cleanupIntervalSeconds});await store.initialize();return store}});if(config.mode==="webhook"){providers.push({name:"approval:challenge-service",provide:ChallengeServiceToken,inject:()=>[],useFactory:async()=>{const service=new ChallengeService({storage:config.storage,storageInstance:config.storageInstance,namespace:`${config.namespace}:challenge`,defaultTtlSeconds:config.webhook?.challengeTtl??300});await service.initialize();return service}})}providers.push({name:"approval:service",provide:ApprovalServiceToken,scope:ProviderScope4.CONTEXT,inject:()=>[ApprovalStoreToken,FRONTMCP_CONTEXT,ScopeEntry2],useFactory:(store,ctx,scope)=>{const{sessionId,userId}=resolveApprovalIdentity(ctx);const requirementOf=toolId=>{const tool=scope.tools.getTools(true).find(entry=>entry.fullName===toolId);if(!tool)return void 0;const approval=tool.metadata.approval;return resolveApprovalRequirement(approval)};return createApprovalService(store,sessionId,userId,requirementOf)}});return providers});ApprovalPlugin=__decorateClass([Plugin2({name:"approval",description:"Tool authorization workflow with PKCE webhook security",plugins:[ApprovalCheckPlugin],contextExtensions:[{property:"approval",token:ApprovalServiceToken,errorMessage:"ApprovalPlugin is not installed. Add ApprovalPlugin.init() to your plugins array."}]})],ApprovalPlugin);var installed=false;function installApprovalContextExtension(){if(installed)return;const{ExecutionContextBase}=__require("@frontmcp/sdk");Object.defineProperty(ExecutionContextBase.prototype,"approval",{get:function(){return this.get(ApprovalServiceToken)},configurable:true,enumerable:false});installed=true}export{ApprovalCheckPlugin,ApprovalError,ApprovalExpiredError,ApprovalOperationError,ApprovalPlugin,ApprovalPlugin as ApprovalPluginClass,ApprovalRequiredError,ApprovalScope,ApprovalScopeNotAllowedError,ApprovalService,ApprovalServiceToken,ApprovalState,ApprovalStorageStore,ApprovalStoreToken,ChallengeService,ChallengeServiceToken,ChallengeValidationError,adminGrantor,adminRevoker,agentGrantor,apiGrantor,createApprovalMemoryStore,createApprovalService,createMemoryChallengeService,customGrantor,expiryRevoker,installApprovalContextExtension,isApiGrantor,isAutoGrantor,isDelegatedGrantor,isGrantorSource,isHumanGrantor,normalizeGrantor,normalizeRevoker,oauthGrantor,policyGrantor,policyRevoker,sessionEndRevoker,systemGrantor,testGrantor,userGrantor,userRevoker};