@frontmcp/plugin-approval 1.11.2 → 1.12.0-rc.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/README.md +183 -13
- package/approval/delegation.d.ts +30 -0
- package/approval/delegation.d.ts.map +1 -0
- package/approval/errors.d.ts +6 -1
- package/approval/errors.d.ts.map +1 -1
- package/approval/factories.d.ts +1 -1
- package/approval/factories.d.ts.map +1 -1
- package/approval/index.d.ts +4 -3
- package/approval/index.d.ts.map +1 -1
- package/approval/schemas.d.ts +28 -0
- package/approval/schemas.d.ts.map +1 -1
- package/approval/types.d.ts +19 -1
- package/approval/types.d.ts.map +1 -1
- package/approval.context-extension.d.ts.map +1 -1
- package/approval.identity.d.ts +2 -0
- package/approval.identity.d.ts.map +1 -1
- package/approval.options.d.ts +43 -0
- package/approval.options.d.ts.map +1 -0
- package/approval.plugin.d.ts +62 -18
- package/approval.plugin.d.ts.map +1 -1
- package/approval.symbols.d.ts +11 -2
- package/approval.symbols.d.ts.map +1 -1
- package/audit/approval-audit.d.ts +44 -0
- package/audit/approval-audit.d.ts.map +1 -0
- package/esm/index.mjs +1 -1
- package/esm/package.json +5 -5
- package/external/approval-callback.flow.d.ts +36 -0
- package/external/approval-callback.flow.d.ts.map +1 -0
- package/external/approval-decisions.d.ts +60 -0
- package/external/approval-decisions.d.ts.map +1 -0
- package/external/outbound-request.d.ts +32 -0
- package/external/outbound-request.d.ts.map +1 -0
- package/external/recheck-approver.d.ts +49 -0
- package/external/recheck-approver.d.ts.map +1 -0
- package/external/webhook-approver.d.ts +44 -0
- package/external/webhook-approver.d.ts.map +1 -0
- package/external/webhook-signature.d.ts +12 -0
- package/external/webhook-signature.d.ts.map +1 -0
- package/flows/index.d.ts +3 -2
- package/flows/index.d.ts.map +1 -1
- package/hooks/approval-check.hook.d.ts +5 -0
- package/hooks/approval-check.hook.d.ts.map +1 -1
- package/index.d.ts +3 -2
- package/index.d.ts.map +1 -1
- package/index.js +1 -1
- package/package.json +5 -5
- package/services/challenge.service.d.ts +20 -1
- package/services/challenge.service.d.ts.map +1 -1
- package/stores/approval-storage.store.d.ts +15 -0
- package/stores/approval-storage.store.d.ts.map +1 -1
- package/stores/approval-store.interface.d.ts +6 -0
- package/stores/approval-store.interface.d.ts.map +1 -1
- package/types/approval.types.d.ts +41 -17
- package/types/approval.types.d.ts.map +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"approval-decisions.d.ts","sourceRoot":"","sources":["../../src/external/approval-decisions.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAKpD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AAC9E,OAAO,KAAK,EAAE,aAAa,EAAwB,MAAM,oCAAoC,CAAC;AAC9F,OAAO,EAAE,aAAa,EAAE,KAAK,eAAe,EAAE,KAAK,eAAe,EAAE,KAAK,uBAAuB,EAAE,MAAM,UAAU,CAAC;AAEnH,gGAAgG;AAChG,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,WAAW,EAAE,uBAAuB,CAAC;IACrC,wEAAwE;IACxE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,8GAA8G;AAC9G,MAAM,MAAM,uBAAuB,GAAG,UAAU,GAAG,QAAQ,GAAG,SAAS,CAAC;AAExE,2EAA2E;AAC3E,MAAM,WAAW,gBAAgB;IAC/B,gDAAgD;IAChD,QAAQ,CAAC,GAAG,EAAE,SAAS,GAAG,SAAS,CAAC;IACpC,eAAe,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC;CAC9E;AAED,wCAAwC;AACxC,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,eAAe,CAAC;CAC3B;AAED,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,6FAA6F;AAC7F,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,eAAe,EAAE,QAAQ,GAAG,WAAW,GAAG,QAAQ,CAAC,GAAG,MAAM,CAE3G;AAmBD,wDAAwD;AACxD,qBAAa,wBAAwB;IAEjC,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAFN,KAAK,EAAE,aAAa,EACpB,aAAa,EAAE,yBAAyB,EACxC,MAAM,EAAE,cAAc;IAGzC;;;;OAIG;IACG,OAAO,CAAC,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IA8BrG,8EAA8E;IACxE,IAAI,CAAC,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAiB/G"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one way the plugin calls an external approval system: a JSON POST with a timeout, no redirects followed and a
|
|
3
|
+
* bounded answer.
|
|
4
|
+
*
|
|
5
|
+
* @module @frontmcp/plugin-approval
|
|
6
|
+
*/
|
|
7
|
+
/** How long the plugin waits for an approval system to answer one request. */
|
|
8
|
+
export declare const OUTBOUND_TIMEOUT_MS = 10000;
|
|
9
|
+
/** The largest answer the plugin reads from an approval system, in bytes. */
|
|
10
|
+
export declare const OUTBOUND_MAX_RESPONSE_BYTES: number;
|
|
11
|
+
/** A request that got no usable answer. Its message names no URL, header or body, so it can be logged. */
|
|
12
|
+
export declare class OutboundRequestError extends Error {
|
|
13
|
+
readonly name = "OutboundRequestError";
|
|
14
|
+
}
|
|
15
|
+
export interface OutboundRequest {
|
|
16
|
+
url: string;
|
|
17
|
+
body: string;
|
|
18
|
+
headers: Record<string, string>;
|
|
19
|
+
/** Cancels the request, as the tool call that made it is cancelled. */
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
/** @default OUTBOUND_TIMEOUT_MS */
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
export interface OutboundAnswer {
|
|
25
|
+
status: number;
|
|
26
|
+
body: string;
|
|
27
|
+
}
|
|
28
|
+
/** POSTs `body` as JSON and returns the answer, or throws {@link OutboundRequestError}. */
|
|
29
|
+
export declare function postJson(request: OutboundRequest): Promise<OutboundAnswer>;
|
|
30
|
+
/** The origin of a URL, which is all a log line names of it. */
|
|
31
|
+
export declare function originOf(url: string): string;
|
|
32
|
+
//# sourceMappingURL=outbound-request.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"outbound-request.d.ts","sourceRoot":"","sources":["../../src/external/outbound-request.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,8EAA8E;AAC9E,eAAO,MAAM,mBAAmB,QAAS,CAAC;AAE1C,6EAA6E;AAC7E,eAAO,MAAM,2BAA2B,QAAY,CAAC;AAErD,0GAA0G;AAC1G,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,SAAkB,IAAI,0BAA0B;CACjD;AAED,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,uEAAuE;IACvE,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,mCAAmC;IACnC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;CACd;AAqCD,2FAA2F;AAC3F,wBAAsB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CA4BhF;AAED,gEAAgE;AAChE,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE5C"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `mode: 'recheck'` with `recheck.url`: a call that needs an approval polls the approval system until it decides, or
|
|
3
|
+
* `recheck.maxAttempts` polls go unanswered.
|
|
4
|
+
*
|
|
5
|
+
* @module @frontmcp/plugin-approval
|
|
6
|
+
*/
|
|
7
|
+
import type { FrontMcpLogger } from '@frontmcp/sdk';
|
|
8
|
+
import type { ResolvedRecheck } from '../approval.options';
|
|
9
|
+
import { type ApprovalDecisionRecorder, type ExternalApprovalOutcome, type ExternalApprover, type PendingApprovalCall } from './approval-decisions';
|
|
10
|
+
/** The body of each poll of `recheck.url`. */
|
|
11
|
+
export interface RecheckRequest {
|
|
12
|
+
type: 'approval.status';
|
|
13
|
+
/** The same for every poll and call of one caller to one tool. */
|
|
14
|
+
requestId: string;
|
|
15
|
+
attempt: number;
|
|
16
|
+
toolId: string;
|
|
17
|
+
toolName: string;
|
|
18
|
+
category?: string;
|
|
19
|
+
riskLevel?: string;
|
|
20
|
+
approvalMessage?: string;
|
|
21
|
+
requestedScope: string;
|
|
22
|
+
allowedScopes?: string[];
|
|
23
|
+
maxTtlMs?: number;
|
|
24
|
+
userId?: string;
|
|
25
|
+
timestamp: number;
|
|
26
|
+
}
|
|
27
|
+
/** What the recheck writes to: the store decisions go to. */
|
|
28
|
+
export interface RecheckDependencies {
|
|
29
|
+
readonly decisions: ApprovalDecisionRecorder;
|
|
30
|
+
}
|
|
31
|
+
export declare class RecheckApprover implements ExternalApprover {
|
|
32
|
+
private readonly recheck;
|
|
33
|
+
private readonly dependencies;
|
|
34
|
+
private readonly logger;
|
|
35
|
+
readonly via = "recheck";
|
|
36
|
+
constructor(recheck: ResolvedRecheck, dependencies: RecheckDependencies, logger: FrontMcpLogger);
|
|
37
|
+
/**
|
|
38
|
+
* Polls `recheck.url` every `recheck.interval`, at most `recheck.maxAttempts` times, while it answers
|
|
39
|
+
* `{ approved: false, pending: true }`. An approval is recorded (and an `alwaysPrompt` tool's lets this call alone
|
|
40
|
+
* through), `{ approved: false }` refuses the call as denied, and a failed poll stops and leaves it pending.
|
|
41
|
+
*/
|
|
42
|
+
requestApproval(call: PendingApprovalCall): Promise<ExternalApprovalOutcome>;
|
|
43
|
+
private approve;
|
|
44
|
+
/** One poll; `undefined` when the call has no token to forward with `auth: 'jwt'`. */
|
|
45
|
+
private poll;
|
|
46
|
+
/** The headers `recheck.auth` adds, or `undefined` when the call has no token for `auth: 'jwt'`. */
|
|
47
|
+
private authorization;
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=recheck-approver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recheck-approver.d.ts","sourceRoot":"","sources":["../../src/external/recheck-approver.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAGpD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAEL,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACzB,MAAM,sBAAsB,CAAC;AAI9B,8CAA8C;AAC9C,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,iBAAiB,CAAC;IACxB,kEAAkE;IAClE,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AA4BD,6DAA6D;AAC7D,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,SAAS,EAAE,wBAAwB,CAAC;CAC9C;AAED,qBAAa,eAAgB,YAAW,gBAAgB;IAIpD,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IALzB,QAAQ,CAAC,GAAG,aAAa;gBAGN,OAAO,EAAE,eAAe,EACxB,YAAY,EAAE,mBAAmB,EACjC,MAAM,EAAE,cAAc;IAGzC;;;;OAIG;IACG,eAAe,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,uBAAuB,CAAC;YAqBpE,OAAO;IAUrB,sFAAsF;YACxE,IAAI;IAoClB,oGAAoG;YACtF,aAAa;CAmB5B"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `mode: 'webhook'` with `webhook.url`: a call that needs an approval sends one signed request to the approval system,
|
|
3
|
+
* which decides by POSTing back to `webhook.callbackPath`.
|
|
4
|
+
*
|
|
5
|
+
* @module @frontmcp/plugin-approval
|
|
6
|
+
*/
|
|
7
|
+
import { httpRespond, type FrontMcpLogger } from '@frontmcp/sdk';
|
|
8
|
+
import type { ResolvedWebhook } from '../approval.options';
|
|
9
|
+
import type { ChallengeService } from '../services/challenge.service';
|
|
10
|
+
import { type ApprovalDecisionRecorder, type ExternalApprovalOutcome, type ExternalApprover, type PendingApprovalCall } from './approval-decisions';
|
|
11
|
+
/** The largest callback body the route reads, in bytes. */
|
|
12
|
+
export declare const MAX_CALLBACK_BYTES: number;
|
|
13
|
+
/** The callback route's JSON answer. */
|
|
14
|
+
export type CallbackAnswer = ReturnType<typeof httpRespond.json>;
|
|
15
|
+
/** The request the callback route reads: its headers and the exact bytes of its body. */
|
|
16
|
+
export interface CallbackRequest {
|
|
17
|
+
headers: Record<string, unknown>;
|
|
18
|
+
bodyBytes?: Uint8Array;
|
|
19
|
+
}
|
|
20
|
+
/** What the webhook reads and writes: the pending requests, and the store decisions go to. */
|
|
21
|
+
export interface WebhookDependencies {
|
|
22
|
+
readonly challenges: ChallengeService;
|
|
23
|
+
readonly decisions: ApprovalDecisionRecorder;
|
|
24
|
+
}
|
|
25
|
+
export declare class WebhookApprover implements ExternalApprover {
|
|
26
|
+
private readonly webhook;
|
|
27
|
+
private readonly dependencies;
|
|
28
|
+
private readonly logger;
|
|
29
|
+
readonly via = "webhook";
|
|
30
|
+
constructor(webhook: ResolvedWebhook, dependencies: WebhookDependencies, logger: FrontMcpLogger);
|
|
31
|
+
private get challenges();
|
|
32
|
+
/**
|
|
33
|
+
* Sends the approval request for a refused call, once per caller and tool until it is decided or `challengeTtl`
|
|
34
|
+
* passes, and reports the call as pending: the decision arrives on the callback route.
|
|
35
|
+
*/
|
|
36
|
+
requestApproval(call: PendingApprovalCall): Promise<ExternalApprovalOutcome>;
|
|
37
|
+
/**
|
|
38
|
+
* A decision POSTed to the callback route. It must be signed with `webhook.secret` within the last five minutes and
|
|
39
|
+
* name a pending request's `codeVerifier`; the request is used up, so a replay does nothing. Every signed,
|
|
40
|
+
* well-formed callback gets the same `202`, whether or not it matched a request.
|
|
41
|
+
*/
|
|
42
|
+
handleCallback(request: CallbackRequest): Promise<CallbackAnswer>;
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=webhook-approver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webhook-approver.d.ts","sourceRoot":"","sources":["../../src/external/webhook-approver.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAsB,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAGrF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAEtE,OAAO,EAEL,KAAK,wBAAwB,EAC7B,KAAK,uBAAuB,EAC5B,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACzB,MAAM,sBAAsB,CAAC;AAU9B,2DAA2D;AAC3D,eAAO,MAAM,kBAAkB,QAAY,CAAC;AAW5C,wCAAwC;AACxC,MAAM,MAAM,cAAc,GAAG,UAAU,CAAC,OAAO,WAAW,CAAC,IAAI,CAAC,CAAC;AAEjE,yFAAyF;AACzF,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,SAAS,CAAC,EAAE,UAAU,CAAC;CACxB;AAgBD,8FAA8F;AAC9F,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,UAAU,EAAE,gBAAgB,CAAC;IACtC,QAAQ,CAAC,SAAS,EAAE,wBAAwB,CAAC;CAC9C;AAED,qBAAa,eAAgB,YAAW,gBAAgB;IAIpD,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IALzB,QAAQ,CAAC,GAAG,aAAa;gBAGN,OAAO,EAAE,eAAe,EACxB,YAAY,EAAE,mBAAmB,EACjC,MAAM,EAAE,cAAc;IAGzC,OAAO,KAAK,UAAU,GAErB;IAED;;;OAGG;IACG,eAAe,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAgElF;;;;OAIG;IACG,cAAc,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;CA2DxE"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard Webhooks signatures on approval requests and callbacks, signed and checked by `@frontmcp/utils`.
|
|
3
|
+
*
|
|
4
|
+
* @module @frontmcp/plugin-approval
|
|
5
|
+
*/
|
|
6
|
+
import { type SignedWebhookMessage, type WebhookSignatureCheck } from '@frontmcp/utils';
|
|
7
|
+
export { signingKeyOf, WEBHOOK_ID_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER } from '@frontmcp/utils';
|
|
8
|
+
/** The headers that sign `body`: a new message id, the current time and the signature over both and the body. */
|
|
9
|
+
export declare function signatureHeaders(signingKey: Uint8Array, body: string, now?: number): Record<string, string>;
|
|
10
|
+
/** Checks a signed message against the key: its timestamp within five minutes of `now`, and its signature. */
|
|
11
|
+
export declare function checkSignature(signingKey: Uint8Array, message: SignedWebhookMessage, now?: number): WebhookSignatureCheck;
|
|
12
|
+
//# sourceMappingURL=webhook-signature.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webhook-signature.d.ts","sourceRoot":"","sources":["../../src/external/webhook-signature.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAIL,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC3B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEtH,iHAAiH;AACjH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,SAAa,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAG/G;AAED,8GAA8G;AAC9G,wBAAgB,cAAc,CAC5B,UAAU,EAAE,UAAU,EACtB,OAAO,EAAE,oBAAoB,EAC7B,GAAG,SAAa,GACf,qBAAqB,CAEvB"}
|
package/flows/index.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Flow exports for ApprovalPlugin.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* `approval:webhook-callback` serves `webhook.callbackPath` in webhook mode; recheck polling runs inside the approval
|
|
5
|
+
* gate, in `tools:call-tool`.
|
|
5
6
|
*
|
|
6
7
|
* @module @frontmcp/plugin-approval
|
|
7
8
|
*/
|
|
8
|
-
export {};
|
|
9
|
+
export { default as ApprovalCallbackFlow } from '../external/approval-callback.flow';
|
|
9
10
|
//# sourceMappingURL=index.d.ts.map
|
package/flows/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/flows/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/flows/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,oCAAoC,CAAC"}
|
|
@@ -25,6 +25,11 @@ export default class ApprovalCheckPlugin extends DynamicPlugin<Record<string, ne
|
|
|
25
25
|
*/
|
|
26
26
|
checkApproval(flowCtx: FlowCtxOf<'tools:call-tool'>): Promise<void>;
|
|
27
27
|
private enforceApproval;
|
|
28
|
+
/**
|
|
29
|
+
* A provider the plugin's options may leave out: the approval system `webhook.url` or `recheck.url` configures, or
|
|
30
|
+
* the audit trail of `enableAudit`. `undefined` without it.
|
|
31
|
+
*/
|
|
32
|
+
private optional;
|
|
28
33
|
/**
|
|
29
34
|
* The stores of every approval gate that runs for the tool: this plugin's, and that of each other
|
|
30
35
|
* `ApprovalCheckPlugin` whose hook the scope runs for it (an `ApprovalPlugin` on the server and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"approval-check.hook.d.ts","sourceRoot":"","sources":["../../src/hooks/approval-check.hook.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,
|
|
1
|
+
{"version":3,"file":"approval-check.hook.d.ts","sourceRoot":"","sources":["../../src/hooks/approval-check.hook.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,aAAa,EAMb,KAAK,SAAS,EAEf,MAAM,eAAe,CAAC;AA0BvB;;;;;GAKG;AAOH,MAAM,CAAC,OAAO,OAAO,mBAAoB,SAAQ,aAAa,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACnF;;;;;;;;;;;OAWG;IAEG,aAAa,CAAC,OAAO,EAAE,SAAS,CAAC,iBAAiB,CAAC;YAwB3C,eAAe;IAsF7B;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAShB;;;;OAIG;IACH,OAAO,CAAC,cAAc;IAoBtB;;;;;;OAMG;YACW,eAAe;IAmB7B;;;OAGG;YACW,aAAa;IAc3B;;;;;;;;OAQG;IACH,OAAO,CAAC,iBAAiB;IAOzB,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,oBAAoB;YAUd,sBAAsB;CAsBrC"}
|
package/index.d.ts
CHANGED
|
@@ -25,12 +25,13 @@
|
|
|
25
25
|
* }
|
|
26
26
|
* ```
|
|
27
27
|
*/
|
|
28
|
-
export { default as ApprovalPlugin, ApprovalPlugin as ApprovalPluginClass, type ApprovalPluginOptions, } from './approval.plugin';
|
|
28
|
+
export { default as ApprovalPlugin, ApprovalPlugin as ApprovalPluginClass, type ApprovalPluginOptions, type RecheckHeaders, } from './approval.plugin';
|
|
29
|
+
export type { RecheckRequest } from './external/recheck-approver';
|
|
29
30
|
export { ApprovalStoreToken, ApprovalServiceToken, ChallengeServiceToken } from './approval.symbols';
|
|
30
31
|
export * from './types';
|
|
31
32
|
export { type ApprovalStore, type ApprovalQuery, type GrantApprovalOptions, type RevokeApprovalOptions, ApprovalStorageStore, type ApprovalStorageStoreOptions, createApprovalMemoryStore, } from './stores';
|
|
32
33
|
export { ApprovalService, createApprovalService, type GrantOptions, type RevokeOptions, ChallengeService, createMemoryChallengeService, type ChallengeServiceOptions, type CreateChallengeOptions, } from './services';
|
|
33
34
|
export { ApprovalCheckPlugin } from './hooks';
|
|
34
35
|
export { installApprovalContextExtension } from './approval.context-extension';
|
|
35
|
-
export { ApprovalError, ApprovalRequiredError, ApprovalOperationError, ApprovalScopeNotAllowedError, ApprovalExpiredError, ChallengeValidationError, userGrantor, adminGrantor, policyGrantor, systemGrantor, agentGrantor, apiGrantor, oauthGrantor, testGrantor, customGrantor, normalizeGrantor, userRevoker, adminRevoker, expiryRevoker, sessionEndRevoker, policyRevoker, normalizeRevoker, isGrantorSource, isHumanGrantor, isAutoGrantor, isDelegatedGrantor, isApiGrantor, } from './approval';
|
|
36
|
+
export { ApprovalError, ApprovalRequiredError, ApprovalOperationError, ApprovalScopeNotAllowedError, ApprovalExpiredError, ChallengeValidationError, ApprovalConfigurationError, userGrantor, adminGrantor, policyGrantor, systemGrantor, agentGrantor, apiGrantor, oauthGrantor, testGrantor, customGrantor, normalizeGrantor, userRevoker, adminRevoker, expiryRevoker, sessionEndRevoker, policyRevoker, normalizeRevoker, delegationDepth, delegationProblem, extendDelegation, isGrantorSource, isHumanGrantor, isAutoGrantor, isDelegatedGrantor, isApiGrantor, } from './approval';
|
|
36
37
|
//# sourceMappingURL=index.d.ts.map
|
package/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,OAAO,EACL,OAAO,IAAI,cAAc,EACzB,cAAc,IAAI,mBAAmB,EACrC,KAAK,qBAAqB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,OAAO,EACL,OAAO,IAAI,cAAc,EACzB,cAAc,IAAI,mBAAmB,EACrC,KAAK,qBAAqB,EAC1B,KAAK,cAAc,GACpB,MAAM,mBAAmB,CAAC;AAC3B,YAAY,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAGlE,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAGrG,cAAc,SAAS,CAAC;AAGxB,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC1B,oBAAoB,EACpB,KAAK,2BAA2B,EAChC,yBAAyB,GAC1B,MAAM,UAAU,CAAC;AAGlB,OAAO,EACL,eAAe,EACf,qBAAqB,EACrB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,gBAAgB,EAChB,4BAA4B,EAC5B,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,GAC5B,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAG9C,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAG/E,OAAO,EAEL,aAAa,EACb,qBAAqB,EACrB,sBAAsB,EACtB,4BAA4B,EAC5B,oBAAoB,EACpB,wBAAwB,EACxB,0BAA0B,EAE1B,WAAW,EACX,YAAY,EACZ,aAAa,EACb,aAAa,EACb,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,WAAW,EACX,aAAa,EACb,gBAAgB,EAEhB,WAAW,EACX,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,aAAa,EACb,gBAAgB,EAEhB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAEhB,eAAe,EACf,cAAc,EACd,aAAa,EACb,kBAAkB,EAClB,YAAY,GACb,MAAM,YAAY,CAAC"}
|
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 name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var index_exports={};__export(index_exports,{ApprovalCheckPlugin:()=>ApprovalCheckPlugin,ApprovalError:()=>ApprovalError,ApprovalExpiredError:()=>ApprovalExpiredError,ApprovalOperationError:()=>ApprovalOperationError,ApprovalPlugin:()=>ApprovalPlugin,ApprovalPluginClass:()=>ApprovalPlugin,ApprovalRequiredError:()=>ApprovalRequiredError,ApprovalScope:()=>ApprovalScope,ApprovalScopeNotAllowedError:()=>ApprovalScopeNotAllowedError,ApprovalService:()=>ApprovalService,ApprovalServiceToken:()=>ApprovalServiceToken,ApprovalState:()=>ApprovalState,ApprovalStorageStore:()=>ApprovalStorageStore,ApprovalStoreToken:()=>ApprovalStoreToken,ChallengeService:()=>ChallengeService,ChallengeServiceToken:()=>ChallengeServiceToken,ChallengeValidationError:()=>ChallengeValidationError,adminGrantor:()=>adminGrantor,adminRevoker:()=>adminRevoker,agentGrantor:()=>agentGrantor,apiGrantor:()=>apiGrantor,createApprovalMemoryStore:()=>createApprovalMemoryStore,createApprovalService:()=>createApprovalService,createMemoryChallengeService:()=>createMemoryChallengeService,customGrantor:()=>customGrantor,expiryRevoker:()=>expiryRevoker,installApprovalContextExtension:()=>installApprovalContextExtension,isApiGrantor:()=>isApiGrantor,isAutoGrantor:()=>isAutoGrantor,isDelegatedGrantor:()=>isDelegatedGrantor,isGrantorSource:()=>isGrantorSource,isHumanGrantor:()=>isHumanGrantor,normalizeGrantor:()=>normalizeGrantor,normalizeRevoker:()=>normalizeRevoker,oauthGrantor:()=>oauthGrantor,policyGrantor:()=>policyGrantor,policyRevoker:()=>policyRevoker,sessionEndRevoker:()=>sessionEndRevoker,systemGrantor:()=>systemGrantor,testGrantor:()=>testGrantor,userGrantor:()=>userGrantor,userRevoker:()=>userRevoker});module.exports=__toCommonJS(index_exports);var import_sdk6=require("@frontmcp/sdk");var import_utils=require("@frontmcp/utils");function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function resolveApprovalIdentity(ctx){const extra=ctx?.authInfo?.extra;const userId=nonEmptyString(extra?.["userId"])??nonEmptyString(extra?.["sub"])??nonEmptyString(ctx?.authInfo?.clientId);const sessionId=nonEmptyString(ctx?.verifiedSessionId);if(sessionId){return{sessionId,userId}}return{sessionId:userId?`stateless-user:${userId}`:`unidentified:${(0,import_utils.randomUUID)()}`,userId}}var ApprovalStoreToken=Symbol.for("plugin:approval:store");var ApprovalServiceToken=Symbol.for("plugin:approval:service");var ChallengeServiceToken=Symbol.for("plugin:approval:challenge-service");var import_sdk=require("@frontmcp/sdk");var ApprovalError=class extends import_sdk.PublicMcpError{constructor(message,code="APPROVAL_REQUIRED",statusCode=403){super(message,code,statusCode);this.name="ApprovalError"}};var ApprovalRequiredError=class extends ApprovalError{constructor(details){super(details.message);this.details=details;this.name="ApprovalRequiredError"}details;toJsonRpcError(){return{code:-32600,message:this.details.message,data:{type:"approval_required",toolId:this.details.toolId,state:this.details.state,options:this.details.approvalOptions}}}};var ApprovalOperationError=class extends ApprovalError{constructor(operation,reason){super(`Approval ${operation} failed: ${reason}`,"APPROVAL_OPERATION_FAILED",400);this.operation=operation;this.reason=reason;this.name="ApprovalOperationError"}operation;reason;toJsonRpcError(){return{code:-32603,message:"Approval operation failed",data:{type:"approval_operation_error",operation:this.operation}}}};var ApprovalScopeNotAllowedError=class extends ApprovalError{constructor(requestedScope,allowedScopes){super(`Approval scope '${requestedScope}' is not allowed for this tool. Allowed scopes: ${allowedScopes.join(", ")}`,"APPROVAL_SCOPE_NOT_ALLOWED",400);this.requestedScope=requestedScope;this.allowedScopes=allowedScopes;this.name="ApprovalScopeNotAllowedError"}requestedScope;allowedScopes;toJsonRpcError(){return{code:-32602,message:this.message,data:{type:"approval_scope_not_allowed",requestedScope:this.requestedScope,allowedScopes:this.allowedScopes}}}};var ApprovalExpiredError=class extends ApprovalError{constructor(toolId,expiredAt){super(`Approval for tool '${toolId}' expired at ${new Date(expiredAt).toISOString()}`,"APPROVAL_EXPIRED",403);this.toolId=toolId;this.expiredAt=expiredAt;this.name="ApprovalExpiredError"}toolId;expiredAt;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"approval_expired",toolId:this.toolId,expiredAt:this.expiredAt}}}};var ChallengeValidationError=class extends ApprovalError{constructor(reason="invalid",message){super(message??`PKCE challenge validation failed: ${reason}`,"CHALLENGE_VALIDATION_FAILED",400);this.reason=reason;this.name="ChallengeValidationError"}reason;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"challenge_validation_error",reason:this.reason}}}};var ApprovalScope=(ApprovalScope2=>{ApprovalScope2["SESSION"]="session";ApprovalScope2["USER"]="user";ApprovalScope2["TIME_LIMITED"]="time_limited";ApprovalScope2["TOOL_SPECIFIC"]="tool_specific";ApprovalScope2["CONTEXT_SPECIFIC"]="context_specific";return ApprovalScope2})(ApprovalScope||{});var ApprovalState=(ApprovalState2=>{ApprovalState2["PENDING"]="pending";ApprovalState2["APPROVED"]="approved";ApprovalState2["DENIED"]="denied";ApprovalState2["EXPIRED"]="expired";return ApprovalState2})(ApprovalState||{});function resolveApprovalRequirement(config){if(config===true){return{required:true,defaultScope:"session"}}if(config===false||config===void 0){return{required:false}}return{...config,required:config.required??true,defaultScope:config.defaultScope??"session"}}function effectiveExpiresAt(record,requirement){const capped=requirement.maxTtlMs!==void 0?record.grantedAt+requirement.maxTtlMs:void 0;if(record.expiresAt===void 0)return capped;return capped===void 0?record.expiresAt:Math.min(record.expiresAt,capped)}function isApprovalExpired(record,requirement,now){const expiresAt=effectiveExpiresAt(record,requirement);return expiresAt!==void 0&&now>expiresAt}function isApprovalUsable(record,requirement,now){if(record.state!=="approved")return false;if(requirement.allowedScopes?.length&&!requirement.allowedScopes.includes(record.scope))return false;return!isApprovalExpired(record,requirement,now)}function assertValidTtl(ttlMs){if(ttlMs===void 0)return;if(!Number.isFinite(ttlMs)||ttlMs<=0){throw new ApprovalOperationError("grant",`ttlMs must be a positive number of milliseconds, got ${ttlMs}`)}}function checkGrantAgainstPolicy(toolId,scope,ttlMs,requirement){assertValidTtl(ttlMs);if(!requirement)return ttlMs;if(requirement.allowedScopes?.length&&!requirement.allowedScopes.includes(scope)){throw new ApprovalScopeNotAllowedError(scope,requirement.allowedScopes)}const{maxTtlMs}=requirement;if(maxTtlMs===void 0)return ttlMs;if(ttlMs===void 0)return maxTtlMs;if(ttlMs>maxTtlMs){throw new ApprovalOperationError("grant",`ttlMs ${ttlMs} exceeds the maximum of ${maxTtlMs} ms that tool "${toolId}" allows`)}return ttlMs}var import_sdk2=require("@frontmcp/sdk");var import_lazy_zod=require("@frontmcp/lazy-zod");var approvalScopeSchema=import_lazy_zod.z.nativeEnum(ApprovalScope);var approvalStateSchema=import_lazy_zod.z.nativeEnum(ApprovalState);var approvalMethodSchema=import_lazy_zod.z.enum(["interactive","implicit","delegation","batch","api"]);var approvalSourceTypeSchema=import_lazy_zod.z.string().min(1);var revocationMethodSchema=import_lazy_zod.z.enum(["interactive","implicit","policy","expiry"]);var approvalCategorySchema=import_lazy_zod.z.enum(["read","write","delete","execute","admin"]);var riskLevelSchema=import_lazy_zod.z.enum(["low","medium","high","critical"]);var approvalContextSchema=import_lazy_zod.z.object({type:import_lazy_zod.z.string().min(1),identifier:import_lazy_zod.z.string().min(1),metadata:import_lazy_zod.z.record(import_lazy_zod.z.string(),import_lazy_zod.z.unknown()).optional()});var delegationContextSchema=import_lazy_zod.z.object({delegatorId:import_lazy_zod.z.string().min(1),delegateId:import_lazy_zod.z.string().min(1),purpose:import_lazy_zod.z.string().optional(),constraints:import_lazy_zod.z.record(import_lazy_zod.z.string(),import_lazy_zod.z.unknown()).optional()});var approvalGrantorSchema=import_lazy_zod.z.object({source:approvalSourceTypeSchema,identifier:import_lazy_zod.z.string().optional(),displayName:import_lazy_zod.z.string().optional(),method:approvalMethodSchema.optional(),origin:import_lazy_zod.z.string().optional(),delegationContext:delegationContextSchema.optional()});var approvalRevokerSchema=import_lazy_zod.z.object({source:import_lazy_zod.z.string().min(1),identifier:import_lazy_zod.z.string().optional(),displayName:import_lazy_zod.z.string().optional(),method:revocationMethodSchema.optional()});var approvalRecordSchema=import_lazy_zod.z.object({toolId:import_lazy_zod.z.string().min(1),state:approvalStateSchema,scope:approvalScopeSchema,grantedAt:import_lazy_zod.z.number(),expiresAt:import_lazy_zod.z.number().optional(),ttlMs:import_lazy_zod.z.number().optional(),sessionId:import_lazy_zod.z.string().optional(),userId:import_lazy_zod.z.string().optional(),context:approvalContextSchema.optional(),grantedBy:approvalGrantorSchema,approvalChain:import_lazy_zod.z.array(approvalGrantorSchema).optional(),reason:import_lazy_zod.z.string().optional(),metadata:import_lazy_zod.z.record(import_lazy_zod.z.string(),import_lazy_zod.z.unknown()).optional(),revokedAt:import_lazy_zod.z.number().optional(),revokedBy:approvalRevokerSchema.optional(),revocationReason:import_lazy_zod.z.string().optional()});var toolApprovalRequirementSchema=import_lazy_zod.z.object({required:import_lazy_zod.z.boolean().optional(),defaultScope:approvalScopeSchema.optional(),allowedScopes:import_lazy_zod.z.array(approvalScopeSchema).optional(),maxTtlMs:import_lazy_zod.z.number().positive().optional(),alwaysPrompt:import_lazy_zod.z.boolean().optional(),skipApproval:import_lazy_zod.z.boolean().optional(),approvalMessage:import_lazy_zod.z.string().optional(),category:approvalCategorySchema.optional(),riskLevel:riskLevelSchema.optional(),preApprovedContexts:import_lazy_zod.z.array(approvalContextSchema).optional()});function userGrantor(userId,displayName,options){return{source:"user",identifier:userId,displayName,method:options?.method??"interactive",origin:options?.origin}}function policyGrantor(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"implicit"}}function adminGrantor(adminId,displayName,options){return{source:"admin",identifier:adminId,displayName,method:options?.method??"interactive",origin:options?.origin}}function systemGrantor(systemId="system"){return{source:"system",identifier:systemId,method:"implicit"}}function agentGrantor(agentId,delegationContext,displayName){return{source:"agent",identifier:agentId,displayName,method:"delegation",delegationContext}}function apiGrantor(apiKeyPrefix,serviceName){return{source:"api",identifier:apiKeyPrefix,displayName:serviceName,method:"api",origin:"api"}}function oauthGrantor(tokenId,provider){return{source:"oauth",identifier:tokenId,displayName:provider,method:"api",origin:"oauth"}}function testGrantor(){return{source:"test",identifier:"test",method:"implicit"}}function customGrantor(source,identifier,options){return{source,identifier,displayName:options?.displayName,method:options?.method,origin:options?.origin,delegationContext:options?.delegationContext}}function userRevoker(userId,displayName){return{source:"user",identifier:userId,displayName,method:"interactive"}}function adminRevoker(adminId,displayName){return{source:"admin",identifier:adminId,displayName,method:"interactive"}}function expiryRevoker(){return{source:"expiry",method:"expiry"}}function sessionEndRevoker(sessionId){return{source:"session_end",identifier:sessionId,method:"implicit"}}function policyRevoker(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"policy"}}function normalizeGrantor(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function normalizeRevoker(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function isGrantorSource(grantor,source){return grantor.source===source}function isHumanGrantor(grantor){return grantor.source==="user"||grantor.source==="admin"}function isAutoGrantor(grantor){return grantor.source==="policy"||grantor.source==="system"||grantor.source==="test"}function isDelegatedGrantor(grantor){return grantor.source==="agent"&&!!grantor.delegationContext}function isApiGrantor(grantor){return grantor.source==="api"||grantor.source==="oauth"}var decidedCalls=new WeakSet;var ApprovalCheckPlugin=class extends import_sdk2.DynamicPlugin{async checkApproval(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;const metadata=tool.metadata;const approvalConfig=resolveApprovalRequirement(metadata["approval"]);if(!approvalConfig.required){return}if(approvalConfig.skipApproval){return}if(decidedCalls.has(toolContext))return;await this.enforceApproval(flowCtx,tool,toolContext,approvalConfig,this.coveringStores(tool));decidedCalls.add(toolContext)}async enforceApproval(flowCtx,tool,toolContext,approvalConfig,stores){const{sessionId,userId}=resolveApprovalIdentity(toolContext.tryGetContext?.());const currentContext=this.getCurrentContext(flowCtx);const stored=[];for(const store of stores){const records2=await this.readApprovals(store,tool.fullName,sessionId,userId,currentContext);stored.push(...records2.map(record=>({store,record})))}const records=stored.map(({record})=>record);if(records.some(record=>record.state==="denied")){throw new ApprovalRequiredError({toolId:tool.fullName,state:"denied",message:`Tool "${tool.fullName}" execution denied.`})}if(!approvalConfig.alwaysPrompt&&this.isPreApprovedContext(approvalConfig,currentContext)){return}const approved=records.filter(record=>record.state==="approved");const now=Date.now();const usable=stored.filter(({record})=>isApprovalUsable(record,approvalConfig,now));if(approvalConfig.alwaysPrompt){for(const{store,record}of usable){if(await this.consumeApproval(store,record,sessionId,userId,currentContext))return}}else if(usable.length>0){return}await this.handleApprovalRequired(flowCtx,approvalConfig,approved.find(record=>isApprovalExpired(record,approvalConfig,now))??approved[0])}coveringStores(tool){const stores=new Set([this.get(ApprovalStoreToken)]);let scope;try{scope=this.get(import_sdk2.ScopeEntry)}catch{scope=void 0}if(!scope?.hooks)return[...stores];for(const hook of scope.hooks.getFlowHooks("tools:call-tool")){const gate=hook.metadata.target;if(gate instanceof ApprovalCheckPlugin&&(0,import_sdk2.isEntryGatedBy)(scope,{tool},gate)){stores.add(gate.get(ApprovalStoreToken))}}return[...stores]}async consumeApproval(store,record,sessionId,userId,context){if(store.consumeApproval){return store.consumeApproval(record,sessionId,userId,context)}return store.revokeApproval({toolId:record.toolId,sessionId,userId,revokedBy:"system",reason:"Used by a call of an alwaysPrompt tool"})}async readApprovals(store,toolId,sessionId,userId,context){if(store.getApprovals){return store.getApprovals(toolId,sessionId,userId,context)}const record=await store.getApproval(toolId,sessionId,userId,context);return record?[record]:[]}getCurrentContext(flowCtx){const ctx=flowCtx.state.toolContext?.tryGetContext?.();const sessionContext=ctx?.authInfo?.extra?.["approvalContext"];return this.isApprovalContext(sessionContext)?sessionContext:void 0}isApprovalContext(value){return typeof value==="object"&&value!==null&&"type"in value&&"identifier"in value&&typeof value.type==="string"&&typeof value.identifier==="string"}isPreApprovedContext(config,currentContext){if(!currentContext||!config.preApprovedContexts?.length){return false}return config.preApprovedContexts.some(preApproved=>preApproved.type===currentContext.type&&preApproved.identifier===currentContext.identifier)}async handleApprovalRequired(flowCtx,config,existingApproval){const{tool}=flowCtx.state;const message=config.approvalMessage??`Tool "${tool?.fullName}" requires approval to execute. Allow?`;const isExpiredApproval=existingApproval?isApprovalExpired(existingApproval,config,Date.now()):false;throw new ApprovalRequiredError({toolId:tool?.fullName??"unknown",state:isExpiredApproval?"expired":"pending",message,approvalOptions:{allowedScopes:config.allowedScopes,defaultScope:config.defaultScope,maxTtlMs:config.maxTtlMs,category:config.category,riskLevel:config.riskLevel}})}};__decorateClass([import_sdk2.ToolHook.Will("execute",{priority:100,appliesTo:"uncovered-apps"})],ApprovalCheckPlugin.prototype,"checkApproval",1);ApprovalCheckPlugin=__decorateClass([(0,import_sdk2.Plugin)({name:"approval:check",description:"Checks tool approval state before execution",enforcesMetadata:["approval"]})],ApprovalCheckPlugin);var import_sdk3=require("@frontmcp/sdk");var ApprovalService=class{constructor(store,sessionId,userId,requirementOf=()=>void 0){this.store=store;this.sessionId=sessionId;this.userId=userId;this.requirementOf=requirementOf}store;sessionId;userId;requirementOf;checkGrant(toolId,scope,ttlMs){return checkGrantAgainstPolicy(toolId,scope,ttlMs,this.requirementOf(toolId))}get signedInUserId(){return this.userId&&!(0,import_sdk3.isAnonymousSubject)(this.userId)?this.userId:void 0}defaultGrantor(){const userId=this.signedInUserId;return userId?userGrantor(userId,void 0,{method:"implicit"}):{source:"user",method:"implicit"}}defaultRevoker(){const userId=this.signedInUserId;return userId?{source:"user",identifier:userId,method:"implicit"}:{source:"user",method:"implicit"}}async isApproved(toolId,context){const requirement=this.requirementOf(toolId);if(!requirement||!this.store.getApprovals){return this.store.isApproved(toolId,this.sessionId,this.userId,context)}const records=await this.store.getApprovals(toolId,this.sessionId,this.userId,context);if(records.some(record=>record.state==="denied"))return false;const now=Date.now();return records.some(record=>isApprovalUsable(record,requirement,now))}async getApproval(toolId){return this.store.getApproval(toolId,this.sessionId,this.userId)}async getSessionApprovals(){return this.store.queryApprovals({sessionId:this.sessionId,states:["approved"],includeExpired:false})}async getUserApprovals(){if(!this.userId)return[];return this.store.queryApprovals({userId:this.userId,scope:"user",states:["approved"],includeExpired:false})}async queryApprovals(query){const records=await this.store.queryApprovals(query);return records.filter(record=>record.sessionId===this.sessionId||this.userId!==void 0&&record.userId===this.userId)}async getRevocations(toolId){return await this.store.getRevocations?.(toolId,this.sessionId,this.userId)??[]}async grantSessionApproval(toolId,options={}){const ttlMs=this.checkGrant(toolId,"session");return this.store.grantApproval({toolId,scope:"session",ttlMs,sessionId:this.sessionId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantUserApproval(toolId,options={}){if(!this.userId){throw new Error("Cannot grant user approval without userId")}const ttlMs=this.checkGrant(toolId,"user");return this.store.grantApproval({toolId,scope:"user",ttlMs,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantTimeLimitedApproval(toolId,ttlMs,options={}){this.checkGrant(toolId,"time_limited",ttlMs);return this.store.grantApproval({toolId,scope:"time_limited",ttlMs,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantContextApproval(toolId,context,options={}){const ttlMs=this.checkGrant(toolId,"context_specific");return this.store.grantApproval({toolId,scope:"context_specific",ttlMs,context,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async revokeApproval(toolId,options={}){return this.store.revokeApproval({toolId,sessionId:this.sessionId,userId:this.userId,revokedBy:options.revokedBy??this.defaultRevoker(),reason:options.reason})}async clearSessionApprovals(){return this.store.clearSessionApprovals(this.sessionId)}};ApprovalService=__decorateClass([(0,import_sdk3.Provider)({name:"provider:approval:service",description:"Service for managing tool approvals",scope:import_sdk3.ProviderScope.CONTEXT})],ApprovalService);function createApprovalService(store,sessionId,userId,requirementOf){return new ApprovalService(store,sessionId,userId,requirementOf)}var import_sdk4=require("@frontmcp/sdk");var import_utils2=require("@frontmcp/utils");var ChallengeService=class{storage;options;initialized=false;ownedStorage=false;constructor(options={}){this.options={storage:options.storage??{type:"auto"},storageInstance:options.storageInstance,namespace:options.namespace??"approval:challenge",defaultTtlSeconds:options.defaultTtlSeconds??300}}async initialize(){if(this.initialized)return;if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await(0,import_utils2.createStorage)(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}this.initialized=true}ensureInitialized(){if(!this.initialized){throw new Error("ChallengeService not initialized. Call initialize() first.")}}async createChallenge(options){this.ensureInitialized();const{codeVerifier,codeChallenge}=(0,import_utils2.generatePkcePair)();const now=Date.now();const ttlSeconds=options.ttlSeconds??this.options.defaultTtlSeconds;const expiresAt=now+ttlSeconds*1e3;const record={toolId:options.toolId,sessionId:options.sessionId,userId:options.userId,requestedScope:options.requestedScope,requestInfo:options.requestInfo,createdAt:now,expiresAt,webhookSent:false};await this.storage.set(codeChallenge,JSON.stringify(record),{ttlSeconds});return{codeVerifier,codeChallenge,expiresAt}}async verifyAndConsume(codeVerifier){this.ensureInitialized();const{codeChallenge}=generatePkcePairFromVerifier(codeVerifier);const recordJson=await this.storage.get(codeChallenge);if(!recordJson){throw new ChallengeValidationError("not_found","Invalid or expired challenge")}const record=JSON.parse(recordJson);if(Date.now()>record.expiresAt){await this.storage.delete(codeChallenge);throw new ChallengeValidationError("expired","Challenge expired")}await this.storage.delete(codeChallenge);return record}async markWebhookSent(codeChallenge){this.ensureInitialized();const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return false;const record=JSON.parse(recordJson);record.webhookSent=true;const remainingMs=record.expiresAt-Date.now();if(remainingMs<=0){await this.storage.delete(codeChallenge);return false}const ttlSeconds=Math.ceil(remainingMs/1e3);await this.storage.set(codeChallenge,JSON.stringify(record),{ttlSeconds});return true}async getChallenge(codeChallenge){this.ensureInitialized();const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return null;const record=JSON.parse(recordJson);if(Date.now()>record.expiresAt){await this.storage.delete(codeChallenge);return null}return record}async deleteChallenge(codeChallenge){this.ensureInitialized();const exists=await this.storage.exists(codeChallenge);if(exists){await this.storage.delete(codeChallenge);return true}return false}async close(){if(this.ownedStorage&&this.storage){await this.storage.root.disconnect()}this.initialized=false}};ChallengeService=__decorateClass([(0,import_sdk4.Provider)({name:"provider:approval:challenge-service",description:"PKCE challenge service for webhook approval flows",scope:import_sdk4.ProviderScope.GLOBAL})],ChallengeService);function generatePkcePairFromVerifier(codeVerifier){return{codeVerifier,codeChallenge:(0,import_utils2.generateCodeChallenge)(codeVerifier)}}function createMemoryChallengeService(options={}){const memoryStorage=(0,import_utils2.createMemoryStorage)();return new ChallengeService({...options,storageInstance:memoryStorage})}var import_sdk5=require("@frontmcp/sdk");var import_utils3=require("@frontmcp/utils");function escapePattern(str){return str.replace(/[*?[\]\\]/g,"\\$&")}function isSameRecord(a,b){return a.toolId===b.toolId&&a.state===b.state&&a.scope===b.scope&&a.grantedAt===b.grantedAt&&a.sessionId===b.sessionId&&a.userId===b.userId&&a.context?.type===b.context?.type&&a.context?.identifier===b.context?.identifier}var REVOCATION_RETENTION_SECONDS=24*60*60;var TIME_LIMITED_KEY_SEGMENT=`scope:${"time_limited"}`;var ApprovalStorageStore=class{storage;revocationStorage;options;cleanupInterval;initialized=false;ownedStorage=false;constructor(options={}){this.options={storage:options.storage??{type:"auto"},storageInstance:options.storageInstance,namespace:options.namespace??"approval",cleanupIntervalSeconds:options.cleanupIntervalSeconds??60}}async initialize(){if(this.initialized){return}if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await(0,import_utils3.createStorage)(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}if(this.options.cleanupIntervalSeconds>0){this.cleanupInterval=setInterval(()=>{void this.clearExpiredApprovals()},this.options.cleanupIntervalSeconds*1e3);this.cleanupInterval.unref?.()}this.initialized=true}get revocations(){this.revocationStorage??=(0,import_utils3.createNamespacedStorage)(this.storage.root,`${this.storage.prefix.replace(/:$/,"")}-revoked`);return this.revocationStorage}ensureInitialized(){if(!this.initialized){throw new Error("ApprovalStorageStore not initialized. Call initialize() first.")}}buildKey(toolId,sessionId,userId,context){const parts=[toolId];if(sessionId)parts.push(`session:${sessionId}`);if(userId)parts.push(`user:${userId}`);if(context)parts.push(`ctx:${context.type}:${context.identifier}`);return parts.join(":")}timeLimitedKey(toolId,sessionId,userId){return`${this.buildKey(toolId,sessionId,userId)}:${TIME_LIMITED_KEY_SEGMENT}`}recordKey(options){const{toolId,scope,sessionId,userId,context}=options;if(scope==="time_limited"&&!context&&!(sessionId&&userId)){return this.timeLimitedKey(toolId,sessionId,userId)}return this.buildKey(toolId,sessionId,userId,context)}parseRecord(value){if(!value)return void 0;try{const parsed=JSON.parse(value);const result=approvalRecordSchema.safeParse(parsed);if(!result.success){return void 0}return result.data}catch{return void 0}}isExpired(approval){return approval.expiresAt!==void 0&&Date.now()>approval.expiresAt}callerKeys(toolId,sessionId,userId,context){const keys=[this.buildKey(toolId,sessionId),this.timeLimitedKey(toolId,sessionId)];if(userId){keys.push(this.buildKey(toolId,void 0,userId),this.timeLimitedKey(toolId,void 0,userId),this.buildKey(toolId,sessionId,userId))}if(context){keys.push(this.buildKey(toolId,sessionId,void 0,context));if(userId)keys.push(this.buildKey(toolId,sessionId,userId,context))}return[...new Set(keys)]}async getApprovals(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const key of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.storage.get(key));if(record&&record.toolId===toolId&&!this.isExpired(record)){records.push(record)}}return records}async getApproval(toolId,sessionId,userId,context){const records=await this.getApprovals(toolId,sessionId,userId,context);return records.find(record=>record.state==="denied")??records[0]}async queryApprovals(query){this.ensureInitialized();const results=[];const pattern=query.toolId?`${escapePattern(query.toolId)}:*`:"*";const keys=await this.storage.keys(pattern);const values=await this.storage.mget(keys);for(const value of values){const approval=this.parseRecord(value);if(!approval)continue;if(!query.includeExpired&&this.isExpired(approval)){continue}if(query.toolId&&approval.toolId!==query.toolId)continue;if(query.toolIds&&!query.toolIds.includes(approval.toolId))continue;if(query.scope&&approval.scope!==query.scope)continue;if(query.scopes&&!query.scopes.includes(approval.scope))continue;if(query.state&&approval.state!==query.state)continue;if(query.states&&!query.states.includes(approval.state))continue;if(query.sessionId&&approval.sessionId!==query.sessionId)continue;if(query.userId&&approval.userId!==query.userId)continue;if(query.context){if(!approval.context||approval.context.type!==query.context.type||approval.context.identifier!==query.context.identifier){continue}}results.push(approval)}return results}async grantApproval(options){this.ensureInitialized();assertValidTtl(options.ttlMs);if(options.scope==="time_limited"&&options.ttlMs===void 0){throw new ApprovalOperationError("grant","a time-limited approval needs ttlMs")}const now=Date.now();const expiresAt=options.ttlMs!==void 0?now+options.ttlMs:void 0;const grantedBy=normalizeGrantor(options.grantedBy);const record={toolId:options.toolId,state:"approved",scope:options.scope,grantedAt:now,expiresAt,ttlMs:options.ttlMs,sessionId:options.sessionId,userId:options.userId,context:options.context,grantedBy,reason:options.reason,metadata:options.metadata};const key=this.recordKey(options);const ttlSeconds=options.ttlMs!==void 0?Math.ceil(options.ttlMs/1e3):void 0;await this.storage.set(key,JSON.stringify(record),{ttlSeconds});return record}async revokeApproval(options){this.ensureInitialized();const{toolId,sessionId,userId,context}=options;if(!sessionId&&!userId&&!context){return false}const keys=await this.storage.keys(`${escapePattern(toolId)}:*`);const values=await this.storage.mget(keys);const keysToDelete=[];const revoked=new Map;for(let i=0;i<keys.length;i++){const record=this.parseRecord(values[i]);if(!record||record.toolId!==toolId||record.state==="denied")continue;const matches=keysToDelete.length;if(context){const sameSession=sessionId!==void 0&&record.sessionId===sessionId;if(record.context?.type===context.type&&record.context.identifier===context.identifier&&(!sessionId||sameSession)&&(!userId||record.userId===userId||sameSession&&record.userId===void 0)){keysToDelete.push(keys[i])}}else if(sessionId&&record.sessionId===sessionId||userId&&record.userId===userId){keysToDelete.push(keys[i])}if(keysToDelete.length>matches)revoked.set(keys[i],record)}if(keysToDelete.length===0){return false}const revokedAt=Date.now();const revokedBy=normalizeRevoker(options.revokedBy);for(const[key,record]of revoked){const entry={...record,revokedAt,revokedBy,revocationReason:options.reason};await this.revocations.set(key,JSON.stringify(entry),{ttlSeconds:REVOCATION_RETENTION_SECONDS})}await this.storage.mdelete(keysToDelete);return true}async consumeApproval(record,sessionId,userId,context){this.ensureInitialized();for(const key of this.callerKeys(record.toolId,sessionId,userId,context)){const storedValue=await this.storage.get(key);const stored=this.parseRecord(storedValue);if(storedValue!==null&&stored&&isSameRecord(stored,record)){return this.deleteIfUnchanged(key,storedValue)}}return false}async deleteIfUnchanged(key,storedValue){try{return await this.storage.deleteIfEquals(key,storedValue)}catch(error){if(!(error instanceof import_utils3.StorageNotSupportedError))throw error;return this.storage.delete(key)}}async getRevocations(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const key of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.revocations.get(key));if(record&&record.toolId===toolId)records.push(record)}return records.sort((a,b)=>(a.revokedAt??0)-(b.revokedAt??0))}async isApproved(toolId,sessionId,userId,context){const approval=await this.getApproval(toolId,sessionId,userId,context);return approval?.state==="approved"}async clearSessionApprovals(sessionId){this.ensureInitialized();const escapedSessionId=escapePattern(sessionId);const keys=[...new Set([...await this.storage.keys(`*:session:${escapedSessionId}`),...await this.storage.keys(`*:session:${escapedSessionId}:*`)])];if(keys.length===0){return 0}return await this.storage.mdelete(keys)}async clearExpiredApprovals(){this.ensureInitialized();const now=Date.now();const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);const keysToDelete=[];for(let i=0;i<keys.length;i++){const approval=this.parseRecord(values[i]);if(approval&&approval.expiresAt&&approval.expiresAt<=now){keysToDelete.push(keys[i])}}if(keysToDelete.length>0){return await this.storage.mdelete(keysToDelete)}return 0}async getStats(){this.ensureInitialized();const byScope={["session"]:0,["user"]:0,["time_limited"]:0,["tool_specific"]:0,["context_specific"]:0};const byState={["pending"]:0,["approved"]:0,["denied"]:0,["expired"]:0};const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);let total=0;for(const value of values){const approval=this.parseRecord(value);if(approval){total++;byScope[approval.scope]++;byState[approval.state]++}}return{totalApprovals:total,byScope,byState}}async close(){if(this.cleanupInterval){clearInterval(this.cleanupInterval);this.cleanupInterval=void 0}if(this.ownedStorage&&this.storage){await this.storage.root.disconnect()}this.revocationStorage=void 0;this.initialized=false}};ApprovalStorageStore=__decorateClass([(0,import_sdk5.Provider)({name:"provider:approval:store:storage",description:"Storage-backed approval store (supports Memory, Redis, Vercel KV, Upstash)",scope:import_sdk5.ProviderScope.GLOBAL})],ApprovalStorageStore);function createApprovalMemoryStore(options={}){const memoryStorage=(0,import_utils3.createMemoryStorage)();return new ApprovalStorageStore({...options,storageInstance:memoryStorage})}var ApprovalPlugin=class extends import_sdk6.DynamicPlugin{options;constructor(options={}){super();this.options={...ApprovalPlugin.defaultOptions,...options}}};__publicField(ApprovalPlugin,"defaultOptions",{namespace:"approval",mode:"recheck",enableAudit:true,maxDelegationDepth:3,cleanupIntervalSeconds:60});__publicField(ApprovalPlugin,"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};providers.push((0,import_sdk6.storeProvider)({name:"approval:store",provide:ApprovalStoreToken,inject:()=>[],useFactory:async()=>{const store=new ApprovalStorageStore({storage:config.storage,storageInstance:config.storageInstance,namespace:config.namespace,cleanupIntervalSeconds:config.cleanupIntervalSeconds});await store.initialize();return store}}));if(config.mode==="webhook"){providers.push((0,import_sdk6.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}}))}providers.push({name:"approval:service",provide:ApprovalServiceToken,scope:import_sdk6.ProviderScope.CONTEXT,inject:()=>[ApprovalStoreToken,import_sdk6.FRONTMCP_CONTEXT,import_sdk6.ScopeEntry],useFactory:(store,ctx,scope)=>{const{sessionId,userId}=resolveApprovalIdentity(ctx);const requirementOf=toolId=>{const tool=scope.tools.getTools(true).find(entry=>entry.fullName===toolId);if(!tool)return void 0;const approval=tool.metadata.approval;return resolveApprovalRequirement(approval)};return createApprovalService(store,sessionId,userId,requirementOf)}});return providers});ApprovalPlugin=__decorateClass([(0,import_sdk6.Plugin)({name:"approval",description:"Tool authorization workflow with PKCE webhook security",plugins:[ApprovalCheckPlugin],contextExtensions:[{property:"approval",token:ApprovalServiceToken,errorMessage:"ApprovalPlugin is not installed. Add ApprovalPlugin.init() to your plugins array."}]})],ApprovalPlugin);var installed=false;function installApprovalContextExtension(){if(installed)return;const{ExecutionContextBase}=require("@frontmcp/sdk");Object.defineProperty(ExecutionContextBase.prototype,"approval",{get:function(){return this.get(ApprovalServiceToken)},configurable:true,enumerable:false});installed=true}0&&(module.exports={ApprovalCheckPlugin,ApprovalError,ApprovalExpiredError,ApprovalOperationError,ApprovalPlugin,ApprovalPluginClass,ApprovalRequiredError,ApprovalScope,ApprovalScopeNotAllowedError,ApprovalService,ApprovalServiceToken,ApprovalState,ApprovalStorageStore,ApprovalStoreToken,ChallengeService,ChallengeServiceToken,ChallengeValidationError,adminGrantor,adminRevoker,agentGrantor,apiGrantor,createApprovalMemoryStore,createApprovalService,createMemoryChallengeService,customGrantor,expiryRevoker,installApprovalContextExtension,isApiGrantor,isAutoGrantor,isDelegatedGrantor,isGrantorSource,isHumanGrantor,normalizeGrantor,normalizeRevoker,oauthGrantor,policyGrantor,policyRevoker,sessionEndRevoker,systemGrantor,testGrantor,userGrantor,userRevoker});
|
|
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});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frontmcp/plugin-approval",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.0-rc.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.
|
|
53
|
+
"@frontmcp/utils": "1.12.0-rc.1",
|
|
54
54
|
"ioredis": "^5.8.0",
|
|
55
55
|
"reflect-metadata": "^0.2.2"
|
|
56
56
|
},
|
|
57
57
|
"peerDependencies": {
|
|
58
|
-
"@frontmcp/lazy-zod": "1.
|
|
59
|
-
"@frontmcp/sdk": "1.
|
|
58
|
+
"@frontmcp/lazy-zod": "1.12.0-rc.1",
|
|
59
|
+
"@frontmcp/sdk": "1.12.0-rc.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.
|
|
68
|
+
"@frontmcp/sdk": "1.12.0-rc.1",
|
|
69
69
|
"reflect-metadata": "^0.2.2"
|
|
70
70
|
}
|
|
71
71
|
}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* @module @frontmcp/plugin-approval
|
|
8
8
|
*/
|
|
9
9
|
import { type NamespacedStorage, type RootStorage, type StorageConfig } from '@frontmcp/utils';
|
|
10
|
-
import type { ChallengeRecord } from '../types';
|
|
10
|
+
import type { ApprovalContext, ChallengeRecord } from '../types';
|
|
11
11
|
/**
|
|
12
12
|
* Configuration for ChallengeService.
|
|
13
13
|
*/
|
|
@@ -42,6 +42,8 @@ export interface CreateChallengeOptions {
|
|
|
42
42
|
sessionId: string;
|
|
43
43
|
/** User ID if available */
|
|
44
44
|
userId?: string;
|
|
45
|
+
/** The context the call ran in, for a `context_specific` approval */
|
|
46
|
+
context?: ApprovalContext;
|
|
45
47
|
/** Requested approval scope */
|
|
46
48
|
requestedScope: string;
|
|
47
49
|
/** Request information for webhook */
|
|
@@ -91,6 +93,23 @@ export declare class ChallengeService {
|
|
|
91
93
|
* @throws ChallengeValidationError if verification fails
|
|
92
94
|
*/
|
|
93
95
|
verifyAndConsume(codeVerifier: string): Promise<ChallengeRecord>;
|
|
96
|
+
/**
|
|
97
|
+
* The request a code verifier answers, deleted so no other callback gets it, or `undefined` when there is none: an
|
|
98
|
+
* unknown or expired verifier, or one another callback already used. Of two callbacks racing with one verifier,
|
|
99
|
+
* exactly one gets the record.
|
|
100
|
+
*/
|
|
101
|
+
consume(codeVerifier: string): Promise<ChallengeRecord | undefined>;
|
|
102
|
+
/** Deletes the record stored under the verifier's challenge and returns it, or `undefined` when this call didn't. */
|
|
103
|
+
private take;
|
|
104
|
+
/** Deletes `key` only while it still holds `value`, in one step where the backend allows. */
|
|
105
|
+
private deleteIfUnchanged;
|
|
106
|
+
/**
|
|
107
|
+
* Marks the request named `key` as sent, for `ttlSeconds` (the default TTL when absent), and reports whether this
|
|
108
|
+
* call marked it: `false` when one is already pending, so it is sent once however many calls ask.
|
|
109
|
+
*/
|
|
110
|
+
claimPendingRequest(key: string, ttlSeconds?: number): Promise<boolean>;
|
|
111
|
+
/** Clears the mark {@link claimPendingRequest} set, so the next call sends the request again. */
|
|
112
|
+
releasePendingRequest(key: string): Promise<void>;
|
|
94
113
|
/**
|
|
95
114
|
* Mark a challenge as having been sent to webhook.
|
|
96
115
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"challenge.service.d.ts","sourceRoot":"","sources":["../../src/services/challenge.service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,
|
|
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"}
|