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