@frontmcp/plugin-approval 1.12.0 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : undefined;
2
2
  const require = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || 'file:///') : undefined;
3
3
  // __frontmcpCreateRequire
4
- var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);import{DynamicPlugin as DynamicPlugin2,FRONTMCP_CONTEXT,Plugin as Plugin2,ProviderRegistry,ProviderScope as ProviderScope4,ScopeEntry as ScopeEntry2,storeProvider}from"@frontmcp/sdk";import{randomUUID}from"@frontmcp/utils";var UNIDENTIFIED_SESSION_PREFIX="unidentified:";function isUnidentifiedSession(sessionId){return sessionId.startsWith(UNIDENTIFIED_SESSION_PREFIX)}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_SESSION_PREFIX}${randomUUID()}`,userId}}import{isProduction}from"@frontmcp/utils";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||{});import{z}from"@frontmcp/lazy-zod";var approvalScopeSchema=z.nativeEnum(ApprovalScope);var approvalStateSchema=z.nativeEnum(ApprovalState);var approvalMethodSchema=z.enum(["interactive","implicit","delegation","batch","api"]);var approvalSourceTypeSchema=z.string().min(1);var revocationMethodSchema=z.enum(["interactive","implicit","policy","expiry"]);var approvalCategorySchema=z.enum(["read","write","delete","execute","admin"]);var riskLevelSchema=z.enum(["low","medium","high","critical"]);var approvalContextSchema=z.object({type:z.string().min(1),identifier:z.string().min(1),metadata:z.record(z.string(),z.unknown()).optional()});var MAX_DELEGATION_CHAIN_LINKS=64;var delegationLinkSchema=z.object({delegatorId:z.string().min(1),delegateId:z.string().min(1),purpose:z.string().optional()});var delegationContextSchema=z.object({delegatorId:z.string().min(1),delegateId:z.string().min(1),purpose:z.string().optional(),constraints:z.record(z.string(),z.unknown()).optional(),chain:z.array(delegationLinkSchema).max(MAX_DELEGATION_CHAIN_LINKS).optional()});var approvalGrantorSchema=z.object({source:approvalSourceTypeSchema,identifier:z.string().optional(),displayName:z.string().optional(),method:approvalMethodSchema.optional(),origin:z.string().optional(),delegationContext:delegationContextSchema.optional()});var approvalRevokerSchema=z.object({source:z.string().min(1),identifier:z.string().optional(),displayName:z.string().optional(),method:revocationMethodSchema.optional()});var approvalRecordSchema=z.object({toolId:z.string().min(1),state:approvalStateSchema,scope:approvalScopeSchema,grantedAt:z.number(),expiresAt:z.number().optional(),ttlMs:z.number().optional(),sessionId:z.string().optional(),userId:z.string().optional(),context:approvalContextSchema.optional(),grantedBy:approvalGrantorSchema,approvalChain:z.array(approvalGrantorSchema).optional(),reason:z.string().optional(),metadata:z.record(z.string(),z.unknown()).optional(),revokedAt:z.number().optional(),revokedBy:approvalRevokerSchema.optional(),revocationReason:z.string().optional()});var toolApprovalRequirementSchema=z.object({required:z.boolean().optional(),defaultScope:approvalScopeSchema.optional(),allowedScopes:z.array(approvalScopeSchema).optional(),maxTtlMs:z.number().positive().optional(),alwaysPrompt:z.boolean().optional(),skipApproval:z.boolean().optional(),approvalMessage:z.string().optional(),category:approvalCategorySchema.optional(),riskLevel:riskLevelSchema.optional(),preApprovedContexts:z.array(approvalContextSchema).optional()});function userGrantor(userId,displayName,options){return{source:"user",identifier:userId,displayName,method:options?.method??"interactive",origin:options?.origin}}function policyGrantor(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"implicit"}}function adminGrantor(adminId,displayName,options){return{source:"admin",identifier:adminId,displayName,method:options?.method??"interactive",origin:options?.origin}}function systemGrantor(systemId="system"){return{source:"system",identifier:systemId,method:"implicit"}}function agentGrantor(agentId,delegationContext,displayName){return{source:"agent",identifier:agentId,displayName,method:"delegation",delegationContext}}function apiGrantor(apiKeyPrefix,serviceName){return{source:"api",identifier:apiKeyPrefix,displayName:serviceName,method:"api",origin:"api"}}function oauthGrantor(tokenId,provider){return{source:"oauth",identifier:tokenId,displayName:provider,method:"api",origin:"oauth"}}function testGrantor(){return{source:"test",identifier:"test",method:"implicit"}}function customGrantor(source,identifier,options){return{source,identifier,displayName:options?.displayName,method:options?.method,origin:options?.origin,delegationContext:options?.delegationContext}}function userRevoker(userId,displayName){return{source:"user",identifier:userId,displayName,method:"interactive"}}function adminRevoker(adminId,displayName){return{source:"admin",identifier:adminId,displayName,method:"interactive"}}function expiryRevoker(){return{source:"expiry",method:"expiry"}}function sessionEndRevoker(sessionId){return{source:"session_end",identifier:sessionId,method:"implicit"}}function policyRevoker(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"policy"}}function normalizeGrantor(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function normalizeRevoker(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function delegationDepth(context){return(context.chain?.length??0)+1}function delegationProblem(context,maxDepth){const links=[...context.chain??[],context];if(links.length>maxDepth){return`the delegation chain is ${links.length} deep, and maxDelegationDepth is ${maxDepth}`}const parties=new Set([links[0].delegatorId]);for(let index=0;index<links.length;index++){const link=links[index];if(index>0&&link.delegatorId!==links[index-1].delegateId){return`the delegation chain is broken: ${link.delegatorId} was not delegated to by ${links[index-1].delegatorId}`}if(parties.has(link.delegateId))return`the delegation chain names ${link.delegateId} twice`;parties.add(link.delegateId)}return void 0}function grantorDelegationProblem(grantor,maxDepth){return grantor.delegationContext?delegationProblem(grantor.delegationContext,maxDepth):void 0}function extendDelegation(context,delegateId,options={}){const{delegatorId,delegateId:delegate,purpose}=context;return{delegatorId:delegate,delegateId,...options,chain:[...context.chain??[],{delegatorId,delegateId:delegate,...purpose?{purpose}:{}}]}}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"}import{InternalMcpError,PublicMcpError}from"@frontmcp/sdk";var ApprovalConfigurationError=class extends InternalMcpError{name="ApprovalConfigurationError";constructor(message){super(message,"APPROVAL_CONFIGURATION")}};var ApprovalError=class extends PublicMcpError{constructor(message,code="APPROVAL_REQUIRED",statusCode=403){super(message,code,statusCode);this.name="ApprovalError"}};var ApprovalRequiredError=class extends ApprovalError{constructor(details){super(details.message);this.details=details;this.name="ApprovalRequiredError"}details;toJsonRpcError(){return{code:-32600,message:this.details.message,data:{type:"approval_required",toolId:this.details.toolId,state:this.details.state,options:this.details.approvalOptions}}}};var ApprovalOperationError=class extends ApprovalError{constructor(operation,reason){super(`Approval ${operation} failed: ${reason}`,"APPROVAL_OPERATION_FAILED",400);this.operation=operation;this.reason=reason;this.name="ApprovalOperationError"}operation;reason;toJsonRpcError(){return{code:-32603,message:"Approval operation failed",data:{type:"approval_operation_error",operation:this.operation}}}};var ApprovalScopeNotAllowedError=class extends ApprovalError{constructor(requestedScope,allowedScopes){super(`Approval scope '${requestedScope}' is not allowed for this tool. Allowed scopes: ${allowedScopes.join(", ")}`,"APPROVAL_SCOPE_NOT_ALLOWED",400);this.requestedScope=requestedScope;this.allowedScopes=allowedScopes;this.name="ApprovalScopeNotAllowedError"}requestedScope;allowedScopes;toJsonRpcError(){return{code:-32602,message:this.message,data:{type:"approval_scope_not_allowed",requestedScope:this.requestedScope,allowedScopes:this.allowedScopes}}}};var ApprovalExpiredError=class extends ApprovalError{constructor(toolId,expiredAt){super(`Approval for tool '${toolId}' expired at ${new Date(expiredAt).toISOString()}`,"APPROVAL_EXPIRED",403);this.toolId=toolId;this.expiredAt=expiredAt;this.name="ApprovalExpiredError"}toolId;expiredAt;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"approval_expired",toolId:this.toolId,expiredAt:this.expiredAt}}}};var ChallengeValidationError=class extends ApprovalError{constructor(reason="invalid",message){super(message??`PKCE challenge validation failed: ${reason}`,"CHALLENGE_VALIDATION_FAILED",400);this.reason=reason;this.name="ChallengeValidationError"}reason;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"challenge_validation_error",reason:this.reason}}}};import{randomUUID as randomUUID2,verifyWebhookSignature,webhookSignatureHeaders}from"@frontmcp/utils";import{signingKeyOf,WEBHOOK_ID_HEADER,WEBHOOK_SIGNATURE_HEADER,WEBHOOK_TIMESTAMP_HEADER}from"@frontmcp/utils";function signatureHeaders(signingKey,body,now=Date.now()){const message={id:`msg_${randomUUID2()}`,timestamp:Math.floor(now/1e3),body};return webhookSignatureHeaders(message,[signingKey])}function checkSignature(signingKey,message,now=Date.now()){return verifyWebhookSignature(message,[signingKey],now)}import{Provider,ProviderScope}from"@frontmcp/sdk";import{createMemoryStorage,createNamespacedStorage,createStorage,StorageNotSupportedError}from"@frontmcp/utils";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}function auditFieldsOf(record){return{toolId:record.toolId,scope:record.scope,userId:record.userId,context:record.context?{type:record.context.type,identifier:record.context.identifier}:void 0,grantedBy:record.grantedBy,reason:record.reason,expiresAt:record.expiresAt}}var LoggerAuditSink=class{constructor(logger){this.logger=logger}logger;record(event){const fields=Object.fromEntries(Object.entries(event).filter(([,value])=>value!==void 0));this.logger.info(event.toolId?`${event.type} ${event.toolId}`:event.type,fields)}};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 DEFAULT_MAX_DELEGATION_DEPTH=3;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,maxDelegationDepth:options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH,audit:options.audit}}async initialize(){if(this.initialized){return}if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await createStorage(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}if(this.options.cleanupIntervalSeconds>0){this.cleanupInterval=setInterval(()=>{void this.clearExpiredApprovals()},this.options.cleanupIntervalSeconds*1e3);this.cleanupInterval.unref?.()}this.initialized=true}get revocations(){this.revocationStorage??=createNamespacedStorage(this.storage.root,`${this.storage.prefix.replace(/:$/,"")}-revoked`);return this.revocationStorage}ensureInitialized(){if(!this.initialized){throw new Error("ApprovalStorageStore not initialized. Call initialize() first.")}}buildKey(toolId,sessionId,userId,context){const parts=[toolId];if(sessionId)parts.push(`session:${sessionId}`);if(userId)parts.push(`user:${userId}`);if(context)parts.push(`ctx:${context.type}:${context.identifier}`);return parts.join(":")}timeLimitedKey(toolId,sessionId,userId){return`${this.buildKey(toolId,sessionId,userId)}:${TIME_LIMITED_KEY_SEGMENT}`}recordKey(options){const{toolId,scope,sessionId,userId,context}=options;if(scope==="time_limited"&&!context&&!(sessionId&&userId)){return this.timeLimitedKey(toolId,sessionId,userId)}return this.buildKey(toolId,sessionId,userId,context)}parseRecord(value){if(!value)return void 0;try{const parsed=JSON.parse(value);const result=approvalRecordSchema.safeParse(parsed);if(!result.success){return void 0}return result.data}catch{return void 0}}isExpired(approval){return approval.expiresAt!==void 0&&Date.now()>approval.expiresAt}isOverDelegated(record){return record.state==="approved"&&grantorDelegationProblem(record.grantedBy,this.options.maxDelegationDepth)!==void 0}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)&&!this.isOverDelegated(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){return this.writeRecord(options,"approved")}async denyApproval(options){return this.writeRecord(options,"denied")}async writeRecord(options,state){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 delegationProblem2=state==="approved"&&grantorDelegationProblem(grantedBy,this.options.maxDelegationDepth);if(delegationProblem2)throw new ApprovalOperationError("grant",delegationProblem2);const record={toolId:options.toolId,state,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});this.options.audit?.record({type:state==="denied"?"approval.denied":"approval.granted",...auditFieldsOf(record)});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);for(const record of revoked.values()){this.options.audit?.record({type:"approval.revoked",...auditFieldsOf(record),revokedBy,reason:options.reason})}return true}async consumeApproval(record,sessionId,userId,context){this.ensureInitialized();for(const key of this.callerKeys(record.toolId,sessionId,userId,context)){const storedValue=await this.storage.get(key);const stored=this.parseRecord(storedValue);if(storedValue!==null&&stored&&isSameRecord(stored,record)){return this.deleteIfUnchanged(key,storedValue)}}return false}async deleteIfUnchanged(key,storedValue){try{return await this.storage.deleteIfEquals(key,storedValue)}catch(error){if(!(error instanceof StorageNotSupportedError))throw error;return this.storage.delete(key)}}async getRevocations(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const key of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.revocations.get(key));if(record&&record.toolId===toolId)records.push(record)}return records.sort((a,b)=>(a.revokedAt??0)-(b.revokedAt??0))}async isApproved(toolId,sessionId,userId,context){const approval=await this.getApproval(toolId,sessionId,userId,context);return approval?.state==="approved"}async clearSessionApprovals(sessionId){this.ensureInitialized();const escapedSessionId=escapePattern(sessionId);const keys=[...new Set([...await this.storage.keys(`*:session:${escapedSessionId}`),...await this.storage.keys(`*:session:${escapedSessionId}:*`)])];if(keys.length===0){return 0}const count=await this.storage.mdelete(keys);this.options.audit?.record({type:"approval.revoked",count,reason:"session approvals cleared"});return count}async clearExpiredApprovals(){this.ensureInitialized();const now=Date.now();const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);const keysToDelete=[];const expired=[];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]);expired.push(approval)}}if(keysToDelete.length===0)return 0;const deleted=await this.storage.mdelete(keysToDelete);for(const record of expired)this.options.audit?.record({type:"approval.expired",...auditFieldsOf(record)});return deleted}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([Provider({name:"provider:approval:store:storage",description:"Storage-backed approval store (supports Memory, Redis, Vercel KV, Upstash)",scope:ProviderScope.GLOBAL})],ApprovalStorageStore);function createApprovalMemoryStore(options={}){const memoryStorage=createMemoryStorage();return new ApprovalStorageStore({...options,storageInstance:memoryStorage})}var DEFAULT_CALLBACK_PATH="/approval/callback";var DEFAULT_RECHECK_INTERVAL_MS=2e3;var DEFAULT_RECHECK_MAX_ATTEMPTS=5;var MAX_RECHECK_WAIT_MS=12e4;var MIN_SECRET_BYTES=24;var LOOPBACK_HOSTNAMES=new Set(["localhost","127.0.0.1","[::1]"]);var CALLBACK_PATH_PATTERN=/^(\/[A-Za-z0-9._~-]+)+$/;function refuse(message){throw new ApprovalConfigurationError(`ApprovalPlugin ${message}`)}function setOptions(values){return Object.entries(values).filter(([,value])=>value!==void 0).map(([name2])=>name2)}function checkOutboundUrl(option,url){let parsed;try{parsed=new URL(url)}catch{return refuse(`\`${option}\` is not a URL`)}if(parsed.username||parsed.password){refuse(`\`${option}\` must not carry credentials; use the auth options instead`)}const loopbackInDevelopment=parsed.protocol==="http:"&&LOOPBACK_HOSTNAMES.has(parsed.hostname)&&!isProduction();if(parsed.protocol!=="https:"&&!loopbackInDevelopment){refuse(`\`${option}\` must be an https:// URL (http://localhost is accepted when NODE_ENV is not production), got ${parsed.protocol}//${parsed.host}`)}return parsed.toString()}function checkSecret(option,secret){if(secret===void 0||secret.trim()===""){return refuse(`needs \`${option}\` to sign its requests and verify callbacks`)}let signingKey;try{signingKey=signingKeyOf(secret)}catch{return refuse(`\`${option}\` starts with whsec_ but the rest is not base64`)}if(signingKey.length<MIN_SECRET_BYTES){refuse(`\`${option}\` must be at least ${MIN_SECRET_BYTES} bytes (32 characters or more is recommended)`)}return signingKey}function checkWholeNumber(option,value,min,max){if(!Number.isInteger(value)||value<min||value>max){refuse(`\`${option}\` must be a whole number from ${min} to ${max}, got ${value}`)}return value}function resolveWebhook(options){const{url,secret,includeJwt,callbackPath,challengeTtl}=options.webhook??{};const external=setOptions({url,secret,includeJwt,callbackPath}).map(name2=>`\`webhook.${name2}\``);if(external.length===0)return void 0;if(options.mode!=="webhook")refuse(`${external.join(", ")} need \`mode: 'webhook'\``);if(url===void 0)refuse(`${external.join(", ")} need \`webhook.url\``);const path=callbackPath??DEFAULT_CALLBACK_PATH;if(!CALLBACK_PATH_PATTERN.test(path)||path.length>256){refuse(`\`webhook.callbackPath\` must be a path such as ${DEFAULT_CALLBACK_PATH}, got ${JSON.stringify(path)}`)}return{url:checkOutboundUrl("webhook.url",url),signingKey:checkSecret("webhook.secret",secret),includeJwt:includeJwt===true,callbackPath:path,challengeTtlSeconds:challengeTtl??300}}function resolveRecheck(options){if(options.recheck===void 0)return void 0;const{url,auth="none",token,headers,secret,interval,maxAttempts}=options.recheck;if(options.mode==="webhook")refuse("`recheck` needs `mode: 'recheck'`");if(url===void 0){const others=setOptions({auth:options.recheck.auth,token,headers,secret,interval,maxAttempts});refuse(`${others.map(name2=>`\`recheck.${name2}\``).join(", ")||"`recheck`"} need \`recheck.url\``)}if(!["jwt","bearer","none","custom"].includes(auth)){refuse(`\`recheck.auth\` must be 'jwt', 'bearer', 'none' or 'custom', got ${JSON.stringify(auth)}`)}if(auth==="bearer"&&!token)refuse("`recheck.auth: 'bearer'` needs `recheck.token`");if(auth!=="bearer"&&token!==void 0)refuse("`recheck.token` is only sent with `recheck.auth: 'bearer'`");if(auth==="custom"&&typeof headers!=="function")refuse("`recheck.auth: 'custom'` needs a `recheck.headers` function");if(auth!=="custom"&&headers!==void 0)refuse("`recheck.headers` is only used with `recheck.auth: 'custom'`");const intervalMs=checkWholeNumber("recheck.interval",interval??DEFAULT_RECHECK_INTERVAL_MS,100,6e4);const attempts=checkWholeNumber("recheck.maxAttempts",maxAttempts??DEFAULT_RECHECK_MAX_ATTEMPTS,1,60);if(intervalMs*(attempts-1)>MAX_RECHECK_WAIT_MS){refuse(`would keep a call waiting ${intervalMs*(attempts-1)} ms: \`recheck.interval\` \xD7 (\`recheck.maxAttempts\` \u2212 1) must be ${MAX_RECHECK_WAIT_MS} ms or less`)}return{url:checkOutboundUrl("recheck.url",url),auth,token,headers,signingKey:secret===void 0?void 0:checkSecret("recheck.secret",secret),intervalMs,maxAttempts:attempts}}function resolveExternalApproval(options){return{webhook:resolveWebhook(options),recheck:resolveRecheck(options)}}function resolveMaxDelegationDepth(options){const depth=options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH;return checkWholeNumber("maxDelegationDepth",depth,0,MAX_DELEGATION_CHAIN_LINKS)}var ApprovalStoreToken=Symbol.for("plugin:approval:store");var ApprovalServiceToken=Symbol.for("plugin:approval:service");var ChallengeServiceToken=Symbol.for("plugin:approval:challenge-service");var ExternalApproverToken=Symbol.for("plugin:approval:external-approver");var ApprovalAuditToken=Symbol.for("plugin:approval:audit");import"reflect-metadata";import{z as z2}from"@frontmcp/lazy-zod";import{enforceGlobalRateLimit,enforceIpFilter,Flow,FlowBase,FlowHooksOf,httpInputSchema,HttpJsonSchema,normalizeEntryPrefix,normalizeScopeBase}from"@frontmcp/sdk";var plan={pre:["checkIpFilter","acquireQuota"],execute:["handleCallback"]};var approvalCallbackStateSchema=z2.object({});var callbackRoutes=new WeakMap;var name="approval:webhook-callback";var{Stage}=FlowHooksOf(name);var ApprovalCallbackFlow=class extends FlowBase{static canActivate(request,scope){return callbackRoutes.get(scope)?.has(request.path)??false}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async handleCallback(){const request=this.rawInput.request;const handler=callbackRoutes.get(this.scope)?.get(request.path);if(!handler)return this.next();this.respond(await handler.handleCallback({headers:request.headers,bodyBytes:request.bodyBytes}))}};__decorateClass([Stage("checkIpFilter")],ApprovalCallbackFlow.prototype,"checkIpFilter",1);__decorateClass([Stage("acquireQuota")],ApprovalCallbackFlow.prototype,"acquireQuota",1);__decorateClass([Stage("handleCallback")],ApprovalCallbackFlow.prototype,"handleCallback",1);ApprovalCallbackFlow=__decorateClass([Flow({name,plan,access:"public",inputSchema:httpInputSchema,outputSchema:HttpJsonSchema,middleware:{method:"POST"}})],ApprovalCallbackFlow);function mcpPaths(scope){const base=`${normalizeEntryPrefix(scope.entryPath)}${normalizeScopeBase(scope.routeBase)}`;return[base||"/",`${base}/sse`,`${base}/message`,`${base}/server-card`]}async function serveApprovalCallback(scope,path,handler){if(mcpPaths(scope).includes(path)||/^\/(oauth|\.well-known)(\/|$)/.test(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is a path the server reserves`)}let routes=callbackRoutes.get(scope);const firstRoute=!routes;routes??=new Map;if(routes.has(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is served by another ApprovalPlugin; give each its own`)}routes.set(path,handler);callbackRoutes.set(scope,routes);if(firstRoute)await scope.registryFlows(ApprovalCallbackFlow)}import{sha256Hex}from"@frontmcp/utils";function pendingRequestKey(subject){return sha256Hex(JSON.stringify([subject.toolId,subject.sessionId,subject.userId??null]))}function grantTarget(scope,subject){const{sessionId,userId,context}=subject;switch(scope){case"session":return{sessionId};case"user":return userId?{userId}:void 0;case"time_limited":return{sessionId,userId};case"context_specific":return context?{context,sessionId,userId}:void 0;default:return void 0}}var ApprovalDecisionRecorder=class{constructor(store,requirementOf,logger){this.store=store;this.requirementOf=requirementOf;this.logger=logger}store;requirementOf;logger;async approve(subject,decision,origin){const requirement=this.requirementOf(subject.toolId);const scope=decision.scope??requirement?.defaultScope??"session";const target=grantTarget(scope,subject);if(!target){this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: no ${scope} to grant it to`);return false}try{const ttlMs=checkGrantAgainstPolicy(subject.toolId,scope,decision.ttlMs,requirement);await this.store.grantApproval({toolId:subject.toolId,scope,ttlMs,...target,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason});return true}catch(error){if(!(error instanceof ApprovalError))throw error;this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: ${error.message}`);return false}}async deny(subject,decision,ttlMs,origin){if(!this.store.denyApproval){this.logger.warn(`ApprovalPlugin: the ${origin} denial of ${subject.toolId} was not recorded: the store keeps no denials`);return}await this.store.denyApproval({toolId:subject.toolId,scope:"session",ttlMs,sessionId:subject.sessionId,userId:subject.userId,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason})}};import{z as z3}from"@frontmcp/lazy-zod";import{isRedirectResponse}from"@frontmcp/utils";var OUTBOUND_TIMEOUT_MS=1e4;var OUTBOUND_MAX_RESPONSE_BYTES=64*1024;var OutboundRequestError=class extends Error{name="OutboundRequestError"};async function readBounded(response){const declaredLength=Number(response.headers.get("content-length")??0);if(declaredLength>OUTBOUND_MAX_RESPONSE_BYTES){await response.body?.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}if(!response.body)return"";const reader=response.body.getReader();const chunks=[];let received2=0;for(;;){const{done,value}=await reader.read();if(done)break;received2+=value.byteLength;if(received2>OUTBOUND_MAX_RESPONSE_BYTES){await reader.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}chunks.push(value)}const bytes=new Uint8Array(received2);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength}return new TextDecoder().decode(bytes)}function failureCode(error){const cause=error?.cause;return typeof cause?.code==="string"?cause.code:error instanceof Error?error.name:"unknown error"}async function postJson(request){const timeoutMs=request.timeoutMs??OUTBOUND_TIMEOUT_MS;const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeoutMs);const cancel=()=>controller.abort();request.signal?.addEventListener("abort",cancel,{once:true});try{const response=await fetch(request.url,{method:"POST",headers:{...request.headers,"content-type":"application/json",accept:"application/json"},body:request.body,redirect:"manual",signal:controller.signal});if(isRedirectResponse(response)){await response.body?.cancel();throw new OutboundRequestError(`answered with a redirect (${response.status}), which is not followed`)}return{status:response.status,body:await readBounded(response)}}catch(error){if(error instanceof OutboundRequestError)throw error;if(request.signal?.aborted)throw new OutboundRequestError("the tool call was cancelled");if(controller.signal.aborted)throw new OutboundRequestError(`no answer within ${timeoutMs} ms`);throw new OutboundRequestError(`the request failed (${failureCode(error)})`)}finally{clearTimeout(timer);request.signal?.removeEventListener("abort",cancel)}}function originOf(url){return new URL(url).origin}var recheckAnswerSchema=z3.object({approved:z3.boolean(),pending:z3.boolean().optional(),scope:approvalScopeSchema.optional(),ttlMs:z3.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),denialReason:z3.string().max(1e3).optional()});function wait(ms,signal){if(signal?.aborted)return Promise.resolve(false);return new Promise(resolve=>{const done=completed=>{clearTimeout(timer);signal?.removeEventListener("abort",cancelled);resolve(completed)};const cancelled=()=>done(false);const timer=setTimeout(()=>done(true),ms);signal?.addEventListener("abort",cancelled,{once:true})})}var RecheckApprover=class{constructor(recheck,dependencies,logger){this.recheck=recheck;this.dependencies=dependencies;this.logger=logger}recheck;dependencies;logger;via="recheck";async requestApproval(call){for(let attempt=1;attempt<=this.recheck.maxAttempts;attempt++){if(attempt>1&&!await wait(this.recheck.intervalMs,call.signal))return"pending";let answer;try{answer=await this.poll(call,attempt)}catch(error){if(!(error instanceof OutboundRequestError))throw error;this.logger.warn(`ApprovalPlugin: polling ${originOf(this.recheck.url)} for ${call.toolId} failed: ${error.message}`);return"pending"}if(!answer)return"pending";if(answer.approved)return await this.approve(call,answer)?"approved":"pending";if(!answer.pending)return"denied"}return"pending"}async approve(call,answer){if(call.requirement.alwaysPrompt)return true;return this.dependencies.decisions.approve(call,{scope:answer.scope,ttlMs:answer.ttlMs,decidedBy:answer.grantedBy},"recheck")}async poll(call,attempt){const{requirement}=call;const request={type:"approval.status",requestId:pendingRequestKey(call),attempt,toolId:call.toolId,toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,approvalMessage:requirement.approvalMessage,requestedScope:requirement.defaultScope??"session",allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,timestamp:Date.now()};const authorization=await this.authorization(call,request);if(!authorization)return void 0;const body=JSON.stringify(request);const signing=this.recheck.signingKey?signatureHeaders(this.recheck.signingKey,body):{};const answer=await postJson({url:this.recheck.url,body,headers:{...authorization,...signing},signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);try{return recheckAnswerSchema.parse(JSON.parse(answer.body))}catch{throw new OutboundRequestError("answered with something other than { approved, pending?, scope?, ttlMs?, ... }")}}async authorization(call,request){switch(this.recheck.auth){case"jwt":if(!call.accessToken){this.logger.verbose(`ApprovalPlugin: not polling for ${call.toolId}: the call has no token to forward`);return void 0}return{authorization:`Bearer ${call.accessToken}`};case"bearer":return{authorization:`Bearer ${this.recheck.token}`};case"custom":return{...await this.recheck.headers?.(request)};default:return{}}}};import{z as z4}from"@frontmcp/lazy-zod";import{getPinnedPublicUrl,httpRespond}from"@frontmcp/sdk";var MAX_CALLBACK_BYTES=16*1024;var callbackSchema=z4.object({codeVerifier:z4.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),approved:z4.boolean(),scope:approvalScopeSchema.optional(),ttlMs:z4.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),reason:z4.string().max(1e3).optional()});function refusal(status,error,description){return httpRespond.json({error,error_description:description},{status})}function headerOf(headers,name2){const value=headers[name2];return typeof value==="string"?value:void 0}function received(){return httpRespond.json({status:"received"},{status:202})}var WebhookApprover=class{constructor(webhook,dependencies,logger){this.webhook=webhook;this.dependencies=dependencies;this.logger=logger}webhook;dependencies;logger;via="webhook";get challenges(){return this.dependencies.challenges}async requestApproval(call){const pendingKey=pendingRequestKey(call);const ttlSeconds=this.webhook.challengeTtlSeconds;if(!await this.challenges.claimPendingRequest(pendingKey,ttlSeconds))return"pending";const{requirement}=call;const requestedScope=requirement.defaultScope??"session";const requestInfo={toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,customMessage:requirement.approvalMessage};const{codeVerifier,codeChallenge,expiresAt}=await this.challenges.createChallenge({toolId:call.toolId,sessionId:call.sessionId,userId:call.userId,context:call.context,requestedScope,requestInfo,ttlSeconds});const publicUrl=getPinnedPublicUrl();const payload={type:"approval.requested",codeChallenge,codeVerifier,toolId:call.toolId,toolName:call.toolName,category:requestInfo.category,riskLevel:requestInfo.riskLevel,approvalMessage:requestInfo.customMessage,requestedScope,allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,callbackPath:this.webhook.callbackPath,callbackUrl:publicUrl?`${publicUrl}${this.webhook.callbackPath}`:void 0,expiresAt,timestamp:Date.now(),jwt:this.webhook.includeJwt?call.accessToken:void 0};const body=JSON.stringify(payload);try{const answer=await postJson({url:this.webhook.url,body,headers:signatureHeaders(this.webhook.signingKey,body),signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);await this.challenges.markWebhookSent(codeChallenge)}catch(error){if(!(error instanceof OutboundRequestError))throw error;await this.challenges.deleteChallenge(codeChallenge);await this.challenges.releasePendingRequest(pendingKey);this.logger.warn(`ApprovalPlugin: the approval request for ${call.toolId} to ${originOf(this.webhook.url)} failed: ${error.message}`)}return"pending"}async handleCallback(request){const{bodyBytes}=request;if(!bodyBytes||bodyBytes.byteLength===0){return refusal(400,"invalid_request","the body must be the decision, as JSON")}if(bodyBytes.byteLength>MAX_CALLBACK_BYTES){return refusal(413,"payload_too_large",`the body must be ${MAX_CALLBACK_BYTES} bytes or less`)}const body=new TextDecoder().decode(bodyBytes);const signature=checkSignature(this.webhook.signingKey,{id:headerOf(request.headers,WEBHOOK_ID_HEADER),timestamp:headerOf(request.headers,WEBHOOK_TIMESTAMP_HEADER),signature:headerOf(request.headers,WEBHOOK_SIGNATURE_HEADER),body});if(signature!=="valid"){this.logger.warn(`ApprovalPlugin: refused an approval callback: signature ${signature}`);return refusal(401,"invalid_signature","the callback must be signed with webhook.secret, within five minutes")}let decision;try{decision=callbackSchema.parse(JSON.parse(body))}catch{return refusal(400,"invalid_request","the body must be { codeVerifier, approved, scope?, ttlMs?, grantedBy?, reason? }")}const pending=await this.challenges.consume(decision.codeVerifier);if(!pending)return received();await this.challenges.releasePendingRequest(pendingRequestKey(pending));const subject={toolId:pending.toolId,sessionId:pending.sessionId,userId:pending.userId,context:pending.context};const outcome={scope:decision.scope,ttlMs:decision.ttlMs,decidedBy:decision.grantedBy,reason:decision.reason};if(decision.approved){await this.dependencies.decisions.approve(subject,outcome,"webhook")}else{await this.dependencies.decisions.deny(subject,outcome,decision.ttlMs??this.webhook.challengeTtlSeconds*1e3,"webhook")}return received()}};import{DynamicPlugin,isEntryGatedBy,Plugin,ProviderNotAvailableError,ScopeEntry,ToolHook}from"@frontmcp/sdk";var decidedCalls=new WeakSet;var ApprovalCheckPlugin=class extends DynamicPlugin{async checkApproval(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;const metadata=tool.metadata;const approvalConfig=resolveApprovalRequirement(metadata["approval"]);if(!approvalConfig.required){return}if(approvalConfig.skipApproval){return}if(decidedCalls.has(toolContext))return;await this.enforceApproval(flowCtx,tool,toolContext,approvalConfig,this.coveringStores(tool));decidedCalls.add(toolContext)}async enforceApproval(flowCtx,tool,toolContext,approvalConfig,stores){const callerContext=toolContext.tryGetContext?.();const{sessionId,userId}=resolveApprovalIdentity(callerContext);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);const requested=(state,via)=>this.optional(ApprovalAuditToken)?.record({type:"approval.requested",toolId:tool.fullName,userId,context:currentContext&&{type:currentContext.type,identifier:currentContext.identifier},state,via});if(records.some(record=>record.state==="denied")){requested("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}const external=isUnidentifiedSession(sessionId)?void 0:this.optional(ExternalApproverToken);const outcome=await external?.requestApproval({toolId:tool.fullName,toolName:tool.name,sessionId,userId,context:currentContext,requirement:approvalConfig,accessToken:callerContext?.authInfo?.token,signal:toolContext.signal});const expiredApproval=approved.find(record=>isApprovalExpired(record,approvalConfig,now));const callState=outcome==="approved"||outcome==="denied"?outcome:expiredApproval?"expired":"pending";requested(callState,external?.via);if(outcome==="approved")return;if(outcome==="denied"){throw new ApprovalRequiredError({toolId:tool.fullName,state:"denied",message:`Tool "${tool.fullName}" execution denied.`})}await this.handleApprovalRequired(flowCtx,approvalConfig,expiredApproval??approved[0])}optional(token){try{return this.get(token)}catch(error){if(error instanceof ProviderNotAvailableError)return void 0;throw error}}coveringStores(tool){const stores=new Set([this.get(ApprovalStoreToken)]);let scope;try{scope=this.get(ScopeEntry)}catch{scope=void 0}if(!scope?.hooks)return[...stores];for(const hook of scope.hooks.getFlowHooks("tools:call-tool")){const gate=hook.metadata.target;if(gate instanceof ApprovalCheckPlugin&&isEntryGatedBy(scope,{tool},gate)){stores.add(gate.get(ApprovalStoreToken))}}return[...stores]}async consumeApproval(store,record,sessionId,userId,context){if(store.consumeApproval){return store.consumeApproval(record,sessionId,userId,context)}return store.revokeApproval({toolId:record.toolId,sessionId,userId,revokedBy:"system",reason:"Used by a call of an alwaysPrompt tool"})}async readApprovals(store,toolId,sessionId,userId,context){if(store.getApprovals){return store.getApprovals(toolId,sessionId,userId,context)}const record=await store.getApproval(toolId,sessionId,userId,context);return record?[record]:[]}getCurrentContext(flowCtx){const ctx=flowCtx.state.toolContext?.tryGetContext?.();const sessionContext=ctx?.authInfo?.extra?.["approvalContext"];return this.isApprovalContext(sessionContext)?sessionContext:void 0}isApprovalContext(value){return typeof value==="object"&&value!==null&&"type"in value&&"identifier"in value&&typeof value.type==="string"&&typeof value.identifier==="string"}isPreApprovedContext(config,currentContext){if(!currentContext||!config.preApprovedContexts?.length){return false}return config.preApprovedContexts.some(preApproved=>preApproved.type===currentContext.type&&preApproved.identifier===currentContext.identifier)}async handleApprovalRequired(flowCtx,config,existingApproval){const{tool}=flowCtx.state;const message=config.approvalMessage??`Tool "${tool?.fullName}" requires approval to execute. Allow?`;const isExpiredApproval=existingApproval?isApprovalExpired(existingApproval,config,Date.now()):false;throw new ApprovalRequiredError({toolId:tool?.fullName??"unknown",state:isExpiredApproval?"expired":"pending",message,approvalOptions:{allowedScopes:config.allowedScopes,defaultScope:config.defaultScope,maxTtlMs:config.maxTtlMs,category:config.category,riskLevel:config.riskLevel}})}};__decorateClass([ToolHook.Will("execute",{priority:100,appliesTo:"uncovered-apps"})],ApprovalCheckPlugin.prototype,"checkApproval",1);ApprovalCheckPlugin=__decorateClass([Plugin({name:"approval:check",description:"Checks tool approval state before execution",enforcesMetadata:["approval"]})],ApprovalCheckPlugin);import{isAnonymousSubject,Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";var ApprovalService=class{constructor(store,sessionId,userId,requirementOf=()=>void 0){this.store=store;this.sessionId=sessionId;this.userId=userId;this.requirementOf=requirementOf}store;sessionId;userId;requirementOf;checkGrant(toolId,scope,ttlMs){return checkGrantAgainstPolicy(toolId,scope,ttlMs,this.requirementOf(toolId))}get signedInUserId(){return this.userId&&!isAnonymousSubject(this.userId)?this.userId:void 0}defaultGrantor(){const userId=this.signedInUserId;return userId?userGrantor(userId,void 0,{method:"implicit"}):{source:"user",method:"implicit"}}defaultRevoker(){const userId=this.signedInUserId;return userId?{source:"user",identifier:userId,method:"implicit"}:{source:"user",method:"implicit"}}async isApproved(toolId,context){const requirement=this.requirementOf(toolId);if(!requirement||!this.store.getApprovals){return this.store.isApproved(toolId,this.sessionId,this.userId,context)}const records=await this.store.getApprovals(toolId,this.sessionId,this.userId,context);if(records.some(record=>record.state==="denied"))return false;const now=Date.now();return records.some(record=>isApprovalUsable(record,requirement,now))}async getApproval(toolId){return this.store.getApproval(toolId,this.sessionId,this.userId)}async getSessionApprovals(){return this.store.queryApprovals({sessionId:this.sessionId,states:["approved"],includeExpired:false})}async getUserApprovals(){if(!this.userId)return[];return this.store.queryApprovals({userId:this.userId,scope:"user",states:["approved"],includeExpired:false})}async queryApprovals(query){const records=await this.store.queryApprovals(query);return records.filter(record=>record.sessionId===this.sessionId||this.userId!==void 0&&record.userId===this.userId)}async getRevocations(toolId){return await this.store.getRevocations?.(toolId,this.sessionId,this.userId)??[]}async grantSessionApproval(toolId,options={}){const ttlMs=this.checkGrant(toolId,"session");return this.store.grantApproval({toolId,scope:"session",ttlMs,sessionId:this.sessionId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantUserApproval(toolId,options={}){if(!this.userId){throw new Error("Cannot grant user approval without userId")}const ttlMs=this.checkGrant(toolId,"user");return this.store.grantApproval({toolId,scope:"user",ttlMs,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantTimeLimitedApproval(toolId,ttlMs,options={}){this.checkGrant(toolId,"time_limited",ttlMs);return this.store.grantApproval({toolId,scope:"time_limited",ttlMs,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantContextApproval(toolId,context,options={}){const ttlMs=this.checkGrant(toolId,"context_specific");return this.store.grantApproval({toolId,scope:"context_specific",ttlMs,context,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async revokeApproval(toolId,options={}){return this.store.revokeApproval({toolId,sessionId:this.sessionId,userId:this.userId,revokedBy:options.revokedBy??this.defaultRevoker(),reason:options.reason})}async clearSessionApprovals(){return this.store.clearSessionApprovals(this.sessionId)}};ApprovalService=__decorateClass([Provider2({name:"provider:approval:service",description:"Service for managing tool approvals",scope:ProviderScope2.CONTEXT})],ApprovalService);function createApprovalService(store,sessionId,userId,requirementOf){return new ApprovalService(store,sessionId,userId,requirementOf)}import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{createMemoryStorage as createMemoryStorage2,createStorage as createStorage2,generateCodeChallenge,generatePkcePair,randomUUID as randomUUID3,StorageNotSupportedError as StorageNotSupportedError2}from"@frontmcp/utils";var PENDING_REQUEST_PREFIX="pending:";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 createStorage2(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}this.initialized=true}ensureInitialized(){if(!this.initialized){throw new Error("ChallengeService not initialized. Call initialize() first.")}}async createChallenge(options){this.ensureInitialized();const{codeVerifier,codeChallenge}=generatePkcePair();const now=Date.now();const ttlSeconds=options.ttlSeconds??this.options.defaultTtlSeconds;const expiresAt=now+ttlSeconds*1e3;const record={toolId:options.toolId,sessionId:options.sessionId,userId:options.userId,context:options.context,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){const consumed=await this.take(codeVerifier);if(!consumed){throw new ChallengeValidationError("not_found","Invalid or expired challenge")}if(Date.now()>consumed.expiresAt){throw new ChallengeValidationError("expired","Challenge expired")}return consumed}async consume(codeVerifier){const consumed=await this.take(codeVerifier);return consumed&&Date.now()<=consumed.expiresAt?consumed:void 0}async take(codeVerifier){this.ensureInitialized();const codeChallenge=generateCodeChallenge(codeVerifier);const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return void 0;if(!await this.deleteIfUnchanged(codeChallenge,recordJson))return void 0;return JSON.parse(recordJson)}async deleteIfUnchanged(key,value){try{return await this.storage.deleteIfEquals(key,value)}catch(error){if(!(error instanceof StorageNotSupportedError2))throw error;return this.storage.delete(key)}}async claimPendingRequest(key,ttlSeconds=this.options.defaultTtlSeconds){this.ensureInitialized();const claim=randomUUID3();const pendingKey=`${PENDING_REQUEST_PREFIX}${key}`;try{await this.storage.set(pendingKey,claim,{ttlSeconds,ifNotExists:true})}catch(error){if(!(error instanceof StorageNotSupportedError2))throw error;if(await this.storage.exists(pendingKey))return false;await this.storage.set(pendingKey,claim,{ttlSeconds})}return await this.storage.get(pendingKey)===claim}async releasePendingRequest(key){this.ensureInitialized();await this.storage.delete(`${PENDING_REQUEST_PREFIX}${key}`)}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([Provider3({name:"provider:approval:challenge-service",description:"PKCE challenge service for webhook approval flows",scope:ProviderScope3.GLOBAL})],ChallengeService);function createMemoryChallengeService(options={}){const memoryStorage=createMemoryStorage2();return new ChallengeService({...options,storageInstance:memoryStorage})}function toolRequirementLookup(scope){return 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)}}function externalApproverProvider(external){const{webhook,recheck}=external;if(!webhook&&!recheck)return void 0;return{name:"approval:external-approver",provide:ExternalApproverToken,inject:()=>[ProviderRegistry,ScopeEntry2],useFactory:async(providers,scope)=>{const logger=scope.logger.child("ApprovalPlugin");const requirementOf=toolRequirementLookup(scope);const dependencies={get challenges(){return providers.get(ChallengeServiceToken)},get decisions(){return new ApprovalDecisionRecorder(providers.get(ApprovalStoreToken),requirementOf,logger)}};if(!webhook)return new RecheckApprover(recheck,dependencies,logger);const approver=new WebhookApprover(webhook,dependencies,logger);await serveApprovalCallback(scope,webhook.callbackPath,approver);return approver}}}var ApprovalPlugin=class extends DynamicPlugin2{options;constructor(options={}){super();this.options={...ApprovalPlugin.defaultOptions,...options}}};__publicField(ApprovalPlugin,"defaultOptions",{namespace:"approval",mode:"recheck",enableAudit:false,maxDelegationDepth:DEFAULT_MAX_DELEGATION_DEPTH,cleanupIntervalSeconds:60});__publicField(ApprovalPlugin,"browserStores",({storage,storageInstance})=>{const type=storageInstance?void 0:storage?.type;return[{plugin:"ApprovalPlugin",option:type==="redis"||type==="sqlite"?`storage: { type: '${type}' }`:void 0,memory:"storage: { type: 'memory' }"}]});__publicField(ApprovalPlugin,"dynamicProviders",options=>{const providers=[];const config={...ApprovalPlugin.defaultOptions,...options};const external=resolveExternalApproval(config);const maxDelegationDepth=resolveMaxDelegationDepth(config);providers.push(storeProvider({name:"approval:store",provide:ApprovalStoreToken,inject:()=>[ScopeEntry2],useFactory:async scope=>{const store=new ApprovalStorageStore({storage:config.storage,storageInstance:config.storageInstance,namespace:config.namespace,cleanupIntervalSeconds:config.cleanupIntervalSeconds,maxDelegationDepth,audit:config.enableAudit?new LoggerAuditSink(scope.logger.child("ApprovalAudit")):void 0});await store.initialize();return store}}));if(config.mode==="webhook"){providers.push(storeProvider({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}}))}const externalApprover=externalApproverProvider(external);if(externalApprover)providers.push(externalApprover);if(config.enableAudit){providers.push({name:"approval:audit",provide:ApprovalAuditToken,inject:()=>[ScopeEntry2],useFactory:scope=>new LoggerAuditSink(scope.logger.child("ApprovalAudit"))})}providers.push({name:"approval:service",provide:ApprovalServiceToken,scope:ProviderScope4.CONTEXT,inject:()=>[ApprovalStoreToken,FRONTMCP_CONTEXT,ScopeEntry2],useFactory:(store,ctx,scope)=>{const{sessionId,userId}=resolveApprovalIdentity(ctx);return createApprovalService(store,sessionId,userId,toolRequirementLookup(scope))}});return providers});ApprovalPlugin=__decorateClass([Plugin2({name:"approval",description:"Tool authorization workflow with PKCE webhook security",plugins:[ApprovalCheckPlugin],contextExtensions:[{property:"approval",token:ApprovalServiceToken,errorMessage:"ApprovalPlugin is not installed. Add ApprovalPlugin.init() to your plugins array."}]})],ApprovalPlugin);var installed=false;function installApprovalContextExtension(){if(installed)return;const{ExecutionContextBase}=__require("@frontmcp/sdk");Object.defineProperty(ExecutionContextBase.prototype,"approval",{get:function(){return this.get(ApprovalServiceToken)},configurable:true,enumerable:false});installed=true}export{ApprovalCheckPlugin,ApprovalConfigurationError,ApprovalError,ApprovalExpiredError,ApprovalOperationError,ApprovalPlugin,ApprovalPlugin as ApprovalPluginClass,ApprovalRequiredError,ApprovalScope,ApprovalScopeNotAllowedError,ApprovalService,ApprovalServiceToken,ApprovalState,ApprovalStorageStore,ApprovalStoreToken,ChallengeService,ChallengeServiceToken,ChallengeValidationError,adminGrantor,adminRevoker,agentGrantor,apiGrantor,createApprovalMemoryStore,createApprovalService,createMemoryChallengeService,customGrantor,delegationDepth,delegationProblem,expiryRevoker,extendDelegation,installApprovalContextExtension,isApiGrantor,isAutoGrantor,isDelegatedGrantor,isGrantorSource,isHumanGrantor,normalizeGrantor,normalizeRevoker,oauthGrantor,policyGrantor,policyRevoker,sessionEndRevoker,systemGrantor,testGrantor,userGrantor,userRevoker};
4
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);import{DynamicPlugin as DynamicPlugin2,FRONTMCP_CONTEXT,Plugin as Plugin2,ProviderRegistry,ProviderScope as ProviderScope4,ScopeEntry as ScopeEntry2,storeProvider}from"@frontmcp/sdk";import{randomUUID}from"@frontmcp/utils";var UNIDENTIFIED_SESSION_PREFIX="unidentified:";function isUnidentifiedSession(sessionId){return sessionId.startsWith(UNIDENTIFIED_SESSION_PREFIX)}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_SESSION_PREFIX}${randomUUID()}`,userId}}import{isProduction}from"@frontmcp/utils";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||{});import{z}from"@frontmcp/lazy-zod";var approvalScopeSchema=z.nativeEnum(ApprovalScope);var approvalStateSchema=z.nativeEnum(ApprovalState);var approvalMethodSchema=z.enum(["interactive","implicit","delegation","batch","api"]);var approvalSourceTypeSchema=z.string().min(1);var revocationMethodSchema=z.enum(["interactive","implicit","policy","expiry"]);var approvalCategorySchema=z.enum(["read","write","delete","execute","admin"]);var riskLevelSchema=z.enum(["low","medium","high","critical"]);var approvalContextSchema=z.object({type:z.string().min(1),identifier:z.string().min(1),metadata:z.record(z.string(),z.unknown()).optional()});var MAX_DELEGATION_CHAIN_LINKS=64;var delegationLinkSchema=z.object({delegatorId:z.string().min(1),delegateId:z.string().min(1),purpose:z.string().optional()});var delegationContextSchema=z.object({delegatorId:z.string().min(1),delegateId:z.string().min(1),purpose:z.string().optional(),constraints:z.record(z.string(),z.unknown()).optional(),chain:z.array(delegationLinkSchema).max(MAX_DELEGATION_CHAIN_LINKS).optional()});var approvalGrantorSchema=z.object({source:approvalSourceTypeSchema,identifier:z.string().optional(),displayName:z.string().optional(),method:approvalMethodSchema.optional(),origin:z.string().optional(),delegationContext:delegationContextSchema.optional()});var approvalRevokerSchema=z.object({source:z.string().min(1),identifier:z.string().optional(),displayName:z.string().optional(),method:revocationMethodSchema.optional()});var approvalRecordSchema=z.object({toolId:z.string().min(1),state:approvalStateSchema,scope:approvalScopeSchema,grantedAt:z.number(),expiresAt:z.number().optional(),ttlMs:z.number().optional(),sessionId:z.string().optional(),userId:z.string().optional(),context:approvalContextSchema.optional(),grantedBy:approvalGrantorSchema,approvalChain:z.array(approvalGrantorSchema).optional(),reason:z.string().optional(),metadata:z.record(z.string(),z.unknown()).optional(),revokedAt:z.number().optional(),revokedBy:approvalRevokerSchema.optional(),revocationReason:z.string().optional()});var toolApprovalRequirementSchema=z.object({required:z.boolean().optional(),defaultScope:approvalScopeSchema.optional(),allowedScopes:z.array(approvalScopeSchema).optional(),maxTtlMs:z.number().positive().optional(),alwaysPrompt:z.boolean().optional(),skipApproval:z.boolean().optional(),approvalMessage:z.string().optional(),category:approvalCategorySchema.optional(),riskLevel:riskLevelSchema.optional(),preApprovedContexts:z.array(approvalContextSchema).optional()});function userGrantor(userId,displayName,options){return{source:"user",identifier:userId,displayName,method:options?.method??"interactive",origin:options?.origin}}function policyGrantor(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"implicit"}}function adminGrantor(adminId,displayName,options){return{source:"admin",identifier:adminId,displayName,method:options?.method??"interactive",origin:options?.origin}}function systemGrantor(systemId="system"){return{source:"system",identifier:systemId,method:"implicit"}}function agentGrantor(agentId,delegationContext,displayName){return{source:"agent",identifier:agentId,displayName,method:"delegation",delegationContext}}function apiGrantor(apiKeyPrefix,serviceName){return{source:"api",identifier:apiKeyPrefix,displayName:serviceName,method:"api",origin:"api"}}function oauthGrantor(tokenId,provider){return{source:"oauth",identifier:tokenId,displayName:provider,method:"api",origin:"oauth"}}function testGrantor(){return{source:"test",identifier:"test",method:"implicit"}}function customGrantor(source,identifier,options){return{source,identifier,displayName:options?.displayName,method:options?.method,origin:options?.origin,delegationContext:options?.delegationContext}}function userRevoker(userId,displayName){return{source:"user",identifier:userId,displayName,method:"interactive"}}function adminRevoker(adminId,displayName){return{source:"admin",identifier:adminId,displayName,method:"interactive"}}function expiryRevoker(){return{source:"expiry",method:"expiry"}}function sessionEndRevoker(sessionId){return{source:"session_end",identifier:sessionId,method:"implicit"}}function policyRevoker(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"policy"}}function normalizeGrantor(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function normalizeRevoker(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function delegationDepth(context){return(context.chain?.length??0)+1}function delegationProblem(context,maxDepth){const links=[...context.chain??[],context];if(links.length>maxDepth){return`the delegation chain is ${links.length} deep, and maxDelegationDepth is ${maxDepth}`}const parties=new Set([links[0].delegatorId]);for(let index=0;index<links.length;index++){const link=links[index];if(index>0&&link.delegatorId!==links[index-1].delegateId){return`the delegation chain is broken: ${link.delegatorId} was not delegated to by ${links[index-1].delegatorId}`}if(parties.has(link.delegateId))return`the delegation chain names ${link.delegateId} twice`;parties.add(link.delegateId)}return void 0}function grantorDelegationProblem(grantor,maxDepth){return grantor.delegationContext?delegationProblem(grantor.delegationContext,maxDepth):void 0}function extendDelegation(context,delegateId,options={}){const{delegatorId,delegateId:delegate,purpose}=context;return{delegatorId:delegate,delegateId,...options,chain:[...context.chain??[],{delegatorId,delegateId:delegate,...purpose?{purpose}:{}}]}}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"}import{InternalMcpError,PublicMcpError}from"@frontmcp/sdk";var ApprovalConfigurationError=class extends InternalMcpError{name="ApprovalConfigurationError";constructor(message){super(message,"APPROVAL_CONFIGURATION")}};var ApprovalError=class extends PublicMcpError{constructor(message,code="APPROVAL_REQUIRED",statusCode=403){super(message,code,statusCode);this.name="ApprovalError"}};var ApprovalRequiredError=class extends ApprovalError{constructor(details){super(details.message);this.details=details;this.name="ApprovalRequiredError"}details;toJsonRpcError(){return{code:-32600,message:this.details.message,data:{type:"approval_required",toolId:this.details.toolId,state:this.details.state,options:this.details.approvalOptions}}}};var ApprovalOperationError=class extends ApprovalError{constructor(operation,reason){super(`Approval ${operation} failed: ${reason}`,"APPROVAL_OPERATION_FAILED",400);this.operation=operation;this.reason=reason;this.name="ApprovalOperationError"}operation;reason;toJsonRpcError(){return{code:-32603,message:"Approval operation failed",data:{type:"approval_operation_error",operation:this.operation}}}};var ApprovalScopeNotAllowedError=class extends ApprovalError{constructor(requestedScope,allowedScopes){super(`Approval scope '${requestedScope}' is not allowed for this tool. Allowed scopes: ${allowedScopes.join(", ")}`,"APPROVAL_SCOPE_NOT_ALLOWED",400);this.requestedScope=requestedScope;this.allowedScopes=allowedScopes;this.name="ApprovalScopeNotAllowedError"}requestedScope;allowedScopes;toJsonRpcError(){return{code:-32602,message:this.message,data:{type:"approval_scope_not_allowed",requestedScope:this.requestedScope,allowedScopes:this.allowedScopes}}}};var ApprovalExpiredError=class extends ApprovalError{constructor(toolId,expiredAt){super(`Approval for tool '${toolId}' expired at ${new Date(expiredAt).toISOString()}`,"APPROVAL_EXPIRED",403);this.toolId=toolId;this.expiredAt=expiredAt;this.name="ApprovalExpiredError"}toolId;expiredAt;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"approval_expired",toolId:this.toolId,expiredAt:this.expiredAt}}}};var ChallengeValidationError=class extends ApprovalError{constructor(reason="invalid",message){super(message??`PKCE challenge validation failed: ${reason}`,"CHALLENGE_VALIDATION_FAILED",400);this.reason=reason;this.name="ChallengeValidationError"}reason;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"challenge_validation_error",reason:this.reason}}}};import{randomUUID as randomUUID2,verifyWebhookSignature,webhookSignatureHeaders}from"@frontmcp/utils";import{signingKeyOf,WEBHOOK_ID_HEADER,WEBHOOK_SIGNATURE_HEADER,WEBHOOK_TIMESTAMP_HEADER}from"@frontmcp/utils";function signatureHeaders(signingKey,body,now=Date.now()){const message={id:`msg_${randomUUID2()}`,timestamp:Math.floor(now/1e3),body};return webhookSignatureHeaders(message,[signingKey])}function checkSignature(signingKey,message,now=Date.now()){return verifyWebhookSignature(message,[signingKey],now)}import{Provider,ProviderScope}from"@frontmcp/sdk";import{createMemoryStorage,createNamespacedStorage,createStorage,StorageNotSupportedError}from"@frontmcp/utils";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&&!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&&!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}function auditFieldsOf(record){return{toolId:record.toolId,scope:record.scope,userId:record.userId,context:record.context?{type:record.context.type,identifier:record.context.identifier}:void 0,grantedBy:record.grantedBy,reason:record.reason,expiresAt:record.expiresAt}}var LoggerAuditSink=class{constructor(logger){this.logger=logger}logger;record(event){const fields=Object.fromEntries(Object.entries(event).filter(([,value])=>value!==void 0));this.logger.info(event.toolId?`${event.type} ${event.toolId}`:event.type,fields)}};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 SINGLE_USE_STORAGE_MESSAGE="ApprovalPlugin: an alwaysPrompt tool's approval can be used up by exactly one call only on a storage that deletes a key only while it holds a given value, and this storage cannot. Set the plugin's storage to type 'memory', 'redis', 'upstash', 'vercel-kv' or 'sqlite'.";var TIME_LIMITED_KEY_SEGMENT=`scope:${"time_limited"}`;function encodeKeyPart(part){return part.replace(/%/g,"%25").replace(/:/g,"%3A")}function legacyKeyPart(part){return part}var DEFAULT_MAX_DELEGATION_DEPTH=3;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,maxDelegationDepth:options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH,audit:options.audit}}async initialize(){if(this.initialized){return}if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await createStorage(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}if(this.options.cleanupIntervalSeconds>0){this.cleanupInterval=setInterval(()=>{void this.clearExpiredApprovals()},this.options.cleanupIntervalSeconds*1e3);this.cleanupInterval.unref?.()}this.initialized=true}get revocations(){this.revocationStorage??=createNamespacedStorage(this.storage.root,`${this.storage.prefix.replace(/:$/,"")}-revoked`);return this.revocationStorage}ensureInitialized(){if(!this.initialized){throw new Error("ApprovalStorageStore not initialized. Call initialize() first.")}}buildKey(toolId,owner,encode=encodeKeyPart){const parts=[toolId];if(owner.sessionId)parts.push(`session:${encode(owner.sessionId)}`);if(owner.userId)parts.push(`user:${encode(owner.userId)}`);if(owner.context)parts.push(`ctx:${encode(owner.context.type)}:${encode(owner.context.identifier)}`);if(owner.timeLimited)parts.push(TIME_LIMITED_KEY_SEGMENT);return parts.join(":")}recordKey(options){const{toolId,scope,sessionId,userId,context}=options;return this.buildKey(toolId,{sessionId,userId,context,timeLimited:scope==="time_limited"&&!context})}isOwnedBy(record,owner){const{sessionId,userId,context}=record;return this.buildKey(record.toolId,{sessionId,userId,context})===this.buildKey(record.toolId,{sessionId:owner.sessionId,userId:owner.userId,context:owner.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}isOverDelegated(record){return record.state==="approved"&&grantorDelegationProblem(record.grantedBy,this.options.maxDelegationDepth)!==void 0}callerOwners(sessionId,userId,context){const owners=[{sessionId},{sessionId,timeLimited:true}];if(userId){owners.push({userId},{userId,timeLimited:true},{sessionId,userId},{sessionId,userId,timeLimited:true})}if(context){owners.push({sessionId,context});if(userId)owners.push({sessionId,userId,context})}return owners}callerKeys(toolId,sessionId,userId,context){const owners=new Map;for(const owner of this.callerOwners(sessionId,userId,context)){for(const key of[this.buildKey(toolId,owner),this.buildKey(toolId,owner,legacyKeyPart)]){if(!owners.has(key))owners.set(key,owner)}}return[...owners].map(([key,owner])=>({key,owner}))}async getApprovals(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const{key,owner}of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.storage.get(key));if(record&&record.toolId===toolId&&this.isOwnedBy(record,owner)&&!this.isExpired(record)&&!this.isOverDelegated(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){return this.writeRecord(options,"approved")}async denyApproval(options){return this.writeRecord(options,"denied")}async writeRecord(options,state){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 delegationProblem2=state==="approved"&&grantorDelegationProblem(grantedBy,this.options.maxDelegationDepth);if(delegationProblem2)throw new ApprovalOperationError("grant",delegationProblem2);const record={toolId:options.toolId,state,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});this.options.audit?.record({type:state==="denied"?"approval.denied":"approval.granted",...auditFieldsOf(record)});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 revocable=new Map;for(let i=0;i<keys.length;i++){const value=values[i];const record=this.parseRecord(value);if(value===null||!record||record.toolId!==toolId||record.state==="denied")continue;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)){revocable.set(keys[i],{record,value})}}else if(sessionId&&record.sessionId===sessionId||userId&&record.userId===userId){revocable.set(keys[i],{record,value})}}const revokedAt=Date.now();const revokedBy=normalizeRevoker(options.revokedBy);let revokedAny=false;for(const[key,{record,value}]of revocable){if(!await this.deleteIfUnchanged(key,value))continue;revokedAny=true;const entry={...record,revokedAt,revokedBy,revocationReason:options.reason};await this.revocations.set(key,JSON.stringify(entry),{ttlSeconds:REVOCATION_RETENTION_SECONDS});this.options.audit?.record({type:"approval.revoked",...auditFieldsOf(record),revokedBy,reason:options.reason})}return revokedAny}async consumeApproval(record,sessionId,userId,context){this.ensureInitialized();for(const{key,owner}of this.callerKeys(record.toolId,sessionId,userId,context)){const storedValue=await this.storage.get(key);const stored=this.parseRecord(storedValue);if(storedValue!==null&&stored&&this.isOwnedBy(stored,owner)&&isSameRecord(stored,record)){return this.deleteOnce(key,storedValue)}}return false}async deleteOnce(key,storedValue){try{return await this.storage.deleteIfEquals(key,storedValue)}catch(error){if(!(error instanceof StorageNotSupportedError))throw error;throw new ApprovalConfigurationError(SINGLE_USE_STORAGE_MESSAGE)}}async deleteIfUnchanged(key,storedValue){try{return await this.storage.deleteIfEquals(key,storedValue)}catch(error){if(!(error instanceof StorageNotSupportedError))throw error;if(await this.storage.get(key)!==storedValue)return false;return this.storage.delete(key)}}async getRevocations(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const{key,owner}of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.revocations.get(key));if(record&&record.toolId===toolId&&this.isOwnedBy(record,owner))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 patterns=new Set;for(const storedSessionId of[encodeKeyPart(sessionId),legacyKeyPart(sessionId)]){const escapedSessionId=escapePattern(storedSessionId);patterns.add(`*:session:${escapedSessionId}`);patterns.add(`*:session:${escapedSessionId}:*`)}const keys=new Set;for(const pattern of patterns){for(const key of await this.storage.keys(pattern))keys.add(key)}if(keys.size===0){return 0}const candidates=[...keys];const values=await this.storage.mget(candidates);let count=0;for(let index=0;index<candidates.length;index++){const value=values[index];if(value===null||this.parseRecord(value)?.sessionId!==sessionId)continue;if(await this.deleteIfUnchanged(candidates[index],value))count++}this.options.audit?.record({type:"approval.revoked",count,reason:"session approvals cleared"});return count}async clearExpiredApprovals(){this.ensureInitialized();const now=Date.now();const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);let deleted=0;for(let i=0;i<keys.length;i++){const value=values[i];const approval=this.parseRecord(value);if(value===null||!approval?.expiresAt||approval.expiresAt>now)continue;if(!await this.deleteIfUnchanged(keys[i],value))continue;deleted++;this.options.audit?.record({type:"approval.expired",...auditFieldsOf(approval)})}return deleted}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([Provider({name:"provider:approval:store:storage",description:"Storage-backed approval store (supports Memory, Redis, Vercel KV, Upstash)",scope:ProviderScope.GLOBAL})],ApprovalStorageStore);function createApprovalMemoryStore(options={}){const memoryStorage=createMemoryStorage();return new ApprovalStorageStore({...options,storageInstance:memoryStorage})}var DEFAULT_CALLBACK_PATH="/approval/callback";var DEFAULT_RECHECK_INTERVAL_MS=2e3;var DEFAULT_RECHECK_MAX_ATTEMPTS=5;var MAX_RECHECK_WAIT_MS=12e4;var MIN_SECRET_BYTES=24;var LOOPBACK_HOSTNAMES=new Set(["localhost","127.0.0.1","[::1]"]);var CALLBACK_PATH_PATTERN=/^(\/[A-Za-z0-9._~-]+)+$/;function refuse(message){throw new ApprovalConfigurationError(`ApprovalPlugin ${message}`)}function setOptions(values){return Object.entries(values).filter(([,value])=>value!==void 0).map(([name2])=>name2)}function checkOutboundUrl(option,url){let parsed;try{parsed=new URL(url)}catch{return refuse(`\`${option}\` is not a URL`)}if(parsed.username||parsed.password){refuse(`\`${option}\` must not carry credentials; use the auth options instead`)}const loopbackInDevelopment=parsed.protocol==="http:"&&LOOPBACK_HOSTNAMES.has(parsed.hostname)&&!isProduction();if(parsed.protocol!=="https:"&&!loopbackInDevelopment){refuse(`\`${option}\` must be an https:// URL (http://localhost is accepted when NODE_ENV is not production), got ${parsed.protocol}//${parsed.host}`)}return parsed.toString()}function checkSecret(option,secret){if(secret===void 0||secret.trim()===""){return refuse(`needs \`${option}\` to sign its requests and verify callbacks`)}let signingKey;try{signingKey=signingKeyOf(secret)}catch{return refuse(`\`${option}\` starts with whsec_ but the rest is not base64`)}if(signingKey.length<MIN_SECRET_BYTES){refuse(`\`${option}\` must be at least ${MIN_SECRET_BYTES} bytes (32 characters or more is recommended)`)}return signingKey}function checkWholeNumber(option,value,min,max){if(!Number.isInteger(value)||value<min||value>max){refuse(`\`${option}\` must be a whole number from ${min} to ${max}, got ${value}`)}return value}function resolveWebhook(options){const{url,secret,includeJwt,callbackPath,challengeTtl}=options.webhook??{};const external=setOptions({url,secret,includeJwt,callbackPath}).map(name2=>`\`webhook.${name2}\``);if(external.length===0)return void 0;if(options.mode!=="webhook")refuse(`${external.join(", ")} need \`mode: 'webhook'\``);if(url===void 0)refuse(`${external.join(", ")} need \`webhook.url\``);const path=callbackPath??DEFAULT_CALLBACK_PATH;if(!CALLBACK_PATH_PATTERN.test(path)||path.length>256){refuse(`\`webhook.callbackPath\` must be a path such as ${DEFAULT_CALLBACK_PATH}, got ${JSON.stringify(path)}`)}return{url:checkOutboundUrl("webhook.url",url),signingKey:checkSecret("webhook.secret",secret),includeJwt:includeJwt===true,callbackPath:path,challengeTtlSeconds:challengeTtl??300}}function resolveRecheck(options){if(options.recheck===void 0)return void 0;const{url,auth="none",token,headers,secret,interval,maxAttempts}=options.recheck;if(options.mode==="webhook")refuse("`recheck` needs `mode: 'recheck'`");if(url===void 0){const others=setOptions({auth:options.recheck.auth,token,headers,secret,interval,maxAttempts});refuse(`${others.map(name2=>`\`recheck.${name2}\``).join(", ")||"`recheck`"} need \`recheck.url\``)}if(!["jwt","bearer","none","custom"].includes(auth)){refuse(`\`recheck.auth\` must be 'jwt', 'bearer', 'none' or 'custom', got ${JSON.stringify(auth)}`)}if(auth==="bearer"&&!token)refuse("`recheck.auth: 'bearer'` needs `recheck.token`");if(auth!=="bearer"&&token!==void 0)refuse("`recheck.token` is only sent with `recheck.auth: 'bearer'`");if(auth==="custom"&&typeof headers!=="function")refuse("`recheck.auth: 'custom'` needs a `recheck.headers` function");if(auth!=="custom"&&headers!==void 0)refuse("`recheck.headers` is only used with `recheck.auth: 'custom'`");const intervalMs=checkWholeNumber("recheck.interval",interval??DEFAULT_RECHECK_INTERVAL_MS,100,6e4);const attempts=checkWholeNumber("recheck.maxAttempts",maxAttempts??DEFAULT_RECHECK_MAX_ATTEMPTS,1,60);if(intervalMs*(attempts-1)>MAX_RECHECK_WAIT_MS){refuse(`would keep a call waiting ${intervalMs*(attempts-1)} ms: \`recheck.interval\` \xD7 (\`recheck.maxAttempts\` \u2212 1) must be ${MAX_RECHECK_WAIT_MS} ms or less`)}return{url:checkOutboundUrl("recheck.url",url),auth,token,headers,signingKey:secret===void 0?void 0:checkSecret("recheck.secret",secret),intervalMs,maxAttempts:attempts}}function resolveExternalApproval(options){return{webhook:resolveWebhook(options),recheck:resolveRecheck(options)}}function resolveMaxDelegationDepth(options){const depth=options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH;return checkWholeNumber("maxDelegationDepth",depth,0,MAX_DELEGATION_CHAIN_LINKS)}var ApprovalStoreToken=Symbol.for("plugin:approval:store");var ApprovalServiceToken=Symbol.for("plugin:approval:service");var ChallengeServiceToken=Symbol.for("plugin:approval:challenge-service");var ExternalApproverToken=Symbol.for("plugin:approval:external-approver");var ApprovalAuditToken=Symbol.for("plugin:approval:audit");import"reflect-metadata";import{z as z2}from"@frontmcp/lazy-zod";import{enforceGlobalRateLimit,enforceIpFilter,Flow,FlowBase,FlowHooksOf,httpInputSchema,HttpJsonSchema,normalizeEntryPrefix,normalizeScopeBase}from"@frontmcp/sdk";var plan={pre:["checkIpFilter","acquireQuota"],execute:["handleCallback"]};var approvalCallbackStateSchema=z2.object({});var callbackRoutes=new WeakMap;var name="approval:webhook-callback";var{Stage}=FlowHooksOf(name);var ApprovalCallbackFlow=class extends FlowBase{static canActivate(request,scope){return callbackRoutes.get(scope)?.has(request.path)??false}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async handleCallback(){const request=this.rawInput.request;const handler=callbackRoutes.get(this.scope)?.get(request.path);if(!handler)return this.next();this.respond(await handler.handleCallback({headers:request.headers,bodyBytes:request.bodyBytes}))}};__decorateClass([Stage("checkIpFilter")],ApprovalCallbackFlow.prototype,"checkIpFilter",1);__decorateClass([Stage("acquireQuota")],ApprovalCallbackFlow.prototype,"acquireQuota",1);__decorateClass([Stage("handleCallback")],ApprovalCallbackFlow.prototype,"handleCallback",1);ApprovalCallbackFlow=__decorateClass([Flow({name,plan,access:"public",inputSchema:httpInputSchema,outputSchema:HttpJsonSchema,middleware:{method:"POST"}})],ApprovalCallbackFlow);function mcpPaths(scope){const base=`${normalizeEntryPrefix(scope.entryPath)}${normalizeScopeBase(scope.routeBase)}`;return[base||"/",`${base}/sse`,`${base}/message`,`${base}/server-card`]}async function serveApprovalCallback(scope,path,handler){if(mcpPaths(scope).includes(path)||/^\/(oauth|\.well-known)(\/|$)/.test(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is a path the server reserves`)}let routes=callbackRoutes.get(scope);const firstRoute=!routes;routes??=new Map;if(routes.has(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is served by another ApprovalPlugin; give each its own`)}routes.set(path,handler);callbackRoutes.set(scope,routes);if(firstRoute)await scope.registryFlows(ApprovalCallbackFlow)}import{sha256Hex}from"@frontmcp/utils";function pendingRequestKey(subject){return sha256Hex(JSON.stringify([subject.toolId,subject.sessionId,subject.userId??null]))}function grantTarget(scope,subject){const{sessionId,userId,context}=subject;switch(scope){case"session":return{sessionId};case"user":return userId?{userId}:void 0;case"time_limited":return{sessionId,userId};case"context_specific":return context?{context,sessionId,userId}:void 0;default:return void 0}}var ApprovalDecisionRecorder=class{constructor(store,requirementOf,logger){this.store=store;this.requirementOf=requirementOf;this.logger=logger}store;requirementOf;logger;async approve(subject,decision,origin){const requirement=this.requirementOf(subject.toolId);const scope=decision.scope??requirement?.defaultScope??"session";const target=grantTarget(scope,subject);if(!target){this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: no ${scope} to grant it to`);return false}try{const ttlMs=checkGrantAgainstPolicy(subject.toolId,scope,decision.ttlMs,requirement);await this.store.grantApproval({toolId:subject.toolId,scope,ttlMs,...target,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason});return true}catch(error){if(!(error instanceof ApprovalError))throw error;this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: ${error.message}`);return false}}async deny(subject,decision,ttlMs,origin){if(!this.store.denyApproval){this.logger.warn(`ApprovalPlugin: the ${origin} denial of ${subject.toolId} was not recorded: the store keeps no denials`);return}await this.store.denyApproval({toolId:subject.toolId,scope:"session",ttlMs,sessionId:subject.sessionId,userId:subject.userId,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason})}};import{z as z3}from"@frontmcp/lazy-zod";import{isRedirectResponse}from"@frontmcp/utils";var OUTBOUND_TIMEOUT_MS=1e4;var OUTBOUND_MAX_RESPONSE_BYTES=64*1024;var OutboundRequestError=class extends Error{name="OutboundRequestError"};async function readBounded(response){const declaredLength=Number(response.headers.get("content-length")??0);if(declaredLength>OUTBOUND_MAX_RESPONSE_BYTES){await response.body?.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}if(!response.body)return"";const reader=response.body.getReader();const chunks=[];let received2=0;for(;;){const{done,value}=await reader.read();if(done)break;received2+=value.byteLength;if(received2>OUTBOUND_MAX_RESPONSE_BYTES){await reader.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}chunks.push(value)}const bytes=new Uint8Array(received2);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength}return new TextDecoder().decode(bytes)}function failureCode(error){const cause=error?.cause;return typeof cause?.code==="string"?cause.code:error instanceof Error?error.name:"unknown error"}async function postJson(request){const timeoutMs=request.timeoutMs??OUTBOUND_TIMEOUT_MS;const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeoutMs);const cancel=()=>controller.abort();request.signal?.addEventListener("abort",cancel,{once:true});try{const response=await fetch(request.url,{method:"POST",headers:{...request.headers,"content-type":"application/json",accept:"application/json"},body:request.body,redirect:"manual",signal:controller.signal});if(isRedirectResponse(response)){await response.body?.cancel();throw new OutboundRequestError(`answered with a redirect (${response.status}), which is not followed`)}return{status:response.status,body:await readBounded(response)}}catch(error){if(error instanceof OutboundRequestError)throw error;if(request.signal?.aborted)throw new OutboundRequestError("the tool call was cancelled");if(controller.signal.aborted)throw new OutboundRequestError(`no answer within ${timeoutMs} ms`);throw new OutboundRequestError(`the request failed (${failureCode(error)})`)}finally{clearTimeout(timer);request.signal?.removeEventListener("abort",cancel)}}function originOf(url){return new URL(url).origin}var recheckAnswerSchema=z3.object({approved:z3.boolean(),pending:z3.boolean().optional(),scope:approvalScopeSchema.optional(),ttlMs:z3.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),denialReason:z3.string().max(1e3).optional()});function wait(ms,signal){if(signal?.aborted)return Promise.resolve(false);return new Promise(resolve=>{const done=completed=>{clearTimeout(timer);signal?.removeEventListener("abort",cancelled);resolve(completed)};const cancelled=()=>done(false);const timer=setTimeout(()=>done(true),ms);signal?.addEventListener("abort",cancelled,{once:true})})}var RecheckApprover=class{constructor(recheck,dependencies,logger){this.recheck=recheck;this.dependencies=dependencies;this.logger=logger}recheck;dependencies;logger;via="recheck";async requestApproval(call){for(let attempt=1;attempt<=this.recheck.maxAttempts;attempt++){if(attempt>1&&!await wait(this.recheck.intervalMs,call.signal))return"pending";let answer;try{answer=await this.poll(call,attempt)}catch(error){if(!(error instanceof OutboundRequestError))throw error;this.logger.warn(`ApprovalPlugin: polling ${originOf(this.recheck.url)} for ${call.toolId} failed: ${error.message}`);return"pending"}if(!answer)return"pending";if(answer.approved)return await this.approve(call,answer)?"approved":"pending";if(!answer.pending)return"denied"}return"pending"}async approve(call,answer){if(call.requirement.alwaysPrompt)return true;return this.dependencies.decisions.approve(call,{scope:answer.scope,ttlMs:answer.ttlMs,decidedBy:answer.grantedBy},"recheck")}async poll(call,attempt){const{requirement}=call;const request={type:"approval.status",requestId:pendingRequestKey(call),attempt,toolId:call.toolId,toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,approvalMessage:requirement.approvalMessage,requestedScope:requirement.defaultScope??"session",allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,timestamp:Date.now()};const authorization=await this.authorization(call,request);if(!authorization)return void 0;const body=JSON.stringify(request);const signing=this.recheck.signingKey?signatureHeaders(this.recheck.signingKey,body):{};const answer=await postJson({url:this.recheck.url,body,headers:{...authorization,...signing},signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);try{return recheckAnswerSchema.parse(JSON.parse(answer.body))}catch{throw new OutboundRequestError("answered with something other than { approved, pending?, scope?, ttlMs?, ... }")}}async authorization(call,request){switch(this.recheck.auth){case"jwt":if(!call.accessToken){this.logger.verbose(`ApprovalPlugin: not polling for ${call.toolId}: the call has no token to forward`);return void 0}return{authorization:`Bearer ${call.accessToken}`};case"bearer":return{authorization:`Bearer ${this.recheck.token}`};case"custom":return{...await this.recheck.headers?.(request)};default:return{}}}};import{z as z4}from"@frontmcp/lazy-zod";import{getPinnedPublicUrl,httpRespond}from"@frontmcp/sdk";var MAX_CALLBACK_BYTES=16*1024;var callbackSchema=z4.object({codeVerifier:z4.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),approved:z4.boolean(),scope:approvalScopeSchema.optional(),ttlMs:z4.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),reason:z4.string().max(1e3).optional()});function refusal(status,error,description){return httpRespond.json({error,error_description:description},{status})}function headerOf(headers,name2){const value=headers[name2];return typeof value==="string"?value:void 0}function received(){return httpRespond.json({status:"received"},{status:202})}var WebhookApprover=class{constructor(webhook,dependencies,logger){this.webhook=webhook;this.dependencies=dependencies;this.logger=logger}webhook;dependencies;logger;via="webhook";get challenges(){return this.dependencies.challenges}async requestApproval(call){const pendingKey=pendingRequestKey(call);const ttlSeconds=this.webhook.challengeTtlSeconds;if(!await this.challenges.claimPendingRequest(pendingKey,ttlSeconds))return"pending";const{requirement}=call;const requestedScope=requirement.defaultScope??"session";const requestInfo={toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,customMessage:requirement.approvalMessage};const{codeVerifier,codeChallenge,expiresAt}=await this.challenges.createChallenge({toolId:call.toolId,sessionId:call.sessionId,userId:call.userId,context:call.context,requestedScope,requestInfo,ttlSeconds});const publicUrl=getPinnedPublicUrl();const payload={type:"approval.requested",codeChallenge,codeVerifier,toolId:call.toolId,toolName:call.toolName,category:requestInfo.category,riskLevel:requestInfo.riskLevel,approvalMessage:requestInfo.customMessage,requestedScope,allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,callbackPath:this.webhook.callbackPath,callbackUrl:publicUrl?`${publicUrl}${this.webhook.callbackPath}`:void 0,expiresAt,timestamp:Date.now(),jwt:this.webhook.includeJwt?call.accessToken:void 0};const body=JSON.stringify(payload);try{const answer=await postJson({url:this.webhook.url,body,headers:signatureHeaders(this.webhook.signingKey,body),signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);await this.challenges.markWebhookSent(codeChallenge)}catch(error){if(!(error instanceof OutboundRequestError))throw error;await this.challenges.deleteChallenge(codeChallenge);await this.challenges.releasePendingRequest(pendingKey);this.logger.warn(`ApprovalPlugin: the approval request for ${call.toolId} to ${originOf(this.webhook.url)} failed: ${error.message}`)}return"pending"}async handleCallback(request){const{bodyBytes}=request;if(!bodyBytes||bodyBytes.byteLength===0){return refusal(400,"invalid_request","the body must be the decision, as JSON")}if(bodyBytes.byteLength>MAX_CALLBACK_BYTES){return refusal(413,"payload_too_large",`the body must be ${MAX_CALLBACK_BYTES} bytes or less`)}const body=new TextDecoder().decode(bodyBytes);const signature=checkSignature(this.webhook.signingKey,{id:headerOf(request.headers,WEBHOOK_ID_HEADER),timestamp:headerOf(request.headers,WEBHOOK_TIMESTAMP_HEADER),signature:headerOf(request.headers,WEBHOOK_SIGNATURE_HEADER),body});if(signature!=="valid"){this.logger.warn(`ApprovalPlugin: refused an approval callback: signature ${signature}`);return refusal(401,"invalid_signature","the callback must be signed with webhook.secret, within five minutes")}let decision;try{decision=callbackSchema.parse(JSON.parse(body))}catch{return refusal(400,"invalid_request","the body must be { codeVerifier, approved, scope?, ttlMs?, grantedBy?, reason? }")}const pending=await this.challenges.consume(decision.codeVerifier);if(!pending)return received();await this.challenges.releasePendingRequest(pendingRequestKey(pending));const subject={toolId:pending.toolId,sessionId:pending.sessionId,userId:pending.userId,context:pending.context};const outcome={scope:decision.scope,ttlMs:decision.ttlMs,decidedBy:decision.grantedBy,reason:decision.reason};if(decision.approved){await this.dependencies.decisions.approve(subject,outcome,"webhook")}else{await this.dependencies.decisions.deny(subject,outcome,decision.ttlMs??this.webhook.challengeTtlSeconds*1e3,"webhook")}return received()}};import{DynamicPlugin,isEntryGatedBy,Plugin,ProviderNotAvailableError,ScopeEntry,ToolHook}from"@frontmcp/sdk";var decidedCalls=new WeakSet;var ApprovalCheckPlugin=class extends DynamicPlugin{async checkApproval(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;const metadata=tool.metadata;const approvalConfig=resolveApprovalRequirement(metadata["approval"]);if(!approvalConfig.required){return}if(approvalConfig.skipApproval){return}if(decidedCalls.has(toolContext))return;await this.enforceApproval(flowCtx,tool,toolContext,approvalConfig,this.coveringStores(tool));decidedCalls.add(toolContext)}async enforceApproval(flowCtx,tool,toolContext,approvalConfig,stores){const callerContext=toolContext.tryGetContext?.();const{sessionId,userId}=resolveApprovalIdentity(callerContext);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);const requested=(state,via)=>this.optional(ApprovalAuditToken)?.record({type:"approval.requested",toolId:tool.fullName,userId,context:currentContext&&{type:currentContext.type,identifier:currentContext.identifier},state,via});if(records.some(record=>record.state==="denied")){requested("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}const external=isUnidentifiedSession(sessionId)?void 0:this.optional(ExternalApproverToken);const outcome=await external?.requestApproval({toolId:tool.fullName,toolName:tool.name,sessionId,userId,context:currentContext,requirement:approvalConfig,accessToken:callerContext?.authInfo?.token,signal:toolContext.signal});const expiredApproval=approved.find(record=>isApprovalExpired(record,approvalConfig,now));const callState=outcome==="approved"||outcome==="denied"?outcome:expiredApproval?"expired":"pending";requested(callState,external?.via);if(outcome==="approved")return;if(outcome==="denied"){throw new ApprovalRequiredError({toolId:tool.fullName,state:"denied",message:`Tool "${tool.fullName}" execution denied.`})}await this.handleApprovalRequired(flowCtx,approvalConfig,expiredApproval??approved[0])}optional(token){try{return this.get(token)}catch(error){if(error instanceof ProviderNotAvailableError)return void 0;throw error}}coveringStores(tool){const stores=new Set([this.get(ApprovalStoreToken)]);let scope;try{scope=this.get(ScopeEntry)}catch{scope=void 0}if(!scope?.hooks)return[...stores];for(const hook of scope.hooks.getFlowHooks("tools:call-tool")){const gate=hook.metadata.target;if(gate instanceof ApprovalCheckPlugin&&isEntryGatedBy(scope,{tool},gate)){stores.add(gate.get(ApprovalStoreToken))}}return[...stores]}async consumeApproval(store,record,sessionId,userId,context){if(store.consumeApproval){return store.consumeApproval(record,sessionId,userId,context)}return store.revokeApproval({toolId:record.toolId,sessionId,userId,revokedBy:"system",reason:"Used by a call of an alwaysPrompt tool"})}async readApprovals(store,toolId,sessionId,userId,context){if(store.getApprovals){return store.getApprovals(toolId,sessionId,userId,context)}const record=await store.getApproval(toolId,sessionId,userId,context);return record?[record]:[]}getCurrentContext(flowCtx){const ctx=flowCtx.state.toolContext?.tryGetContext?.();const sessionContext=ctx?.authInfo?.extra?.["approvalContext"];return this.isApprovalContext(sessionContext)?sessionContext:void 0}isApprovalContext(value){return typeof value==="object"&&value!==null&&"type"in value&&"identifier"in value&&typeof value.type==="string"&&typeof value.identifier==="string"}isPreApprovedContext(config,currentContext){if(!currentContext||!config.preApprovedContexts?.length){return false}return config.preApprovedContexts.some(preApproved=>preApproved.type===currentContext.type&&preApproved.identifier===currentContext.identifier)}async handleApprovalRequired(flowCtx,config,existingApproval){const{tool}=flowCtx.state;const message=config.approvalMessage??`Tool "${tool?.fullName}" requires approval to execute. Allow?`;const isExpiredApproval=existingApproval?isApprovalExpired(existingApproval,config,Date.now()):false;throw new ApprovalRequiredError({toolId:tool?.fullName??"unknown",state:isExpiredApproval?"expired":"pending",message,approvalOptions:{allowedScopes:config.allowedScopes,defaultScope:config.defaultScope,maxTtlMs:config.maxTtlMs,category:config.category,riskLevel:config.riskLevel}})}};__decorateClass([ToolHook.Will("execute",{priority:100,appliesTo:"uncovered-apps"})],ApprovalCheckPlugin.prototype,"checkApproval",1);ApprovalCheckPlugin=__decorateClass([Plugin({name:"approval:check",description:"Checks tool approval state before execution",enforcesMetadata:["approval"]})],ApprovalCheckPlugin);import{isAnonymousSubject,Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";var ApprovalService=class{constructor(store,sessionId,userId,requirementOf=()=>void 0){this.store=store;this.sessionId=sessionId;this.userId=userId;this.requirementOf=requirementOf}store;sessionId;userId;requirementOf;checkGrant(toolId,scope,ttlMs){return checkGrantAgainstPolicy(toolId,scope,ttlMs,this.requirementOf(toolId))}get signedInUserId(){return this.userId&&!isAnonymousSubject(this.userId)?this.userId:void 0}defaultGrantor(){const userId=this.signedInUserId;return userId?userGrantor(userId,void 0,{method:"implicit"}):{source:"user",method:"implicit"}}defaultRevoker(){const userId=this.signedInUserId;return userId?{source:"user",identifier:userId,method:"implicit"}:{source:"user",method:"implicit"}}async isApproved(toolId,context){const requirement=this.requirementOf(toolId);if(!requirement||!this.store.getApprovals){return this.store.isApproved(toolId,this.sessionId,this.userId,context)}const records=await this.store.getApprovals(toolId,this.sessionId,this.userId,context);if(records.some(record=>record.state==="denied"))return false;const now=Date.now();return records.some(record=>isApprovalUsable(record,requirement,now))}async getApproval(toolId){return this.store.getApproval(toolId,this.sessionId,this.userId)}async getSessionApprovals(){return this.store.queryApprovals({sessionId:this.sessionId,states:["approved"],includeExpired:false})}async getUserApprovals(){if(!this.userId)return[];return this.store.queryApprovals({userId:this.userId,scope:"user",states:["approved"],includeExpired:false})}async queryApprovals(query){const records=await this.store.queryApprovals(query);return records.filter(record=>record.sessionId===this.sessionId||this.userId!==void 0&&record.userId===this.userId)}async getRevocations(toolId){return await this.store.getRevocations?.(toolId,this.sessionId,this.userId)??[]}async grantSessionApproval(toolId,options={}){const ttlMs=this.checkGrant(toolId,"session");return this.store.grantApproval({toolId,scope:"session",ttlMs,sessionId:this.sessionId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantUserApproval(toolId,options={}){if(!this.userId){throw new Error("Cannot grant user approval without userId")}const ttlMs=this.checkGrant(toolId,"user");return this.store.grantApproval({toolId,scope:"user",ttlMs,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantTimeLimitedApproval(toolId,ttlMs,options={}){this.checkGrant(toolId,"time_limited",ttlMs);return this.store.grantApproval({toolId,scope:"time_limited",ttlMs,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantContextApproval(toolId,context,options={}){const ttlMs=this.checkGrant(toolId,"context_specific");return this.store.grantApproval({toolId,scope:"context_specific",ttlMs,context,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async revokeApproval(toolId,options={}){return this.store.revokeApproval({toolId,sessionId:this.sessionId,userId:this.userId,revokedBy:options.revokedBy??this.defaultRevoker(),reason:options.reason})}async clearSessionApprovals(){return this.store.clearSessionApprovals(this.sessionId)}};ApprovalService=__decorateClass([Provider2({name:"provider:approval:service",description:"Service for managing tool approvals",scope:ProviderScope2.CONTEXT})],ApprovalService);function createApprovalService(store,sessionId,userId,requirementOf){return new ApprovalService(store,sessionId,userId,requirementOf)}import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{createMemoryStorage as createMemoryStorage2,createStorage as createStorage2,generateCodeChallenge,generatePkcePair,randomUUID as randomUUID3,StorageNotSupportedError as StorageNotSupportedError2}from"@frontmcp/utils";var PENDING_REQUEST_PREFIX="pending:";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 createStorage2(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}this.initialized=true}ensureInitialized(){if(!this.initialized){throw new Error("ChallengeService not initialized. Call initialize() first.")}}async createChallenge(options){this.ensureInitialized();const{codeVerifier,codeChallenge}=generatePkcePair();const now=Date.now();const ttlSeconds=options.ttlSeconds??this.options.defaultTtlSeconds;const expiresAt=now+ttlSeconds*1e3;const record={toolId:options.toolId,sessionId:options.sessionId,userId:options.userId,context:options.context,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){const consumed=await this.take(codeVerifier);if(!consumed){throw new ChallengeValidationError("not_found","Invalid or expired challenge")}if(Date.now()>consumed.expiresAt){throw new ChallengeValidationError("expired","Challenge expired")}return consumed}async consume(codeVerifier){const consumed=await this.take(codeVerifier);return consumed&&Date.now()<=consumed.expiresAt?consumed:void 0}async take(codeVerifier){this.ensureInitialized();const codeChallenge=generateCodeChallenge(codeVerifier);const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return void 0;if(!await this.deleteIfUnchanged(codeChallenge,recordJson))return void 0;return JSON.parse(recordJson)}async deleteIfUnchanged(key,value){try{return await this.storage.deleteIfEquals(key,value)}catch(error){if(!(error instanceof StorageNotSupportedError2))throw error;return this.storage.delete(key)}}async claimPendingRequest(key,ttlSeconds=this.options.defaultTtlSeconds){this.ensureInitialized();const claim=randomUUID3();const pendingKey=`${PENDING_REQUEST_PREFIX}${key}`;try{await this.storage.set(pendingKey,claim,{ttlSeconds,ifNotExists:true})}catch(error){if(!(error instanceof StorageNotSupportedError2))throw error;if(await this.storage.exists(pendingKey))return false;await this.storage.set(pendingKey,claim,{ttlSeconds})}return await this.storage.get(pendingKey)===claim}async releasePendingRequest(key){this.ensureInitialized();await this.storage.delete(`${PENDING_REQUEST_PREFIX}${key}`)}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);const updatedJson=JSON.stringify(record);try{await this.storage.set(codeChallenge,updatedJson,{ttlSeconds,ifExists:true})}catch(error){if(!(error instanceof StorageNotSupportedError2))throw error;return false}return await this.storage.get(codeChallenge)===updatedJson}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([Provider3({name:"provider:approval:challenge-service",description:"PKCE challenge service for webhook approval flows",scope:ProviderScope3.GLOBAL})],ChallengeService);function createMemoryChallengeService(options={}){const memoryStorage=createMemoryStorage2();return new ChallengeService({...options,storageInstance:memoryStorage})}function toolRequirementLookup(scope){return 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)}}function externalApproverProvider(external){const{webhook,recheck}=external;if(!webhook&&!recheck)return void 0;return{name:"approval:external-approver",provide:ExternalApproverToken,inject:()=>[ProviderRegistry,ScopeEntry2],useFactory:async(providers,scope)=>{const logger=scope.logger.child("ApprovalPlugin");const requirementOf=toolRequirementLookup(scope);const dependencies={get challenges(){return providers.get(ChallengeServiceToken)},get decisions(){return new ApprovalDecisionRecorder(providers.get(ApprovalStoreToken),requirementOf,logger)}};if(!webhook)return new RecheckApprover(recheck,dependencies,logger);const approver=new WebhookApprover(webhook,dependencies,logger);await serveApprovalCallback(scope,webhook.callbackPath,approver);return approver}}}var ApprovalPlugin=class extends DynamicPlugin2{options;constructor(options={}){super();this.options={...ApprovalPlugin.defaultOptions,...options}}};__publicField(ApprovalPlugin,"defaultOptions",{namespace:"approval",mode:"recheck",enableAudit:false,maxDelegationDepth:DEFAULT_MAX_DELEGATION_DEPTH,cleanupIntervalSeconds:60});__publicField(ApprovalPlugin,"browserStores",({storage,storageInstance})=>{const type=storageInstance?void 0:storage?.type;return[{plugin:"ApprovalPlugin",option:type==="redis"||type==="sqlite"?`storage: { type: '${type}' }`:void 0,memory:"storage: { type: 'memory' }"}]});__publicField(ApprovalPlugin,"dynamicProviders",options=>{const providers=[];const config={...ApprovalPlugin.defaultOptions,...options};const external=resolveExternalApproval(config);const maxDelegationDepth=resolveMaxDelegationDepth(config);providers.push(storeProvider({name:"approval:store",provide:ApprovalStoreToken,inject:()=>[ScopeEntry2],useFactory:async scope=>{const store=new ApprovalStorageStore({storage:config.storage,storageInstance:config.storageInstance,namespace:config.namespace,cleanupIntervalSeconds:config.cleanupIntervalSeconds,maxDelegationDepth,audit:config.enableAudit?new LoggerAuditSink(scope.logger.child("ApprovalAudit")):void 0});await store.initialize();return store}}));if(config.mode==="webhook"){providers.push(storeProvider({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}}))}const externalApprover=externalApproverProvider(external);if(externalApprover)providers.push(externalApprover);if(config.enableAudit){providers.push({name:"approval:audit",provide:ApprovalAuditToken,inject:()=>[ScopeEntry2],useFactory:scope=>new LoggerAuditSink(scope.logger.child("ApprovalAudit"))})}providers.push({name:"approval:service",provide:ApprovalServiceToken,scope:ProviderScope4.CONTEXT,inject:()=>[ApprovalStoreToken,FRONTMCP_CONTEXT,ScopeEntry2],useFactory:(store,ctx,scope)=>{const{sessionId,userId}=resolveApprovalIdentity(ctx);return createApprovalService(store,sessionId,userId,toolRequirementLookup(scope))}});return providers});ApprovalPlugin=__decorateClass([Plugin2({name:"approval",description:"Tool authorization workflow with PKCE webhook security",plugins:[ApprovalCheckPlugin],contextExtensions:[{property:"approval",token:ApprovalServiceToken,errorMessage:"ApprovalPlugin is not installed. Add ApprovalPlugin.init() to your plugins array."}]})],ApprovalPlugin);var installed=false;function installApprovalContextExtension(){if(installed)return;const{ExecutionContextBase}=__require("@frontmcp/sdk");Object.defineProperty(ExecutionContextBase.prototype,"approval",{get:function(){return this.get(ApprovalServiceToken)},configurable:true,enumerable:false});installed=true}export{ApprovalCheckPlugin,ApprovalConfigurationError,ApprovalError,ApprovalExpiredError,ApprovalOperationError,ApprovalPlugin,ApprovalPlugin as ApprovalPluginClass,ApprovalRequiredError,ApprovalScope,ApprovalScopeNotAllowedError,ApprovalService,ApprovalServiceToken,ApprovalState,ApprovalStorageStore,ApprovalStoreToken,ChallengeService,ChallengeServiceToken,ChallengeValidationError,adminGrantor,adminRevoker,agentGrantor,apiGrantor,createApprovalMemoryStore,createApprovalService,createMemoryChallengeService,customGrantor,delegationDepth,delegationProblem,expiryRevoker,extendDelegation,installApprovalContextExtension,isApiGrantor,isAutoGrantor,isDelegatedGrantor,isGrantorSource,isHumanGrantor,normalizeGrantor,normalizeRevoker,oauthGrantor,policyGrantor,policyRevoker,sessionEndRevoker,systemGrantor,testGrantor,userGrantor,userRevoker};
package/esm/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontmcp/plugin-approval",
3
- "version": "1.12.0",
3
+ "version": "1.12.1",
4
4
  "description": "Approval plugin for FrontMCP: refuses to run marked tools until an approval is recorded for the caller",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "license": "Apache-2.0",
@@ -50,13 +50,13 @@
50
50
  }
51
51
  },
52
52
  "dependencies": {
53
- "@frontmcp/utils": "1.12.0",
53
+ "@frontmcp/utils": "1.12.1",
54
54
  "ioredis": "^5.8.0",
55
55
  "reflect-metadata": "^0.2.2"
56
56
  },
57
57
  "peerDependencies": {
58
- "@frontmcp/lazy-zod": "1.12.0",
59
- "@frontmcp/sdk": "1.12.0",
58
+ "@frontmcp/lazy-zod": "1.12.1",
59
+ "@frontmcp/sdk": "1.12.1",
60
60
  "@vercel/kv": "^2.0.0 || ^3.0.0"
61
61
  },
62
62
  "peerDependenciesMeta": {
@@ -65,7 +65,7 @@
65
65
  }
66
66
  },
67
67
  "devDependencies": {
68
- "@frontmcp/sdk": "1.12.0",
68
+ "@frontmcp/sdk": "1.12.1",
69
69
  "reflect-metadata": "^0.2.2"
70
70
  }
71
71
  }
package/index.js CHANGED
@@ -1 +1 @@
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 name2 in all)__defProp(target,name2,{get:all[name2],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,ApprovalConfigurationError:()=>ApprovalConfigurationError,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,delegationDepth:()=>delegationDepth,delegationProblem:()=>delegationProblem,expiryRevoker:()=>expiryRevoker,extendDelegation:()=>extendDelegation,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_sdk8=require("@frontmcp/sdk");var import_utils=require("@frontmcp/utils");var UNIDENTIFIED_SESSION_PREFIX="unidentified:";function isUnidentifiedSession(sessionId){return sessionId.startsWith(UNIDENTIFIED_SESSION_PREFIX)}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_SESSION_PREFIX}${(0,import_utils.randomUUID)()}`,userId}}var import_utils5=require("@frontmcp/utils");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||{});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 MAX_DELEGATION_CHAIN_LINKS=64;var delegationLinkSchema=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()});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(),chain:import_lazy_zod.z.array(delegationLinkSchema).max(MAX_DELEGATION_CHAIN_LINKS).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 delegationDepth(context){return(context.chain?.length??0)+1}function delegationProblem(context,maxDepth){const links=[...context.chain??[],context];if(links.length>maxDepth){return`the delegation chain is ${links.length} deep, and maxDelegationDepth is ${maxDepth}`}const parties=new Set([links[0].delegatorId]);for(let index=0;index<links.length;index++){const link=links[index];if(index>0&&link.delegatorId!==links[index-1].delegateId){return`the delegation chain is broken: ${link.delegatorId} was not delegated to by ${links[index-1].delegatorId}`}if(parties.has(link.delegateId))return`the delegation chain names ${link.delegateId} twice`;parties.add(link.delegateId)}return void 0}function grantorDelegationProblem(grantor,maxDepth){return grantor.delegationContext?delegationProblem(grantor.delegationContext,maxDepth):void 0}function extendDelegation(context,delegateId,options={}){const{delegatorId,delegateId:delegate,purpose}=context;return{delegatorId:delegate,delegateId,...options,chain:[...context.chain??[],{delegatorId,delegateId:delegate,...purpose?{purpose}:{}}]}}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 import_sdk=require("@frontmcp/sdk");var ApprovalConfigurationError=class extends import_sdk.InternalMcpError{name="ApprovalConfigurationError";constructor(message){super(message,"APPROVAL_CONFIGURATION")}};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 import_utils2=require("@frontmcp/utils");var import_utils3=require("@frontmcp/utils");function signatureHeaders(signingKey,body,now=Date.now()){const message={id:`msg_${(0,import_utils2.randomUUID)()}`,timestamp:Math.floor(now/1e3),body};return(0,import_utils2.webhookSignatureHeaders)(message,[signingKey])}function checkSignature(signingKey,message,now=Date.now()){return(0,import_utils2.verifyWebhookSignature)(message,[signingKey],now)}var import_sdk2=require("@frontmcp/sdk");var import_utils4=require("@frontmcp/utils");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}function auditFieldsOf(record){return{toolId:record.toolId,scope:record.scope,userId:record.userId,context:record.context?{type:record.context.type,identifier:record.context.identifier}:void 0,grantedBy:record.grantedBy,reason:record.reason,expiresAt:record.expiresAt}}var LoggerAuditSink=class{constructor(logger){this.logger=logger}logger;record(event){const fields=Object.fromEntries(Object.entries(event).filter(([,value])=>value!==void 0));this.logger.info(event.toolId?`${event.type} ${event.toolId}`:event.type,fields)}};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 DEFAULT_MAX_DELEGATION_DEPTH=3;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,maxDelegationDepth:options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH,audit:options.audit}}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_utils4.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_utils4.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}isOverDelegated(record){return record.state==="approved"&&grantorDelegationProblem(record.grantedBy,this.options.maxDelegationDepth)!==void 0}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)&&!this.isOverDelegated(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){return this.writeRecord(options,"approved")}async denyApproval(options){return this.writeRecord(options,"denied")}async writeRecord(options,state){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 delegationProblem2=state==="approved"&&grantorDelegationProblem(grantedBy,this.options.maxDelegationDepth);if(delegationProblem2)throw new ApprovalOperationError("grant",delegationProblem2);const record={toolId:options.toolId,state,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});this.options.audit?.record({type:state==="denied"?"approval.denied":"approval.granted",...auditFieldsOf(record)});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);for(const record of revoked.values()){this.options.audit?.record({type:"approval.revoked",...auditFieldsOf(record),revokedBy,reason:options.reason})}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_utils4.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}const count=await this.storage.mdelete(keys);this.options.audit?.record({type:"approval.revoked",count,reason:"session approvals cleared"});return count}async clearExpiredApprovals(){this.ensureInitialized();const now=Date.now();const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);const keysToDelete=[];const expired=[];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]);expired.push(approval)}}if(keysToDelete.length===0)return 0;const deleted=await this.storage.mdelete(keysToDelete);for(const record of expired)this.options.audit?.record({type:"approval.expired",...auditFieldsOf(record)});return deleted}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_sdk2.Provider)({name:"provider:approval:store:storage",description:"Storage-backed approval store (supports Memory, Redis, Vercel KV, Upstash)",scope:import_sdk2.ProviderScope.GLOBAL})],ApprovalStorageStore);function createApprovalMemoryStore(options={}){const memoryStorage=(0,import_utils4.createMemoryStorage)();return new ApprovalStorageStore({...options,storageInstance:memoryStorage})}var DEFAULT_CALLBACK_PATH="/approval/callback";var DEFAULT_RECHECK_INTERVAL_MS=2e3;var DEFAULT_RECHECK_MAX_ATTEMPTS=5;var MAX_RECHECK_WAIT_MS=12e4;var MIN_SECRET_BYTES=24;var LOOPBACK_HOSTNAMES=new Set(["localhost","127.0.0.1","[::1]"]);var CALLBACK_PATH_PATTERN=/^(\/[A-Za-z0-9._~-]+)+$/;function refuse(message){throw new ApprovalConfigurationError(`ApprovalPlugin ${message}`)}function setOptions(values){return Object.entries(values).filter(([,value])=>value!==void 0).map(([name2])=>name2)}function checkOutboundUrl(option,url){let parsed;try{parsed=new URL(url)}catch{return refuse(`\`${option}\` is not a URL`)}if(parsed.username||parsed.password){refuse(`\`${option}\` must not carry credentials; use the auth options instead`)}const loopbackInDevelopment=parsed.protocol==="http:"&&LOOPBACK_HOSTNAMES.has(parsed.hostname)&&!(0,import_utils5.isProduction)();if(parsed.protocol!=="https:"&&!loopbackInDevelopment){refuse(`\`${option}\` must be an https:// URL (http://localhost is accepted when NODE_ENV is not production), got ${parsed.protocol}//${parsed.host}`)}return parsed.toString()}function checkSecret(option,secret){if(secret===void 0||secret.trim()===""){return refuse(`needs \`${option}\` to sign its requests and verify callbacks`)}let signingKey;try{signingKey=(0,import_utils3.signingKeyOf)(secret)}catch{return refuse(`\`${option}\` starts with whsec_ but the rest is not base64`)}if(signingKey.length<MIN_SECRET_BYTES){refuse(`\`${option}\` must be at least ${MIN_SECRET_BYTES} bytes (32 characters or more is recommended)`)}return signingKey}function checkWholeNumber(option,value,min,max){if(!Number.isInteger(value)||value<min||value>max){refuse(`\`${option}\` must be a whole number from ${min} to ${max}, got ${value}`)}return value}function resolveWebhook(options){const{url,secret,includeJwt,callbackPath,challengeTtl}=options.webhook??{};const external=setOptions({url,secret,includeJwt,callbackPath}).map(name2=>`\`webhook.${name2}\``);if(external.length===0)return void 0;if(options.mode!=="webhook")refuse(`${external.join(", ")} need \`mode: 'webhook'\``);if(url===void 0)refuse(`${external.join(", ")} need \`webhook.url\``);const path=callbackPath??DEFAULT_CALLBACK_PATH;if(!CALLBACK_PATH_PATTERN.test(path)||path.length>256){refuse(`\`webhook.callbackPath\` must be a path such as ${DEFAULT_CALLBACK_PATH}, got ${JSON.stringify(path)}`)}return{url:checkOutboundUrl("webhook.url",url),signingKey:checkSecret("webhook.secret",secret),includeJwt:includeJwt===true,callbackPath:path,challengeTtlSeconds:challengeTtl??300}}function resolveRecheck(options){if(options.recheck===void 0)return void 0;const{url,auth="none",token,headers,secret,interval,maxAttempts}=options.recheck;if(options.mode==="webhook")refuse("`recheck` needs `mode: 'recheck'`");if(url===void 0){const others=setOptions({auth:options.recheck.auth,token,headers,secret,interval,maxAttempts});refuse(`${others.map(name2=>`\`recheck.${name2}\``).join(", ")||"`recheck`"} need \`recheck.url\``)}if(!["jwt","bearer","none","custom"].includes(auth)){refuse(`\`recheck.auth\` must be 'jwt', 'bearer', 'none' or 'custom', got ${JSON.stringify(auth)}`)}if(auth==="bearer"&&!token)refuse("`recheck.auth: 'bearer'` needs `recheck.token`");if(auth!=="bearer"&&token!==void 0)refuse("`recheck.token` is only sent with `recheck.auth: 'bearer'`");if(auth==="custom"&&typeof headers!=="function")refuse("`recheck.auth: 'custom'` needs a `recheck.headers` function");if(auth!=="custom"&&headers!==void 0)refuse("`recheck.headers` is only used with `recheck.auth: 'custom'`");const intervalMs=checkWholeNumber("recheck.interval",interval??DEFAULT_RECHECK_INTERVAL_MS,100,6e4);const attempts=checkWholeNumber("recheck.maxAttempts",maxAttempts??DEFAULT_RECHECK_MAX_ATTEMPTS,1,60);if(intervalMs*(attempts-1)>MAX_RECHECK_WAIT_MS){refuse(`would keep a call waiting ${intervalMs*(attempts-1)} ms: \`recheck.interval\` \xD7 (\`recheck.maxAttempts\` \u2212 1) must be ${MAX_RECHECK_WAIT_MS} ms or less`)}return{url:checkOutboundUrl("recheck.url",url),auth,token,headers,signingKey:secret===void 0?void 0:checkSecret("recheck.secret",secret),intervalMs,maxAttempts:attempts}}function resolveExternalApproval(options){return{webhook:resolveWebhook(options),recheck:resolveRecheck(options)}}function resolveMaxDelegationDepth(options){const depth=options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH;return checkWholeNumber("maxDelegationDepth",depth,0,MAX_DELEGATION_CHAIN_LINKS)}var ApprovalStoreToken=Symbol.for("plugin:approval:store");var ApprovalServiceToken=Symbol.for("plugin:approval:service");var ChallengeServiceToken=Symbol.for("plugin:approval:challenge-service");var ExternalApproverToken=Symbol.for("plugin:approval:external-approver");var ApprovalAuditToken=Symbol.for("plugin:approval:audit");var import_reflect_metadata=require("reflect-metadata");var import_lazy_zod2=require("@frontmcp/lazy-zod");var import_sdk3=require("@frontmcp/sdk");var plan={pre:["checkIpFilter","acquireQuota"],execute:["handleCallback"]};var approvalCallbackStateSchema=import_lazy_zod2.z.object({});var callbackRoutes=new WeakMap;var name="approval:webhook-callback";var{Stage}=(0,import_sdk3.FlowHooksOf)(name);var ApprovalCallbackFlow=class extends import_sdk3.FlowBase{static canActivate(request,scope){return callbackRoutes.get(scope)?.has(request.path)??false}async checkIpFilter(){(0,import_sdk3.enforceIpFilter)(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await(0,import_sdk3.enforceGlobalRateLimit)(this.scope,this.tryGetContext())}async handleCallback(){const request=this.rawInput.request;const handler=callbackRoutes.get(this.scope)?.get(request.path);if(!handler)return this.next();this.respond(await handler.handleCallback({headers:request.headers,bodyBytes:request.bodyBytes}))}};__decorateClass([Stage("checkIpFilter")],ApprovalCallbackFlow.prototype,"checkIpFilter",1);__decorateClass([Stage("acquireQuota")],ApprovalCallbackFlow.prototype,"acquireQuota",1);__decorateClass([Stage("handleCallback")],ApprovalCallbackFlow.prototype,"handleCallback",1);ApprovalCallbackFlow=__decorateClass([(0,import_sdk3.Flow)({name,plan,access:"public",inputSchema:import_sdk3.httpInputSchema,outputSchema:import_sdk3.HttpJsonSchema,middleware:{method:"POST"}})],ApprovalCallbackFlow);function mcpPaths(scope){const base=`${(0,import_sdk3.normalizeEntryPrefix)(scope.entryPath)}${(0,import_sdk3.normalizeScopeBase)(scope.routeBase)}`;return[base||"/",`${base}/sse`,`${base}/message`,`${base}/server-card`]}async function serveApprovalCallback(scope,path,handler){if(mcpPaths(scope).includes(path)||/^\/(oauth|\.well-known)(\/|$)/.test(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is a path the server reserves`)}let routes=callbackRoutes.get(scope);const firstRoute=!routes;routes??=new Map;if(routes.has(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is served by another ApprovalPlugin; give each its own`)}routes.set(path,handler);callbackRoutes.set(scope,routes);if(firstRoute)await scope.registryFlows(ApprovalCallbackFlow)}var import_utils6=require("@frontmcp/utils");function pendingRequestKey(subject){return(0,import_utils6.sha256Hex)(JSON.stringify([subject.toolId,subject.sessionId,subject.userId??null]))}function grantTarget(scope,subject){const{sessionId,userId,context}=subject;switch(scope){case"session":return{sessionId};case"user":return userId?{userId}:void 0;case"time_limited":return{sessionId,userId};case"context_specific":return context?{context,sessionId,userId}:void 0;default:return void 0}}var ApprovalDecisionRecorder=class{constructor(store,requirementOf,logger){this.store=store;this.requirementOf=requirementOf;this.logger=logger}store;requirementOf;logger;async approve(subject,decision,origin){const requirement=this.requirementOf(subject.toolId);const scope=decision.scope??requirement?.defaultScope??"session";const target=grantTarget(scope,subject);if(!target){this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: no ${scope} to grant it to`);return false}try{const ttlMs=checkGrantAgainstPolicy(subject.toolId,scope,decision.ttlMs,requirement);await this.store.grantApproval({toolId:subject.toolId,scope,ttlMs,...target,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason});return true}catch(error){if(!(error instanceof ApprovalError))throw error;this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: ${error.message}`);return false}}async deny(subject,decision,ttlMs,origin){if(!this.store.denyApproval){this.logger.warn(`ApprovalPlugin: the ${origin} denial of ${subject.toolId} was not recorded: the store keeps no denials`);return}await this.store.denyApproval({toolId:subject.toolId,scope:"session",ttlMs,sessionId:subject.sessionId,userId:subject.userId,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason})}};var import_lazy_zod3=require("@frontmcp/lazy-zod");var import_utils7=require("@frontmcp/utils");var OUTBOUND_TIMEOUT_MS=1e4;var OUTBOUND_MAX_RESPONSE_BYTES=64*1024;var OutboundRequestError=class extends Error{name="OutboundRequestError"};async function readBounded(response){const declaredLength=Number(response.headers.get("content-length")??0);if(declaredLength>OUTBOUND_MAX_RESPONSE_BYTES){await response.body?.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}if(!response.body)return"";const reader=response.body.getReader();const chunks=[];let received2=0;for(;;){const{done,value}=await reader.read();if(done)break;received2+=value.byteLength;if(received2>OUTBOUND_MAX_RESPONSE_BYTES){await reader.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}chunks.push(value)}const bytes=new Uint8Array(received2);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength}return new TextDecoder().decode(bytes)}function failureCode(error){const cause=error?.cause;return typeof cause?.code==="string"?cause.code:error instanceof Error?error.name:"unknown error"}async function postJson(request){const timeoutMs=request.timeoutMs??OUTBOUND_TIMEOUT_MS;const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeoutMs);const cancel=()=>controller.abort();request.signal?.addEventListener("abort",cancel,{once:true});try{const response=await fetch(request.url,{method:"POST",headers:{...request.headers,"content-type":"application/json",accept:"application/json"},body:request.body,redirect:"manual",signal:controller.signal});if((0,import_utils7.isRedirectResponse)(response)){await response.body?.cancel();throw new OutboundRequestError(`answered with a redirect (${response.status}), which is not followed`)}return{status:response.status,body:await readBounded(response)}}catch(error){if(error instanceof OutboundRequestError)throw error;if(request.signal?.aborted)throw new OutboundRequestError("the tool call was cancelled");if(controller.signal.aborted)throw new OutboundRequestError(`no answer within ${timeoutMs} ms`);throw new OutboundRequestError(`the request failed (${failureCode(error)})`)}finally{clearTimeout(timer);request.signal?.removeEventListener("abort",cancel)}}function originOf(url){return new URL(url).origin}var recheckAnswerSchema=import_lazy_zod3.z.object({approved:import_lazy_zod3.z.boolean(),pending:import_lazy_zod3.z.boolean().optional(),scope:approvalScopeSchema.optional(),ttlMs:import_lazy_zod3.z.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),denialReason:import_lazy_zod3.z.string().max(1e3).optional()});function wait(ms,signal){if(signal?.aborted)return Promise.resolve(false);return new Promise(resolve=>{const done=completed=>{clearTimeout(timer);signal?.removeEventListener("abort",cancelled);resolve(completed)};const cancelled=()=>done(false);const timer=setTimeout(()=>done(true),ms);signal?.addEventListener("abort",cancelled,{once:true})})}var RecheckApprover=class{constructor(recheck,dependencies,logger){this.recheck=recheck;this.dependencies=dependencies;this.logger=logger}recheck;dependencies;logger;via="recheck";async requestApproval(call){for(let attempt=1;attempt<=this.recheck.maxAttempts;attempt++){if(attempt>1&&!await wait(this.recheck.intervalMs,call.signal))return"pending";let answer;try{answer=await this.poll(call,attempt)}catch(error){if(!(error instanceof OutboundRequestError))throw error;this.logger.warn(`ApprovalPlugin: polling ${originOf(this.recheck.url)} for ${call.toolId} failed: ${error.message}`);return"pending"}if(!answer)return"pending";if(answer.approved)return await this.approve(call,answer)?"approved":"pending";if(!answer.pending)return"denied"}return"pending"}async approve(call,answer){if(call.requirement.alwaysPrompt)return true;return this.dependencies.decisions.approve(call,{scope:answer.scope,ttlMs:answer.ttlMs,decidedBy:answer.grantedBy},"recheck")}async poll(call,attempt){const{requirement}=call;const request={type:"approval.status",requestId:pendingRequestKey(call),attempt,toolId:call.toolId,toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,approvalMessage:requirement.approvalMessage,requestedScope:requirement.defaultScope??"session",allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,timestamp:Date.now()};const authorization=await this.authorization(call,request);if(!authorization)return void 0;const body=JSON.stringify(request);const signing=this.recheck.signingKey?signatureHeaders(this.recheck.signingKey,body):{};const answer=await postJson({url:this.recheck.url,body,headers:{...authorization,...signing},signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);try{return recheckAnswerSchema.parse(JSON.parse(answer.body))}catch{throw new OutboundRequestError("answered with something other than { approved, pending?, scope?, ttlMs?, ... }")}}async authorization(call,request){switch(this.recheck.auth){case"jwt":if(!call.accessToken){this.logger.verbose(`ApprovalPlugin: not polling for ${call.toolId}: the call has no token to forward`);return void 0}return{authorization:`Bearer ${call.accessToken}`};case"bearer":return{authorization:`Bearer ${this.recheck.token}`};case"custom":return{...await this.recheck.headers?.(request)};default:return{}}}};var import_lazy_zod4=require("@frontmcp/lazy-zod");var import_sdk4=require("@frontmcp/sdk");var MAX_CALLBACK_BYTES=16*1024;var callbackSchema=import_lazy_zod4.z.object({codeVerifier:import_lazy_zod4.z.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),approved:import_lazy_zod4.z.boolean(),scope:approvalScopeSchema.optional(),ttlMs:import_lazy_zod4.z.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),reason:import_lazy_zod4.z.string().max(1e3).optional()});function refusal(status,error,description){return import_sdk4.httpRespond.json({error,error_description:description},{status})}function headerOf(headers,name2){const value=headers[name2];return typeof value==="string"?value:void 0}function received(){return import_sdk4.httpRespond.json({status:"received"},{status:202})}var WebhookApprover=class{constructor(webhook,dependencies,logger){this.webhook=webhook;this.dependencies=dependencies;this.logger=logger}webhook;dependencies;logger;via="webhook";get challenges(){return this.dependencies.challenges}async requestApproval(call){const pendingKey=pendingRequestKey(call);const ttlSeconds=this.webhook.challengeTtlSeconds;if(!await this.challenges.claimPendingRequest(pendingKey,ttlSeconds))return"pending";const{requirement}=call;const requestedScope=requirement.defaultScope??"session";const requestInfo={toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,customMessage:requirement.approvalMessage};const{codeVerifier,codeChallenge,expiresAt}=await this.challenges.createChallenge({toolId:call.toolId,sessionId:call.sessionId,userId:call.userId,context:call.context,requestedScope,requestInfo,ttlSeconds});const publicUrl=(0,import_sdk4.getPinnedPublicUrl)();const payload={type:"approval.requested",codeChallenge,codeVerifier,toolId:call.toolId,toolName:call.toolName,category:requestInfo.category,riskLevel:requestInfo.riskLevel,approvalMessage:requestInfo.customMessage,requestedScope,allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,callbackPath:this.webhook.callbackPath,callbackUrl:publicUrl?`${publicUrl}${this.webhook.callbackPath}`:void 0,expiresAt,timestamp:Date.now(),jwt:this.webhook.includeJwt?call.accessToken:void 0};const body=JSON.stringify(payload);try{const answer=await postJson({url:this.webhook.url,body,headers:signatureHeaders(this.webhook.signingKey,body),signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);await this.challenges.markWebhookSent(codeChallenge)}catch(error){if(!(error instanceof OutboundRequestError))throw error;await this.challenges.deleteChallenge(codeChallenge);await this.challenges.releasePendingRequest(pendingKey);this.logger.warn(`ApprovalPlugin: the approval request for ${call.toolId} to ${originOf(this.webhook.url)} failed: ${error.message}`)}return"pending"}async handleCallback(request){const{bodyBytes}=request;if(!bodyBytes||bodyBytes.byteLength===0){return refusal(400,"invalid_request","the body must be the decision, as JSON")}if(bodyBytes.byteLength>MAX_CALLBACK_BYTES){return refusal(413,"payload_too_large",`the body must be ${MAX_CALLBACK_BYTES} bytes or less`)}const body=new TextDecoder().decode(bodyBytes);const signature=checkSignature(this.webhook.signingKey,{id:headerOf(request.headers,import_utils3.WEBHOOK_ID_HEADER),timestamp:headerOf(request.headers,import_utils3.WEBHOOK_TIMESTAMP_HEADER),signature:headerOf(request.headers,import_utils3.WEBHOOK_SIGNATURE_HEADER),body});if(signature!=="valid"){this.logger.warn(`ApprovalPlugin: refused an approval callback: signature ${signature}`);return refusal(401,"invalid_signature","the callback must be signed with webhook.secret, within five minutes")}let decision;try{decision=callbackSchema.parse(JSON.parse(body))}catch{return refusal(400,"invalid_request","the body must be { codeVerifier, approved, scope?, ttlMs?, grantedBy?, reason? }")}const pending=await this.challenges.consume(decision.codeVerifier);if(!pending)return received();await this.challenges.releasePendingRequest(pendingRequestKey(pending));const subject={toolId:pending.toolId,sessionId:pending.sessionId,userId:pending.userId,context:pending.context};const outcome={scope:decision.scope,ttlMs:decision.ttlMs,decidedBy:decision.grantedBy,reason:decision.reason};if(decision.approved){await this.dependencies.decisions.approve(subject,outcome,"webhook")}else{await this.dependencies.decisions.deny(subject,outcome,decision.ttlMs??this.webhook.challengeTtlSeconds*1e3,"webhook")}return received()}};var import_sdk5=require("@frontmcp/sdk");var decidedCalls=new WeakSet;var ApprovalCheckPlugin=class extends import_sdk5.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 callerContext=toolContext.tryGetContext?.();const{sessionId,userId}=resolveApprovalIdentity(callerContext);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);const requested=(state,via)=>this.optional(ApprovalAuditToken)?.record({type:"approval.requested",toolId:tool.fullName,userId,context:currentContext&&{type:currentContext.type,identifier:currentContext.identifier},state,via});if(records.some(record=>record.state==="denied")){requested("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}const external=isUnidentifiedSession(sessionId)?void 0:this.optional(ExternalApproverToken);const outcome=await external?.requestApproval({toolId:tool.fullName,toolName:tool.name,sessionId,userId,context:currentContext,requirement:approvalConfig,accessToken:callerContext?.authInfo?.token,signal:toolContext.signal});const expiredApproval=approved.find(record=>isApprovalExpired(record,approvalConfig,now));const callState=outcome==="approved"||outcome==="denied"?outcome:expiredApproval?"expired":"pending";requested(callState,external?.via);if(outcome==="approved")return;if(outcome==="denied"){throw new ApprovalRequiredError({toolId:tool.fullName,state:"denied",message:`Tool "${tool.fullName}" execution denied.`})}await this.handleApprovalRequired(flowCtx,approvalConfig,expiredApproval??approved[0])}optional(token){try{return this.get(token)}catch(error){if(error instanceof import_sdk5.ProviderNotAvailableError)return void 0;throw error}}coveringStores(tool){const stores=new Set([this.get(ApprovalStoreToken)]);let scope;try{scope=this.get(import_sdk5.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_sdk5.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_sdk5.ToolHook.Will("execute",{priority:100,appliesTo:"uncovered-apps"})],ApprovalCheckPlugin.prototype,"checkApproval",1);ApprovalCheckPlugin=__decorateClass([(0,import_sdk5.Plugin)({name:"approval:check",description:"Checks tool approval state before execution",enforcesMetadata:["approval"]})],ApprovalCheckPlugin);var import_sdk6=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_sdk6.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_sdk6.Provider)({name:"provider:approval:service",description:"Service for managing tool approvals",scope:import_sdk6.ProviderScope.CONTEXT})],ApprovalService);function createApprovalService(store,sessionId,userId,requirementOf){return new ApprovalService(store,sessionId,userId,requirementOf)}var import_sdk7=require("@frontmcp/sdk");var import_utils8=require("@frontmcp/utils");var PENDING_REQUEST_PREFIX="pending:";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_utils8.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_utils8.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,context:options.context,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){const consumed=await this.take(codeVerifier);if(!consumed){throw new ChallengeValidationError("not_found","Invalid or expired challenge")}if(Date.now()>consumed.expiresAt){throw new ChallengeValidationError("expired","Challenge expired")}return consumed}async consume(codeVerifier){const consumed=await this.take(codeVerifier);return consumed&&Date.now()<=consumed.expiresAt?consumed:void 0}async take(codeVerifier){this.ensureInitialized();const codeChallenge=(0,import_utils8.generateCodeChallenge)(codeVerifier);const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return void 0;if(!await this.deleteIfUnchanged(codeChallenge,recordJson))return void 0;return JSON.parse(recordJson)}async deleteIfUnchanged(key,value){try{return await this.storage.deleteIfEquals(key,value)}catch(error){if(!(error instanceof import_utils8.StorageNotSupportedError))throw error;return this.storage.delete(key)}}async claimPendingRequest(key,ttlSeconds=this.options.defaultTtlSeconds){this.ensureInitialized();const claim=(0,import_utils8.randomUUID)();const pendingKey=`${PENDING_REQUEST_PREFIX}${key}`;try{await this.storage.set(pendingKey,claim,{ttlSeconds,ifNotExists:true})}catch(error){if(!(error instanceof import_utils8.StorageNotSupportedError))throw error;if(await this.storage.exists(pendingKey))return false;await this.storage.set(pendingKey,claim,{ttlSeconds})}return await this.storage.get(pendingKey)===claim}async releasePendingRequest(key){this.ensureInitialized();await this.storage.delete(`${PENDING_REQUEST_PREFIX}${key}`)}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_sdk7.Provider)({name:"provider:approval:challenge-service",description:"PKCE challenge service for webhook approval flows",scope:import_sdk7.ProviderScope.GLOBAL})],ChallengeService);function createMemoryChallengeService(options={}){const memoryStorage=(0,import_utils8.createMemoryStorage)();return new ChallengeService({...options,storageInstance:memoryStorage})}function toolRequirementLookup(scope){return 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)}}function externalApproverProvider(external){const{webhook,recheck}=external;if(!webhook&&!recheck)return void 0;return{name:"approval:external-approver",provide:ExternalApproverToken,inject:()=>[import_sdk8.ProviderRegistry,import_sdk8.ScopeEntry],useFactory:async(providers,scope)=>{const logger=scope.logger.child("ApprovalPlugin");const requirementOf=toolRequirementLookup(scope);const dependencies={get challenges(){return providers.get(ChallengeServiceToken)},get decisions(){return new ApprovalDecisionRecorder(providers.get(ApprovalStoreToken),requirementOf,logger)}};if(!webhook)return new RecheckApprover(recheck,dependencies,logger);const approver=new WebhookApprover(webhook,dependencies,logger);await serveApprovalCallback(scope,webhook.callbackPath,approver);return approver}}}var ApprovalPlugin=class extends import_sdk8.DynamicPlugin{options;constructor(options={}){super();this.options={...ApprovalPlugin.defaultOptions,...options}}};__publicField(ApprovalPlugin,"defaultOptions",{namespace:"approval",mode:"recheck",enableAudit:false,maxDelegationDepth:DEFAULT_MAX_DELEGATION_DEPTH,cleanupIntervalSeconds:60});__publicField(ApprovalPlugin,"browserStores",({storage,storageInstance})=>{const type=storageInstance?void 0:storage?.type;return[{plugin:"ApprovalPlugin",option:type==="redis"||type==="sqlite"?`storage: { type: '${type}' }`:void 0,memory:"storage: { type: 'memory' }"}]});__publicField(ApprovalPlugin,"dynamicProviders",options=>{const providers=[];const config={...ApprovalPlugin.defaultOptions,...options};const external=resolveExternalApproval(config);const maxDelegationDepth=resolveMaxDelegationDepth(config);providers.push((0,import_sdk8.storeProvider)({name:"approval:store",provide:ApprovalStoreToken,inject:()=>[import_sdk8.ScopeEntry],useFactory:async scope=>{const store=new ApprovalStorageStore({storage:config.storage,storageInstance:config.storageInstance,namespace:config.namespace,cleanupIntervalSeconds:config.cleanupIntervalSeconds,maxDelegationDepth,audit:config.enableAudit?new LoggerAuditSink(scope.logger.child("ApprovalAudit")):void 0});await store.initialize();return store}}));if(config.mode==="webhook"){providers.push((0,import_sdk8.storeProvider)({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}}))}const externalApprover=externalApproverProvider(external);if(externalApprover)providers.push(externalApprover);if(config.enableAudit){providers.push({name:"approval:audit",provide:ApprovalAuditToken,inject:()=>[import_sdk8.ScopeEntry],useFactory:scope=>new LoggerAuditSink(scope.logger.child("ApprovalAudit"))})}providers.push({name:"approval:service",provide:ApprovalServiceToken,scope:import_sdk8.ProviderScope.CONTEXT,inject:()=>[ApprovalStoreToken,import_sdk8.FRONTMCP_CONTEXT,import_sdk8.ScopeEntry],useFactory:(store,ctx,scope)=>{const{sessionId,userId}=resolveApprovalIdentity(ctx);return createApprovalService(store,sessionId,userId,toolRequirementLookup(scope))}});return providers});ApprovalPlugin=__decorateClass([(0,import_sdk8.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,ApprovalConfigurationError,ApprovalError,ApprovalExpiredError,ApprovalOperationError,ApprovalPlugin,ApprovalPluginClass,ApprovalRequiredError,ApprovalScope,ApprovalScopeNotAllowedError,ApprovalService,ApprovalServiceToken,ApprovalState,ApprovalStorageStore,ApprovalStoreToken,ChallengeService,ChallengeServiceToken,ChallengeValidationError,adminGrantor,adminRevoker,agentGrantor,apiGrantor,createApprovalMemoryStore,createApprovalService,createMemoryChallengeService,customGrantor,delegationDepth,delegationProblem,expiryRevoker,extendDelegation,installApprovalContextExtension,isApiGrantor,isAutoGrantor,isDelegatedGrantor,isGrantorSource,isHumanGrantor,normalizeGrantor,normalizeRevoker,oauthGrantor,policyGrantor,policyRevoker,sessionEndRevoker,systemGrantor,testGrantor,userGrantor,userRevoker});
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 name2 in all)__defProp(target,name2,{get:all[name2],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,ApprovalConfigurationError:()=>ApprovalConfigurationError,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,delegationDepth:()=>delegationDepth,delegationProblem:()=>delegationProblem,expiryRevoker:()=>expiryRevoker,extendDelegation:()=>extendDelegation,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_sdk8=require("@frontmcp/sdk");var import_utils=require("@frontmcp/utils");var UNIDENTIFIED_SESSION_PREFIX="unidentified:";function isUnidentifiedSession(sessionId){return sessionId.startsWith(UNIDENTIFIED_SESSION_PREFIX)}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_SESSION_PREFIX}${(0,import_utils.randomUUID)()}`,userId}}var import_utils5=require("@frontmcp/utils");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||{});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 MAX_DELEGATION_CHAIN_LINKS=64;var delegationLinkSchema=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()});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(),chain:import_lazy_zod.z.array(delegationLinkSchema).max(MAX_DELEGATION_CHAIN_LINKS).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 delegationDepth(context){return(context.chain?.length??0)+1}function delegationProblem(context,maxDepth){const links=[...context.chain??[],context];if(links.length>maxDepth){return`the delegation chain is ${links.length} deep, and maxDelegationDepth is ${maxDepth}`}const parties=new Set([links[0].delegatorId]);for(let index=0;index<links.length;index++){const link=links[index];if(index>0&&link.delegatorId!==links[index-1].delegateId){return`the delegation chain is broken: ${link.delegatorId} was not delegated to by ${links[index-1].delegatorId}`}if(parties.has(link.delegateId))return`the delegation chain names ${link.delegateId} twice`;parties.add(link.delegateId)}return void 0}function grantorDelegationProblem(grantor,maxDepth){return grantor.delegationContext?delegationProblem(grantor.delegationContext,maxDepth):void 0}function extendDelegation(context,delegateId,options={}){const{delegatorId,delegateId:delegate,purpose}=context;return{delegatorId:delegate,delegateId,...options,chain:[...context.chain??[],{delegatorId,delegateId:delegate,...purpose?{purpose}:{}}]}}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 import_sdk=require("@frontmcp/sdk");var ApprovalConfigurationError=class extends import_sdk.InternalMcpError{name="ApprovalConfigurationError";constructor(message){super(message,"APPROVAL_CONFIGURATION")}};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 import_utils2=require("@frontmcp/utils");var import_utils3=require("@frontmcp/utils");function signatureHeaders(signingKey,body,now=Date.now()){const message={id:`msg_${(0,import_utils2.randomUUID)()}`,timestamp:Math.floor(now/1e3),body};return(0,import_utils2.webhookSignatureHeaders)(message,[signingKey])}function checkSignature(signingKey,message,now=Date.now()){return(0,import_utils2.verifyWebhookSignature)(message,[signingKey],now)}var import_sdk2=require("@frontmcp/sdk");var import_utils4=require("@frontmcp/utils");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&&!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&&!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}function auditFieldsOf(record){return{toolId:record.toolId,scope:record.scope,userId:record.userId,context:record.context?{type:record.context.type,identifier:record.context.identifier}:void 0,grantedBy:record.grantedBy,reason:record.reason,expiresAt:record.expiresAt}}var LoggerAuditSink=class{constructor(logger){this.logger=logger}logger;record(event){const fields=Object.fromEntries(Object.entries(event).filter(([,value])=>value!==void 0));this.logger.info(event.toolId?`${event.type} ${event.toolId}`:event.type,fields)}};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 SINGLE_USE_STORAGE_MESSAGE="ApprovalPlugin: an alwaysPrompt tool's approval can be used up by exactly one call only on a storage that deletes a key only while it holds a given value, and this storage cannot. Set the plugin's storage to type 'memory', 'redis', 'upstash', 'vercel-kv' or 'sqlite'.";var TIME_LIMITED_KEY_SEGMENT=`scope:${"time_limited"}`;function encodeKeyPart(part){return part.replace(/%/g,"%25").replace(/:/g,"%3A")}function legacyKeyPart(part){return part}var DEFAULT_MAX_DELEGATION_DEPTH=3;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,maxDelegationDepth:options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH,audit:options.audit}}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_utils4.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_utils4.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,owner,encode=encodeKeyPart){const parts=[toolId];if(owner.sessionId)parts.push(`session:${encode(owner.sessionId)}`);if(owner.userId)parts.push(`user:${encode(owner.userId)}`);if(owner.context)parts.push(`ctx:${encode(owner.context.type)}:${encode(owner.context.identifier)}`);if(owner.timeLimited)parts.push(TIME_LIMITED_KEY_SEGMENT);return parts.join(":")}recordKey(options){const{toolId,scope,sessionId,userId,context}=options;return this.buildKey(toolId,{sessionId,userId,context,timeLimited:scope==="time_limited"&&!context})}isOwnedBy(record,owner){const{sessionId,userId,context}=record;return this.buildKey(record.toolId,{sessionId,userId,context})===this.buildKey(record.toolId,{sessionId:owner.sessionId,userId:owner.userId,context:owner.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}isOverDelegated(record){return record.state==="approved"&&grantorDelegationProblem(record.grantedBy,this.options.maxDelegationDepth)!==void 0}callerOwners(sessionId,userId,context){const owners=[{sessionId},{sessionId,timeLimited:true}];if(userId){owners.push({userId},{userId,timeLimited:true},{sessionId,userId},{sessionId,userId,timeLimited:true})}if(context){owners.push({sessionId,context});if(userId)owners.push({sessionId,userId,context})}return owners}callerKeys(toolId,sessionId,userId,context){const owners=new Map;for(const owner of this.callerOwners(sessionId,userId,context)){for(const key of[this.buildKey(toolId,owner),this.buildKey(toolId,owner,legacyKeyPart)]){if(!owners.has(key))owners.set(key,owner)}}return[...owners].map(([key,owner])=>({key,owner}))}async getApprovals(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const{key,owner}of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.storage.get(key));if(record&&record.toolId===toolId&&this.isOwnedBy(record,owner)&&!this.isExpired(record)&&!this.isOverDelegated(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){return this.writeRecord(options,"approved")}async denyApproval(options){return this.writeRecord(options,"denied")}async writeRecord(options,state){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 delegationProblem2=state==="approved"&&grantorDelegationProblem(grantedBy,this.options.maxDelegationDepth);if(delegationProblem2)throw new ApprovalOperationError("grant",delegationProblem2);const record={toolId:options.toolId,state,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});this.options.audit?.record({type:state==="denied"?"approval.denied":"approval.granted",...auditFieldsOf(record)});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 revocable=new Map;for(let i=0;i<keys.length;i++){const value=values[i];const record=this.parseRecord(value);if(value===null||!record||record.toolId!==toolId||record.state==="denied")continue;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)){revocable.set(keys[i],{record,value})}}else if(sessionId&&record.sessionId===sessionId||userId&&record.userId===userId){revocable.set(keys[i],{record,value})}}const revokedAt=Date.now();const revokedBy=normalizeRevoker(options.revokedBy);let revokedAny=false;for(const[key,{record,value}]of revocable){if(!await this.deleteIfUnchanged(key,value))continue;revokedAny=true;const entry={...record,revokedAt,revokedBy,revocationReason:options.reason};await this.revocations.set(key,JSON.stringify(entry),{ttlSeconds:REVOCATION_RETENTION_SECONDS});this.options.audit?.record({type:"approval.revoked",...auditFieldsOf(record),revokedBy,reason:options.reason})}return revokedAny}async consumeApproval(record,sessionId,userId,context){this.ensureInitialized();for(const{key,owner}of this.callerKeys(record.toolId,sessionId,userId,context)){const storedValue=await this.storage.get(key);const stored=this.parseRecord(storedValue);if(storedValue!==null&&stored&&this.isOwnedBy(stored,owner)&&isSameRecord(stored,record)){return this.deleteOnce(key,storedValue)}}return false}async deleteOnce(key,storedValue){try{return await this.storage.deleteIfEquals(key,storedValue)}catch(error){if(!(error instanceof import_utils4.StorageNotSupportedError))throw error;throw new ApprovalConfigurationError(SINGLE_USE_STORAGE_MESSAGE)}}async deleteIfUnchanged(key,storedValue){try{return await this.storage.deleteIfEquals(key,storedValue)}catch(error){if(!(error instanceof import_utils4.StorageNotSupportedError))throw error;if(await this.storage.get(key)!==storedValue)return false;return this.storage.delete(key)}}async getRevocations(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const{key,owner}of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.revocations.get(key));if(record&&record.toolId===toolId&&this.isOwnedBy(record,owner))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 patterns=new Set;for(const storedSessionId of[encodeKeyPart(sessionId),legacyKeyPart(sessionId)]){const escapedSessionId=escapePattern(storedSessionId);patterns.add(`*:session:${escapedSessionId}`);patterns.add(`*:session:${escapedSessionId}:*`)}const keys=new Set;for(const pattern of patterns){for(const key of await this.storage.keys(pattern))keys.add(key)}if(keys.size===0){return 0}const candidates=[...keys];const values=await this.storage.mget(candidates);let count=0;for(let index=0;index<candidates.length;index++){const value=values[index];if(value===null||this.parseRecord(value)?.sessionId!==sessionId)continue;if(await this.deleteIfUnchanged(candidates[index],value))count++}this.options.audit?.record({type:"approval.revoked",count,reason:"session approvals cleared"});return count}async clearExpiredApprovals(){this.ensureInitialized();const now=Date.now();const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);let deleted=0;for(let i=0;i<keys.length;i++){const value=values[i];const approval=this.parseRecord(value);if(value===null||!approval?.expiresAt||approval.expiresAt>now)continue;if(!await this.deleteIfUnchanged(keys[i],value))continue;deleted++;this.options.audit?.record({type:"approval.expired",...auditFieldsOf(approval)})}return deleted}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_sdk2.Provider)({name:"provider:approval:store:storage",description:"Storage-backed approval store (supports Memory, Redis, Vercel KV, Upstash)",scope:import_sdk2.ProviderScope.GLOBAL})],ApprovalStorageStore);function createApprovalMemoryStore(options={}){const memoryStorage=(0,import_utils4.createMemoryStorage)();return new ApprovalStorageStore({...options,storageInstance:memoryStorage})}var DEFAULT_CALLBACK_PATH="/approval/callback";var DEFAULT_RECHECK_INTERVAL_MS=2e3;var DEFAULT_RECHECK_MAX_ATTEMPTS=5;var MAX_RECHECK_WAIT_MS=12e4;var MIN_SECRET_BYTES=24;var LOOPBACK_HOSTNAMES=new Set(["localhost","127.0.0.1","[::1]"]);var CALLBACK_PATH_PATTERN=/^(\/[A-Za-z0-9._~-]+)+$/;function refuse(message){throw new ApprovalConfigurationError(`ApprovalPlugin ${message}`)}function setOptions(values){return Object.entries(values).filter(([,value])=>value!==void 0).map(([name2])=>name2)}function checkOutboundUrl(option,url){let parsed;try{parsed=new URL(url)}catch{return refuse(`\`${option}\` is not a URL`)}if(parsed.username||parsed.password){refuse(`\`${option}\` must not carry credentials; use the auth options instead`)}const loopbackInDevelopment=parsed.protocol==="http:"&&LOOPBACK_HOSTNAMES.has(parsed.hostname)&&!(0,import_utils5.isProduction)();if(parsed.protocol!=="https:"&&!loopbackInDevelopment){refuse(`\`${option}\` must be an https:// URL (http://localhost is accepted when NODE_ENV is not production), got ${parsed.protocol}//${parsed.host}`)}return parsed.toString()}function checkSecret(option,secret){if(secret===void 0||secret.trim()===""){return refuse(`needs \`${option}\` to sign its requests and verify callbacks`)}let signingKey;try{signingKey=(0,import_utils3.signingKeyOf)(secret)}catch{return refuse(`\`${option}\` starts with whsec_ but the rest is not base64`)}if(signingKey.length<MIN_SECRET_BYTES){refuse(`\`${option}\` must be at least ${MIN_SECRET_BYTES} bytes (32 characters or more is recommended)`)}return signingKey}function checkWholeNumber(option,value,min,max){if(!Number.isInteger(value)||value<min||value>max){refuse(`\`${option}\` must be a whole number from ${min} to ${max}, got ${value}`)}return value}function resolveWebhook(options){const{url,secret,includeJwt,callbackPath,challengeTtl}=options.webhook??{};const external=setOptions({url,secret,includeJwt,callbackPath}).map(name2=>`\`webhook.${name2}\``);if(external.length===0)return void 0;if(options.mode!=="webhook")refuse(`${external.join(", ")} need \`mode: 'webhook'\``);if(url===void 0)refuse(`${external.join(", ")} need \`webhook.url\``);const path=callbackPath??DEFAULT_CALLBACK_PATH;if(!CALLBACK_PATH_PATTERN.test(path)||path.length>256){refuse(`\`webhook.callbackPath\` must be a path such as ${DEFAULT_CALLBACK_PATH}, got ${JSON.stringify(path)}`)}return{url:checkOutboundUrl("webhook.url",url),signingKey:checkSecret("webhook.secret",secret),includeJwt:includeJwt===true,callbackPath:path,challengeTtlSeconds:challengeTtl??300}}function resolveRecheck(options){if(options.recheck===void 0)return void 0;const{url,auth="none",token,headers,secret,interval,maxAttempts}=options.recheck;if(options.mode==="webhook")refuse("`recheck` needs `mode: 'recheck'`");if(url===void 0){const others=setOptions({auth:options.recheck.auth,token,headers,secret,interval,maxAttempts});refuse(`${others.map(name2=>`\`recheck.${name2}\``).join(", ")||"`recheck`"} need \`recheck.url\``)}if(!["jwt","bearer","none","custom"].includes(auth)){refuse(`\`recheck.auth\` must be 'jwt', 'bearer', 'none' or 'custom', got ${JSON.stringify(auth)}`)}if(auth==="bearer"&&!token)refuse("`recheck.auth: 'bearer'` needs `recheck.token`");if(auth!=="bearer"&&token!==void 0)refuse("`recheck.token` is only sent with `recheck.auth: 'bearer'`");if(auth==="custom"&&typeof headers!=="function")refuse("`recheck.auth: 'custom'` needs a `recheck.headers` function");if(auth!=="custom"&&headers!==void 0)refuse("`recheck.headers` is only used with `recheck.auth: 'custom'`");const intervalMs=checkWholeNumber("recheck.interval",interval??DEFAULT_RECHECK_INTERVAL_MS,100,6e4);const attempts=checkWholeNumber("recheck.maxAttempts",maxAttempts??DEFAULT_RECHECK_MAX_ATTEMPTS,1,60);if(intervalMs*(attempts-1)>MAX_RECHECK_WAIT_MS){refuse(`would keep a call waiting ${intervalMs*(attempts-1)} ms: \`recheck.interval\` \xD7 (\`recheck.maxAttempts\` \u2212 1) must be ${MAX_RECHECK_WAIT_MS} ms or less`)}return{url:checkOutboundUrl("recheck.url",url),auth,token,headers,signingKey:secret===void 0?void 0:checkSecret("recheck.secret",secret),intervalMs,maxAttempts:attempts}}function resolveExternalApproval(options){return{webhook:resolveWebhook(options),recheck:resolveRecheck(options)}}function resolveMaxDelegationDepth(options){const depth=options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH;return checkWholeNumber("maxDelegationDepth",depth,0,MAX_DELEGATION_CHAIN_LINKS)}var ApprovalStoreToken=Symbol.for("plugin:approval:store");var ApprovalServiceToken=Symbol.for("plugin:approval:service");var ChallengeServiceToken=Symbol.for("plugin:approval:challenge-service");var ExternalApproverToken=Symbol.for("plugin:approval:external-approver");var ApprovalAuditToken=Symbol.for("plugin:approval:audit");var import_reflect_metadata=require("reflect-metadata");var import_lazy_zod2=require("@frontmcp/lazy-zod");var import_sdk3=require("@frontmcp/sdk");var plan={pre:["checkIpFilter","acquireQuota"],execute:["handleCallback"]};var approvalCallbackStateSchema=import_lazy_zod2.z.object({});var callbackRoutes=new WeakMap;var name="approval:webhook-callback";var{Stage}=(0,import_sdk3.FlowHooksOf)(name);var ApprovalCallbackFlow=class extends import_sdk3.FlowBase{static canActivate(request,scope){return callbackRoutes.get(scope)?.has(request.path)??false}async checkIpFilter(){(0,import_sdk3.enforceIpFilter)(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await(0,import_sdk3.enforceGlobalRateLimit)(this.scope,this.tryGetContext())}async handleCallback(){const request=this.rawInput.request;const handler=callbackRoutes.get(this.scope)?.get(request.path);if(!handler)return this.next();this.respond(await handler.handleCallback({headers:request.headers,bodyBytes:request.bodyBytes}))}};__decorateClass([Stage("checkIpFilter")],ApprovalCallbackFlow.prototype,"checkIpFilter",1);__decorateClass([Stage("acquireQuota")],ApprovalCallbackFlow.prototype,"acquireQuota",1);__decorateClass([Stage("handleCallback")],ApprovalCallbackFlow.prototype,"handleCallback",1);ApprovalCallbackFlow=__decorateClass([(0,import_sdk3.Flow)({name,plan,access:"public",inputSchema:import_sdk3.httpInputSchema,outputSchema:import_sdk3.HttpJsonSchema,middleware:{method:"POST"}})],ApprovalCallbackFlow);function mcpPaths(scope){const base=`${(0,import_sdk3.normalizeEntryPrefix)(scope.entryPath)}${(0,import_sdk3.normalizeScopeBase)(scope.routeBase)}`;return[base||"/",`${base}/sse`,`${base}/message`,`${base}/server-card`]}async function serveApprovalCallback(scope,path,handler){if(mcpPaths(scope).includes(path)||/^\/(oauth|\.well-known)(\/|$)/.test(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is a path the server reserves`)}let routes=callbackRoutes.get(scope);const firstRoute=!routes;routes??=new Map;if(routes.has(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is served by another ApprovalPlugin; give each its own`)}routes.set(path,handler);callbackRoutes.set(scope,routes);if(firstRoute)await scope.registryFlows(ApprovalCallbackFlow)}var import_utils6=require("@frontmcp/utils");function pendingRequestKey(subject){return(0,import_utils6.sha256Hex)(JSON.stringify([subject.toolId,subject.sessionId,subject.userId??null]))}function grantTarget(scope,subject){const{sessionId,userId,context}=subject;switch(scope){case"session":return{sessionId};case"user":return userId?{userId}:void 0;case"time_limited":return{sessionId,userId};case"context_specific":return context?{context,sessionId,userId}:void 0;default:return void 0}}var ApprovalDecisionRecorder=class{constructor(store,requirementOf,logger){this.store=store;this.requirementOf=requirementOf;this.logger=logger}store;requirementOf;logger;async approve(subject,decision,origin){const requirement=this.requirementOf(subject.toolId);const scope=decision.scope??requirement?.defaultScope??"session";const target=grantTarget(scope,subject);if(!target){this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: no ${scope} to grant it to`);return false}try{const ttlMs=checkGrantAgainstPolicy(subject.toolId,scope,decision.ttlMs,requirement);await this.store.grantApproval({toolId:subject.toolId,scope,ttlMs,...target,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason});return true}catch(error){if(!(error instanceof ApprovalError))throw error;this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: ${error.message}`);return false}}async deny(subject,decision,ttlMs,origin){if(!this.store.denyApproval){this.logger.warn(`ApprovalPlugin: the ${origin} denial of ${subject.toolId} was not recorded: the store keeps no denials`);return}await this.store.denyApproval({toolId:subject.toolId,scope:"session",ttlMs,sessionId:subject.sessionId,userId:subject.userId,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason})}};var import_lazy_zod3=require("@frontmcp/lazy-zod");var import_utils7=require("@frontmcp/utils");var OUTBOUND_TIMEOUT_MS=1e4;var OUTBOUND_MAX_RESPONSE_BYTES=64*1024;var OutboundRequestError=class extends Error{name="OutboundRequestError"};async function readBounded(response){const declaredLength=Number(response.headers.get("content-length")??0);if(declaredLength>OUTBOUND_MAX_RESPONSE_BYTES){await response.body?.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}if(!response.body)return"";const reader=response.body.getReader();const chunks=[];let received2=0;for(;;){const{done,value}=await reader.read();if(done)break;received2+=value.byteLength;if(received2>OUTBOUND_MAX_RESPONSE_BYTES){await reader.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}chunks.push(value)}const bytes=new Uint8Array(received2);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength}return new TextDecoder().decode(bytes)}function failureCode(error){const cause=error?.cause;return typeof cause?.code==="string"?cause.code:error instanceof Error?error.name:"unknown error"}async function postJson(request){const timeoutMs=request.timeoutMs??OUTBOUND_TIMEOUT_MS;const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeoutMs);const cancel=()=>controller.abort();request.signal?.addEventListener("abort",cancel,{once:true});try{const response=await fetch(request.url,{method:"POST",headers:{...request.headers,"content-type":"application/json",accept:"application/json"},body:request.body,redirect:"manual",signal:controller.signal});if((0,import_utils7.isRedirectResponse)(response)){await response.body?.cancel();throw new OutboundRequestError(`answered with a redirect (${response.status}), which is not followed`)}return{status:response.status,body:await readBounded(response)}}catch(error){if(error instanceof OutboundRequestError)throw error;if(request.signal?.aborted)throw new OutboundRequestError("the tool call was cancelled");if(controller.signal.aborted)throw new OutboundRequestError(`no answer within ${timeoutMs} ms`);throw new OutboundRequestError(`the request failed (${failureCode(error)})`)}finally{clearTimeout(timer);request.signal?.removeEventListener("abort",cancel)}}function originOf(url){return new URL(url).origin}var recheckAnswerSchema=import_lazy_zod3.z.object({approved:import_lazy_zod3.z.boolean(),pending:import_lazy_zod3.z.boolean().optional(),scope:approvalScopeSchema.optional(),ttlMs:import_lazy_zod3.z.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),denialReason:import_lazy_zod3.z.string().max(1e3).optional()});function wait(ms,signal){if(signal?.aborted)return Promise.resolve(false);return new Promise(resolve=>{const done=completed=>{clearTimeout(timer);signal?.removeEventListener("abort",cancelled);resolve(completed)};const cancelled=()=>done(false);const timer=setTimeout(()=>done(true),ms);signal?.addEventListener("abort",cancelled,{once:true})})}var RecheckApprover=class{constructor(recheck,dependencies,logger){this.recheck=recheck;this.dependencies=dependencies;this.logger=logger}recheck;dependencies;logger;via="recheck";async requestApproval(call){for(let attempt=1;attempt<=this.recheck.maxAttempts;attempt++){if(attempt>1&&!await wait(this.recheck.intervalMs,call.signal))return"pending";let answer;try{answer=await this.poll(call,attempt)}catch(error){if(!(error instanceof OutboundRequestError))throw error;this.logger.warn(`ApprovalPlugin: polling ${originOf(this.recheck.url)} for ${call.toolId} failed: ${error.message}`);return"pending"}if(!answer)return"pending";if(answer.approved)return await this.approve(call,answer)?"approved":"pending";if(!answer.pending)return"denied"}return"pending"}async approve(call,answer){if(call.requirement.alwaysPrompt)return true;return this.dependencies.decisions.approve(call,{scope:answer.scope,ttlMs:answer.ttlMs,decidedBy:answer.grantedBy},"recheck")}async poll(call,attempt){const{requirement}=call;const request={type:"approval.status",requestId:pendingRequestKey(call),attempt,toolId:call.toolId,toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,approvalMessage:requirement.approvalMessage,requestedScope:requirement.defaultScope??"session",allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,timestamp:Date.now()};const authorization=await this.authorization(call,request);if(!authorization)return void 0;const body=JSON.stringify(request);const signing=this.recheck.signingKey?signatureHeaders(this.recheck.signingKey,body):{};const answer=await postJson({url:this.recheck.url,body,headers:{...authorization,...signing},signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);try{return recheckAnswerSchema.parse(JSON.parse(answer.body))}catch{throw new OutboundRequestError("answered with something other than { approved, pending?, scope?, ttlMs?, ... }")}}async authorization(call,request){switch(this.recheck.auth){case"jwt":if(!call.accessToken){this.logger.verbose(`ApprovalPlugin: not polling for ${call.toolId}: the call has no token to forward`);return void 0}return{authorization:`Bearer ${call.accessToken}`};case"bearer":return{authorization:`Bearer ${this.recheck.token}`};case"custom":return{...await this.recheck.headers?.(request)};default:return{}}}};var import_lazy_zod4=require("@frontmcp/lazy-zod");var import_sdk4=require("@frontmcp/sdk");var MAX_CALLBACK_BYTES=16*1024;var callbackSchema=import_lazy_zod4.z.object({codeVerifier:import_lazy_zod4.z.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),approved:import_lazy_zod4.z.boolean(),scope:approvalScopeSchema.optional(),ttlMs:import_lazy_zod4.z.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),reason:import_lazy_zod4.z.string().max(1e3).optional()});function refusal(status,error,description){return import_sdk4.httpRespond.json({error,error_description:description},{status})}function headerOf(headers,name2){const value=headers[name2];return typeof value==="string"?value:void 0}function received(){return import_sdk4.httpRespond.json({status:"received"},{status:202})}var WebhookApprover=class{constructor(webhook,dependencies,logger){this.webhook=webhook;this.dependencies=dependencies;this.logger=logger}webhook;dependencies;logger;via="webhook";get challenges(){return this.dependencies.challenges}async requestApproval(call){const pendingKey=pendingRequestKey(call);const ttlSeconds=this.webhook.challengeTtlSeconds;if(!await this.challenges.claimPendingRequest(pendingKey,ttlSeconds))return"pending";const{requirement}=call;const requestedScope=requirement.defaultScope??"session";const requestInfo={toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,customMessage:requirement.approvalMessage};const{codeVerifier,codeChallenge,expiresAt}=await this.challenges.createChallenge({toolId:call.toolId,sessionId:call.sessionId,userId:call.userId,context:call.context,requestedScope,requestInfo,ttlSeconds});const publicUrl=(0,import_sdk4.getPinnedPublicUrl)();const payload={type:"approval.requested",codeChallenge,codeVerifier,toolId:call.toolId,toolName:call.toolName,category:requestInfo.category,riskLevel:requestInfo.riskLevel,approvalMessage:requestInfo.customMessage,requestedScope,allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,callbackPath:this.webhook.callbackPath,callbackUrl:publicUrl?`${publicUrl}${this.webhook.callbackPath}`:void 0,expiresAt,timestamp:Date.now(),jwt:this.webhook.includeJwt?call.accessToken:void 0};const body=JSON.stringify(payload);try{const answer=await postJson({url:this.webhook.url,body,headers:signatureHeaders(this.webhook.signingKey,body),signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);await this.challenges.markWebhookSent(codeChallenge)}catch(error){if(!(error instanceof OutboundRequestError))throw error;await this.challenges.deleteChallenge(codeChallenge);await this.challenges.releasePendingRequest(pendingKey);this.logger.warn(`ApprovalPlugin: the approval request for ${call.toolId} to ${originOf(this.webhook.url)} failed: ${error.message}`)}return"pending"}async handleCallback(request){const{bodyBytes}=request;if(!bodyBytes||bodyBytes.byteLength===0){return refusal(400,"invalid_request","the body must be the decision, as JSON")}if(bodyBytes.byteLength>MAX_CALLBACK_BYTES){return refusal(413,"payload_too_large",`the body must be ${MAX_CALLBACK_BYTES} bytes or less`)}const body=new TextDecoder().decode(bodyBytes);const signature=checkSignature(this.webhook.signingKey,{id:headerOf(request.headers,import_utils3.WEBHOOK_ID_HEADER),timestamp:headerOf(request.headers,import_utils3.WEBHOOK_TIMESTAMP_HEADER),signature:headerOf(request.headers,import_utils3.WEBHOOK_SIGNATURE_HEADER),body});if(signature!=="valid"){this.logger.warn(`ApprovalPlugin: refused an approval callback: signature ${signature}`);return refusal(401,"invalid_signature","the callback must be signed with webhook.secret, within five minutes")}let decision;try{decision=callbackSchema.parse(JSON.parse(body))}catch{return refusal(400,"invalid_request","the body must be { codeVerifier, approved, scope?, ttlMs?, grantedBy?, reason? }")}const pending=await this.challenges.consume(decision.codeVerifier);if(!pending)return received();await this.challenges.releasePendingRequest(pendingRequestKey(pending));const subject={toolId:pending.toolId,sessionId:pending.sessionId,userId:pending.userId,context:pending.context};const outcome={scope:decision.scope,ttlMs:decision.ttlMs,decidedBy:decision.grantedBy,reason:decision.reason};if(decision.approved){await this.dependencies.decisions.approve(subject,outcome,"webhook")}else{await this.dependencies.decisions.deny(subject,outcome,decision.ttlMs??this.webhook.challengeTtlSeconds*1e3,"webhook")}return received()}};var import_sdk5=require("@frontmcp/sdk");var decidedCalls=new WeakSet;var ApprovalCheckPlugin=class extends import_sdk5.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 callerContext=toolContext.tryGetContext?.();const{sessionId,userId}=resolveApprovalIdentity(callerContext);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);const requested=(state,via)=>this.optional(ApprovalAuditToken)?.record({type:"approval.requested",toolId:tool.fullName,userId,context:currentContext&&{type:currentContext.type,identifier:currentContext.identifier},state,via});if(records.some(record=>record.state==="denied")){requested("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}const external=isUnidentifiedSession(sessionId)?void 0:this.optional(ExternalApproverToken);const outcome=await external?.requestApproval({toolId:tool.fullName,toolName:tool.name,sessionId,userId,context:currentContext,requirement:approvalConfig,accessToken:callerContext?.authInfo?.token,signal:toolContext.signal});const expiredApproval=approved.find(record=>isApprovalExpired(record,approvalConfig,now));const callState=outcome==="approved"||outcome==="denied"?outcome:expiredApproval?"expired":"pending";requested(callState,external?.via);if(outcome==="approved")return;if(outcome==="denied"){throw new ApprovalRequiredError({toolId:tool.fullName,state:"denied",message:`Tool "${tool.fullName}" execution denied.`})}await this.handleApprovalRequired(flowCtx,approvalConfig,expiredApproval??approved[0])}optional(token){try{return this.get(token)}catch(error){if(error instanceof import_sdk5.ProviderNotAvailableError)return void 0;throw error}}coveringStores(tool){const stores=new Set([this.get(ApprovalStoreToken)]);let scope;try{scope=this.get(import_sdk5.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_sdk5.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_sdk5.ToolHook.Will("execute",{priority:100,appliesTo:"uncovered-apps"})],ApprovalCheckPlugin.prototype,"checkApproval",1);ApprovalCheckPlugin=__decorateClass([(0,import_sdk5.Plugin)({name:"approval:check",description:"Checks tool approval state before execution",enforcesMetadata:["approval"]})],ApprovalCheckPlugin);var import_sdk6=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_sdk6.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_sdk6.Provider)({name:"provider:approval:service",description:"Service for managing tool approvals",scope:import_sdk6.ProviderScope.CONTEXT})],ApprovalService);function createApprovalService(store,sessionId,userId,requirementOf){return new ApprovalService(store,sessionId,userId,requirementOf)}var import_sdk7=require("@frontmcp/sdk");var import_utils8=require("@frontmcp/utils");var PENDING_REQUEST_PREFIX="pending:";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_utils8.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_utils8.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,context:options.context,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){const consumed=await this.take(codeVerifier);if(!consumed){throw new ChallengeValidationError("not_found","Invalid or expired challenge")}if(Date.now()>consumed.expiresAt){throw new ChallengeValidationError("expired","Challenge expired")}return consumed}async consume(codeVerifier){const consumed=await this.take(codeVerifier);return consumed&&Date.now()<=consumed.expiresAt?consumed:void 0}async take(codeVerifier){this.ensureInitialized();const codeChallenge=(0,import_utils8.generateCodeChallenge)(codeVerifier);const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return void 0;if(!await this.deleteIfUnchanged(codeChallenge,recordJson))return void 0;return JSON.parse(recordJson)}async deleteIfUnchanged(key,value){try{return await this.storage.deleteIfEquals(key,value)}catch(error){if(!(error instanceof import_utils8.StorageNotSupportedError))throw error;return this.storage.delete(key)}}async claimPendingRequest(key,ttlSeconds=this.options.defaultTtlSeconds){this.ensureInitialized();const claim=(0,import_utils8.randomUUID)();const pendingKey=`${PENDING_REQUEST_PREFIX}${key}`;try{await this.storage.set(pendingKey,claim,{ttlSeconds,ifNotExists:true})}catch(error){if(!(error instanceof import_utils8.StorageNotSupportedError))throw error;if(await this.storage.exists(pendingKey))return false;await this.storage.set(pendingKey,claim,{ttlSeconds})}return await this.storage.get(pendingKey)===claim}async releasePendingRequest(key){this.ensureInitialized();await this.storage.delete(`${PENDING_REQUEST_PREFIX}${key}`)}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);const updatedJson=JSON.stringify(record);try{await this.storage.set(codeChallenge,updatedJson,{ttlSeconds,ifExists:true})}catch(error){if(!(error instanceof import_utils8.StorageNotSupportedError))throw error;return false}return await this.storage.get(codeChallenge)===updatedJson}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_sdk7.Provider)({name:"provider:approval:challenge-service",description:"PKCE challenge service for webhook approval flows",scope:import_sdk7.ProviderScope.GLOBAL})],ChallengeService);function createMemoryChallengeService(options={}){const memoryStorage=(0,import_utils8.createMemoryStorage)();return new ChallengeService({...options,storageInstance:memoryStorage})}function toolRequirementLookup(scope){return 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)}}function externalApproverProvider(external){const{webhook,recheck}=external;if(!webhook&&!recheck)return void 0;return{name:"approval:external-approver",provide:ExternalApproverToken,inject:()=>[import_sdk8.ProviderRegistry,import_sdk8.ScopeEntry],useFactory:async(providers,scope)=>{const logger=scope.logger.child("ApprovalPlugin");const requirementOf=toolRequirementLookup(scope);const dependencies={get challenges(){return providers.get(ChallengeServiceToken)},get decisions(){return new ApprovalDecisionRecorder(providers.get(ApprovalStoreToken),requirementOf,logger)}};if(!webhook)return new RecheckApprover(recheck,dependencies,logger);const approver=new WebhookApprover(webhook,dependencies,logger);await serveApprovalCallback(scope,webhook.callbackPath,approver);return approver}}}var ApprovalPlugin=class extends import_sdk8.DynamicPlugin{options;constructor(options={}){super();this.options={...ApprovalPlugin.defaultOptions,...options}}};__publicField(ApprovalPlugin,"defaultOptions",{namespace:"approval",mode:"recheck",enableAudit:false,maxDelegationDepth:DEFAULT_MAX_DELEGATION_DEPTH,cleanupIntervalSeconds:60});__publicField(ApprovalPlugin,"browserStores",({storage,storageInstance})=>{const type=storageInstance?void 0:storage?.type;return[{plugin:"ApprovalPlugin",option:type==="redis"||type==="sqlite"?`storage: { type: '${type}' }`:void 0,memory:"storage: { type: 'memory' }"}]});__publicField(ApprovalPlugin,"dynamicProviders",options=>{const providers=[];const config={...ApprovalPlugin.defaultOptions,...options};const external=resolveExternalApproval(config);const maxDelegationDepth=resolveMaxDelegationDepth(config);providers.push((0,import_sdk8.storeProvider)({name:"approval:store",provide:ApprovalStoreToken,inject:()=>[import_sdk8.ScopeEntry],useFactory:async scope=>{const store=new ApprovalStorageStore({storage:config.storage,storageInstance:config.storageInstance,namespace:config.namespace,cleanupIntervalSeconds:config.cleanupIntervalSeconds,maxDelegationDepth,audit:config.enableAudit?new LoggerAuditSink(scope.logger.child("ApprovalAudit")):void 0});await store.initialize();return store}}));if(config.mode==="webhook"){providers.push((0,import_sdk8.storeProvider)({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}}))}const externalApprover=externalApproverProvider(external);if(externalApprover)providers.push(externalApprover);if(config.enableAudit){providers.push({name:"approval:audit",provide:ApprovalAuditToken,inject:()=>[import_sdk8.ScopeEntry],useFactory:scope=>new LoggerAuditSink(scope.logger.child("ApprovalAudit"))})}providers.push({name:"approval:service",provide:ApprovalServiceToken,scope:import_sdk8.ProviderScope.CONTEXT,inject:()=>[ApprovalStoreToken,import_sdk8.FRONTMCP_CONTEXT,import_sdk8.ScopeEntry],useFactory:(store,ctx,scope)=>{const{sessionId,userId}=resolveApprovalIdentity(ctx);return createApprovalService(store,sessionId,userId,toolRequirementLookup(scope))}});return providers});ApprovalPlugin=__decorateClass([(0,import_sdk8.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,ApprovalConfigurationError,ApprovalError,ApprovalExpiredError,ApprovalOperationError,ApprovalPlugin,ApprovalPluginClass,ApprovalRequiredError,ApprovalScope,ApprovalScopeNotAllowedError,ApprovalService,ApprovalServiceToken,ApprovalState,ApprovalStorageStore,ApprovalStoreToken,ChallengeService,ChallengeServiceToken,ChallengeValidationError,adminGrantor,adminRevoker,agentGrantor,apiGrantor,createApprovalMemoryStore,createApprovalService,createMemoryChallengeService,customGrantor,delegationDepth,delegationProblem,expiryRevoker,extendDelegation,installApprovalContextExtension,isApiGrantor,isAutoGrantor,isDelegatedGrantor,isGrantorSource,isHumanGrantor,normalizeGrantor,normalizeRevoker,oauthGrantor,policyGrantor,policyRevoker,sessionEndRevoker,systemGrantor,testGrantor,userGrantor,userRevoker});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontmcp/plugin-approval",
3
- "version": "1.12.0",
3
+ "version": "1.12.1",
4
4
  "description": "Approval plugin for FrontMCP: refuses to run marked tools until an approval is recorded for the caller",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "license": "Apache-2.0",
@@ -50,13 +50,13 @@
50
50
  }
51
51
  },
52
52
  "dependencies": {
53
- "@frontmcp/utils": "1.12.0",
53
+ "@frontmcp/utils": "1.12.1",
54
54
  "ioredis": "^5.8.0",
55
55
  "reflect-metadata": "^0.2.2"
56
56
  },
57
57
  "peerDependencies": {
58
- "@frontmcp/lazy-zod": "1.12.0",
59
- "@frontmcp/sdk": "1.12.0",
58
+ "@frontmcp/lazy-zod": "1.12.1",
59
+ "@frontmcp/sdk": "1.12.1",
60
60
  "@vercel/kv": "^2.0.0 || ^3.0.0"
61
61
  },
62
62
  "peerDependenciesMeta": {
@@ -65,7 +65,7 @@
65
65
  }
66
66
  },
67
67
  "devDependencies": {
68
- "@frontmcp/sdk": "1.12.0",
68
+ "@frontmcp/sdk": "1.12.1",
69
69
  "reflect-metadata": "^0.2.2"
70
70
  }
71
71
  }
@@ -111,7 +111,8 @@ export declare class ChallengeService {
111
111
  /** Clears the mark {@link claimPendingRequest} set, so the next call sends the request again. */
112
112
  releasePendingRequest(key: string): Promise<void>;
113
113
  /**
114
- * Mark a challenge as having been sent to webhook.
114
+ * Mark a challenge as having been sent to webhook. A challenge a callback already used stays used: this returns
115
+ * `false` and writes nothing, as it does on a backend without conditional writes.
115
116
  */
116
117
  markWebhookSent(codeChallenge: string): Promise<boolean>;
117
118
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"challenge.service.d.ts","sourceRoot":"","sources":["../../src/services/challenge.service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAOL,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAChB,KAAK,aAAa,EACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAKjE;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,OAAO,CAAC,EAAE,aAAa,CAAC;IAExB;;OAEG;IACH,eAAe,CAAC,EAAE,WAAW,GAAG,iBAAiB,CAAC;IAElD;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,6BAA6B;IAC7B,MAAM,EAAE,MAAM,CAAC;IAEf,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAElB,2BAA2B;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,qEAAqE;IACrE,OAAO,CAAC,EAAE,eAAe,CAAC;IAE1B,+BAA+B;IAC/B,cAAc,EAAE,MAAM,CAAC;IAEvB,sCAAsC;IACtC,WAAW,EAAE;QACX,QAAQ,EAAE,MAAM,CAAC;QACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IAEF,yCAAyC;IACzC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;GASG;AACH,qBAKa,gBAAgB;IAC3B,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAEtB;IACF,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,YAAY,CAAS;gBAEjB,OAAO,GAAE,uBAA4B;IASjD;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAejC,OAAO,CAAC,iBAAiB;IAMzB;;;;OAIG;IACG,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC;QAC9D,YAAY,EAAE,MAAM,CAAC;QACrB,aAAa,EAAE,MAAM,CAAC;QACtB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IA0BF;;;;OAIG;IACG,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;IAWtE;;;;OAIG;IACG,OAAO,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC;IAKzE,qHAAqH;YACvG,IAAI;IAWlB,6FAA6F;YAC/E,iBAAiB;IAS/B;;;OAGG;IACG,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,SAAiC,GAAG,OAAO,CAAC,OAAO,CAAC;IAcrG,iGAAiG;IAC3F,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD;;OAEG;IACG,eAAe,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAqB9D;;OAEG;IACG,YAAY,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAe1E;;OAEG;IACG,eAAe,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAU9D;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAM7B;AAED;;GAEG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,GAAE,IAAI,CAAC,uBAAuB,EAAE,SAAS,GAAG,iBAAiB,CAAM,GACzE,gBAAgB,CAMlB"}
1
+ {"version":3,"file":"challenge.service.d.ts","sourceRoot":"","sources":["../../src/services/challenge.service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAOL,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAChB,KAAK,aAAa,EACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAKjE;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,OAAO,CAAC,EAAE,aAAa,CAAC;IAExB;;OAEG;IACH,eAAe,CAAC,EAAE,WAAW,GAAG,iBAAiB,CAAC;IAElD;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,6BAA6B;IAC7B,MAAM,EAAE,MAAM,CAAC;IAEf,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAElB,2BAA2B;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,qEAAqE;IACrE,OAAO,CAAC,EAAE,eAAe,CAAC;IAE1B,+BAA+B;IAC/B,cAAc,EAAE,MAAM,CAAC;IAEvB,sCAAsC;IACtC,WAAW,EAAE;QACX,QAAQ,EAAE,MAAM,CAAC;QACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,aAAa,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IAEF,yCAAyC;IACzC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;GASG;AACH,qBAKa,gBAAgB;IAC3B,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAEtB;IACF,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,YAAY,CAAS;gBAEjB,OAAO,GAAE,uBAA4B;IASjD;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAejC,OAAO,CAAC,iBAAiB;IAMzB;;;;OAIG;IACG,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC;QAC9D,YAAY,EAAE,MAAM,CAAC;QACrB,aAAa,EAAE,MAAM,CAAC;QACtB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IA0BF;;;;OAIG;IACG,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;IAWtE;;;;OAIG;IACG,OAAO,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC;IAKzE,qHAAqH;YACvG,IAAI;IAWlB,6FAA6F;YAC/E,iBAAiB;IAS/B;;;OAGG;IACG,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,SAAiC,GAAG,OAAO,CAAC,OAAO,CAAC;IAcrG,iGAAiG;IAC3F,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvD;;;OAGG;IACG,eAAe,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IA2B9D;;OAEG;IACG,YAAY,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAe1E;;OAEG;IACG,eAAe,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAU9D;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAM7B;AAED;;GAEG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,GAAE,IAAI,CAAC,uBAAuB,EAAE,SAAS,GAAG,iBAAiB,CAAM,GACzE,gBAAgB,CAMlB"}
@@ -61,31 +61,40 @@ export declare class ApprovalStorageStore implements ApprovalStore {
61
61
  initialize(): Promise<void>;
62
62
  private get revocations();
63
63
  private ensureInitialized;
64
+ /**
65
+ * The key of `owner`'s record of a tool. Ids are encoded, so an id holding `:` cannot spell another
66
+ * owner's key; an id with neither `:` nor `%` is stored as it always was.
67
+ */
64
68
  private buildKey;
65
69
  /**
66
- * The key of a time-limited approval granted to a session alone or a user alone. Kept apart from
67
- * that session's or user's own key, so a time-limited grant never replaces the session or user
68
- * approval, or a denial recorded there. (With both a session and a user, `buildKey` is already distinct.)
70
+ * The key a new record is stored under. A time-limited approval without a context has a key of its
71
+ * own, so it never replaces the session or user record, or a denial recorded there.
69
72
  */
70
- private timeLimitedKey;
71
- /** The key a new record is stored under. */
72
73
  private recordKey;
74
+ /** Whether `record` names exactly the session, user and context of `owner`, the owner of the key it was read from. */
75
+ private isOwnedBy;
73
76
  private parseRecord;
74
77
  private isExpired;
75
78
  /** An approval whose delegation chain `maxDelegationDepth` refuses: deeper than it allows, or broken. */
76
79
  private isOverDelegated;
77
80
  /**
78
- * The keys a caller's approvals of a tool can be stored under: its session, its user, both
79
- * (time-limited and context grants made through `ApprovalService`), the time-limited keys of its
80
- * session and its user, and, for a call in a server-established context, that context (granted
81
- * to the session and the user, or to the session before it had a user, the way a session approval
82
- * stays in force once the caller's user is known). Records written by 1.8.2 sit under the same
83
- * keys (a time-limited grant without a user under the session key), so they are still read.
81
+ * The owners of the records that apply to a caller: its session, its user, both (an external
82
+ * denial, and time-limited and context grants made through `ApprovalService`), the time-limited
83
+ * records of each, and, for a call in a server-established context, that context (granted to the
84
+ * session and the user, or to the session before it had a user, the way a session approval stays
85
+ * in force once the caller's user is known).
86
+ */
87
+ private callerOwners;
88
+ /**
89
+ * The keys a caller's records of a tool can be stored under, each with the owner a record read
90
+ * from it must name. Keys written up to 1.12.0, with unencoded ids, are read too, as are records
91
+ * written by 1.8.2 (a time-limited grant without a user under the session key).
84
92
  */
85
93
  private callerKeys;
86
94
  /**
87
95
  * Every unexpired record that applies to this caller: session, user, time-limited and, when
88
- * `context` is given, context-specific approvals and denials.
96
+ * `context` is given, context-specific approvals and denials. A record that names another
97
+ * session, user or context than the key it was read from is ignored.
89
98
  */
90
99
  getApprovals(toolId: string, sessionId: string, userId?: string, context?: ApprovalContext): Promise<ApprovalRecord[]>;
91
100
  /**
@@ -106,10 +115,16 @@ export declare class ApprovalStorageStore implements ApprovalStore {
106
115
  /**
107
116
  * Deletes the key that holds `record`, if it still does, and reports whether this call deleted
108
117
  * it. Two calls racing for one approval both find it, but only one deletes it, and a denial or
109
- * approval written to the key after it was read is kept.
118
+ * approval written to the key after it was read is kept. A backend without compare-and-delete
119
+ * cannot promise that, so it throws `ApprovalConfigurationError`.
110
120
  */
111
121
  consumeApproval(record: ApprovalRecord, sessionId: string, userId?: string, context?: ApprovalContext): Promise<boolean>;
112
- /** Deletes `key` only while it still holds `storedValue`, in one step where the backend allows. */
122
+ /** Deletes `key` only while it holds `storedValue`, in one step; a backend that cannot do that is refused. */
123
+ private deleteOnce;
124
+ /**
125
+ * Deletes `key` only while it still holds `storedValue`: in one step where the backend allows,
126
+ * otherwise by reading it again just before deleting it.
127
+ */
113
128
  private deleteIfUnchanged;
114
129
  getRevocations(toolId: string, sessionId: string, userId?: string, context?: ApprovalContext): Promise<ApprovalRecord[]>;
115
130
  isApproved(toolId: string, sessionId: string, userId?: string, context?: ApprovalContext): Promise<boolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"approval-storage.store.d.ts","sourceRoot":"","sources":["../../src/stores/approval-storage.store.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAKL,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAChB,KAAK,aAAa,EACnB,MAAM,iBAAiB,CAAC;AAKzB,OAAO,EAAiB,KAAK,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAChF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AACnG,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,oBAAoB,EACpB,qBAAqB,EACtB,MAAM,4BAA4B,CAAC;AAsCpC;;GAEG;AACH,MAAM,WAAW,2BAA2B;IAC1C;;;OAGG;IACH,OAAO,CAAC,EAAE,aAAa,CAAC;IAExB;;OAEG;IACH,eAAe,CAAC,EAAE,WAAW,GAAG,iBAAiB,CAAC;IAElD;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAEhC;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAE5B,kFAAkF;IAClF,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC3B;AAED,uGAAuG;AACvG,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAM9C;;;GAGG;AACH,qBAKa,oBAAqB,YAAW,aAAa;IACxD,OAAO,CAAC,OAAO,CAAqB;IACpC,gGAAgG;IAChG,OAAO,CAAC,iBAAiB,CAAC,CAAoB;IAC9C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAGtB;IACF,OAAO,CAAC,eAAe,CAAC,CAAiB;IACzC,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,YAAY,CAAS;gBAEjB,OAAO,GAAE,2BAAgC;IAWrD;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAwBjC,OAAO,KAAK,WAAW,GAMtB;IAED,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,QAAQ;IAQhB;;;;OAIG;IACH,OAAO,CAAC,cAAc;IAItB,4CAA4C;IAC5C,OAAO,CAAC,SAAS;IAQjB,OAAO,CAAC,WAAW;IAcnB,OAAO,CAAC,SAAS;IAIjB,yGAAyG;IACzG,OAAO,CAAC,eAAe;IAOvB;;;;;;;OAOG;IACH,OAAO,CAAC,UAAU;IAgBlB;;;OAGG;IACG,YAAY,CAChB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,cAAc,EAAE,CAAC;IAa5B;;;OAGG;IACG,WAAW,CACf,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC;IAKhC,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAwC/D,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,cAAc,CAAC;IAIrE,YAAY,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,cAAc,CAAC;YAI5D,WAAW;IAyCzB;;;;OAIG;IACG,cAAc,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,OAAO,CAAC;IAuDtE;;;;OAIG;IACG,eAAe,CACnB,MAAM,EAAE,cAAc,EACtB,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,OAAO,CAAC;IAanB,mGAAmG;YACrF,iBAAiB;IASzB,cAAc,CAClB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,cAAc,EAAE,CAAC;IAWtB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC;IAK3G,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAsBzD,qBAAqB,IAAI,OAAO,CAAC,MAAM,CAAC;IAyBxC,QAAQ,IAAI,OAAO,CAAC;QACxB,cAAc,EAAE,MAAM,CAAC;QACvB,OAAO,EAAE,MAAM,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;QACvC,OAAO,EAAE,MAAM,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;KACxC,CAAC;IAsCI,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAa7B;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,GAAE,IAAI,CAAC,2BAA2B,EAAE,SAAS,GAAG,iBAAiB,CAAM,GAC7E,oBAAoB,CAMtB"}
1
+ {"version":3,"file":"approval-storage.store.d.ts","sourceRoot":"","sources":["../../src/stores/approval-storage.store.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAKL,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAChB,KAAK,aAAa,EACnB,MAAM,iBAAiB,CAAC;AAWzB,OAAO,EAAiB,KAAK,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAChF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AACnG,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,oBAAoB,EACpB,qBAAqB,EACtB,MAAM,4BAA4B,CAAC;AAoEpC;;GAEG;AACH,MAAM,WAAW,2BAA2B;IAC1C;;;OAGG;IACH,OAAO,CAAC,EAAE,aAAa,CAAC;IAExB;;OAEG;IACH,eAAe,CAAC,EAAE,WAAW,GAAG,iBAAiB,CAAC;IAElD;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAEhC;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAE5B,kFAAkF;IAClF,KAAK,CAAC,EAAE,iBAAiB,CAAC;CAC3B;AAED,uGAAuG;AACvG,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAM9C;;;GAGG;AACH,qBAKa,oBAAqB,YAAW,aAAa;IACxD,OAAO,CAAC,OAAO,CAAqB;IACpC,gGAAgG;IAChG,OAAO,CAAC,iBAAiB,CAAC,CAAoB;IAC9C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAGtB;IACF,OAAO,CAAC,eAAe,CAAC,CAAiB;IACzC,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,YAAY,CAAS;gBAEjB,OAAO,GAAE,2BAAgC;IAWrD;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAwBjC,OAAO,KAAK,WAAW,GAMtB;IAED,OAAO,CAAC,iBAAiB;IAMzB;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAShB;;;OAGG;IACH,OAAO,CAAC,SAAS;IAUjB,sHAAsH;IACtH,OAAO,CAAC,SAAS;IAQjB,OAAO,CAAC,WAAW;IAcnB,OAAO,CAAC,SAAS;IAIjB,yGAAyG;IACzG,OAAO,CAAC,eAAe;IAOvB;;;;;;OAMG;IACH,OAAO,CAAC,YAAY;IAiBpB;;;;OAIG;IACH,OAAO,CAAC,UAAU;IAUlB;;;;OAIG;IACG,YAAY,CAChB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,cAAc,EAAE,CAAC;IAmB5B;;;OAGG;IACG,WAAW,CACf,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC;IAKhC,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAwC/D,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,cAAc,CAAC;IAIrE,YAAY,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,cAAc,CAAC;YAI5D,WAAW;IAyCzB;;;;OAIG;IACG,cAAc,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,OAAO,CAAC;IAkDtE;;;;;OAKG;IACG,eAAe,CACnB,MAAM,EAAE,cAAc,EACtB,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,OAAO,CAAC;IAanB,8GAA8G;YAChG,UAAU;IASxB;;;OAGG;YACW,iBAAiB;IAUzB,cAAc,CAClB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,cAAc,EAAE,CAAC;IAWtB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC;IAK3G,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAiCzD,qBAAqB,IAAI,OAAO,CAAC,MAAM,CAAC;IAoBxC,QAAQ,IAAI,OAAO,CAAC;QACxB,cAAc,EAAE,MAAM,CAAC;QACvB,OAAO,EAAE,MAAM,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;QACvC,OAAO,EAAE,MAAM,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;KACxC,CAAC;IAsCI,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAa7B;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,GAAE,IAAI,CAAC,2BAA2B,EAAE,SAAS,GAAG,iBAAiB,CAAM,GAC7E,oBAAoB,CAMtB"}