@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.
Files changed (54) hide show
  1. package/README.md +183 -13
  2. package/approval/delegation.d.ts +30 -0
  3. package/approval/delegation.d.ts.map +1 -0
  4. package/approval/errors.d.ts +6 -1
  5. package/approval/errors.d.ts.map +1 -1
  6. package/approval/factories.d.ts +1 -1
  7. package/approval/factories.d.ts.map +1 -1
  8. package/approval/index.d.ts +4 -3
  9. package/approval/index.d.ts.map +1 -1
  10. package/approval/schemas.d.ts +28 -0
  11. package/approval/schemas.d.ts.map +1 -1
  12. package/approval/types.d.ts +19 -1
  13. package/approval/types.d.ts.map +1 -1
  14. package/approval.context-extension.d.ts.map +1 -1
  15. package/approval.identity.d.ts +2 -0
  16. package/approval.identity.d.ts.map +1 -1
  17. package/approval.options.d.ts +43 -0
  18. package/approval.options.d.ts.map +1 -0
  19. package/approval.plugin.d.ts +62 -18
  20. package/approval.plugin.d.ts.map +1 -1
  21. package/approval.symbols.d.ts +11 -2
  22. package/approval.symbols.d.ts.map +1 -1
  23. package/audit/approval-audit.d.ts +44 -0
  24. package/audit/approval-audit.d.ts.map +1 -0
  25. package/esm/index.mjs +1 -1
  26. package/esm/package.json +5 -5
  27. package/external/approval-callback.flow.d.ts +36 -0
  28. package/external/approval-callback.flow.d.ts.map +1 -0
  29. package/external/approval-decisions.d.ts +60 -0
  30. package/external/approval-decisions.d.ts.map +1 -0
  31. package/external/outbound-request.d.ts +32 -0
  32. package/external/outbound-request.d.ts.map +1 -0
  33. package/external/recheck-approver.d.ts +49 -0
  34. package/external/recheck-approver.d.ts.map +1 -0
  35. package/external/webhook-approver.d.ts +44 -0
  36. package/external/webhook-approver.d.ts.map +1 -0
  37. package/external/webhook-signature.d.ts +12 -0
  38. package/external/webhook-signature.d.ts.map +1 -0
  39. package/flows/index.d.ts +3 -2
  40. package/flows/index.d.ts.map +1 -1
  41. package/hooks/approval-check.hook.d.ts +5 -0
  42. package/hooks/approval-check.hook.d.ts.map +1 -1
  43. package/index.d.ts +3 -2
  44. package/index.d.ts.map +1 -1
  45. package/index.js +1 -1
  46. package/package.json +5 -5
  47. package/services/challenge.service.d.ts +20 -1
  48. package/services/challenge.service.d.ts.map +1 -1
  49. package/stores/approval-storage.store.d.ts +15 -0
  50. package/stores/approval-storage.store.d.ts.map +1 -1
  51. package/stores/approval-store.interface.d.ts +6 -0
  52. package/stores/approval-store.interface.d.ts.map +1 -1
  53. package/types/approval.types.d.ts +41 -17
  54. package/types/approval.types.d.ts.map +1 -1
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { DynamicPlugin, type PluginStoreInBrowser, type ProviderType } from '@frontmcp/sdk';
7
7
  import type { NamespacedStorage, RootStorage, StorageConfig } from '@frontmcp/utils';
8
+ import { type RecheckRequest } from './external/recheck-approver';
8
9
  import type { ApprovalMode } from './types';
9
10
  /**
10
11
  * Configuration options for ApprovalPlugin.
@@ -25,45 +26,83 @@ export interface ApprovalPluginOptions {
25
26
  */
26
27
  namespace?: string;
27
28
  /**
28
- * Approval workflow mode. Neither contacts an external system yet: approvals are recorded by your code.
29
- * - 'recheck': Check the stored approvals on every call
30
- * - 'webhook': Also register the PKCE `ChallengeService` (`ChallengeServiceToken`)
29
+ * Approval workflow mode. Approvals are recorded by your code (`this.approval`, the store) in both; an external
30
+ * approval system is asked only when its URL is set.
31
+ * - 'recheck': Check the stored approvals on every call. With `recheck.url`, a call without one polls that URL until
32
+ * it decides.
33
+ * - 'webhook': Also register the PKCE `ChallengeService` (`ChallengeServiceToken`). With `webhook.url`, a call
34
+ * without an approval sends a signed request there, and the decision comes back on `webhook.callbackPath`.
31
35
  * @default 'recheck'
32
36
  */
33
37
  mode?: ApprovalMode;
34
38
  /**
35
- * Recheck mode configuration. Reserved: accepted and not used, nothing is polled.
39
+ * Recheck mode: poll an approval system's URL for a decision about a call that has no approval. Each poll is a signed
40
+ * (with `secret`) JSON POST of `{ type: 'approval.status', requestId, attempt, toolId, toolName, userId?, ... }`,
41
+ * answered with `{ approved, pending?, scope?, ttlMs?, grantedBy?, denialReason? }`: an approval is recorded, as the
42
+ * tool's policy allows, and the call runs; `{ approved: false }` refuses it as denied; `pending: true` polls again.
43
+ * A failed poll, or `maxAttempts` pending answers, refuses the call as pending. Needs `mode: 'recheck'`.
36
44
  */
37
45
  recheck?: {
38
- /** URL to check for approval status */
46
+ /** The approval system's status URL: `https://`, or `http://localhost` when NODE_ENV is not production. */
39
47
  url?: string;
40
- /** Authentication method */
48
+ /**
49
+ * How each poll authenticates:
50
+ * - `'none'`: no `Authorization` header (sign the polls with `secret`).
51
+ * - `'bearer'`: `Authorization: Bearer <token>`.
52
+ * - `'jwt'`: forwards the caller's own access token as `Authorization: Bearer`; a call without one isn't polled.
53
+ * - `'custom'`: the headers `headers(request)` returns.
54
+ * @default 'none'
55
+ */
41
56
  auth?: 'jwt' | 'bearer' | 'none' | 'custom';
42
- /** Interval between rechecks (ms) */
57
+ /** The token `auth: 'bearer'` sends. */
58
+ token?: string;
59
+ /** The headers `auth: 'custom'` sends, for the poll's body. */
60
+ headers?: RecheckHeaders;
61
+ /** Signs each poll (HMAC-SHA256, Standard Webhooks headers); at least 24 bytes. A `whsec_` secret is base64. */
62
+ secret?: string;
63
+ /** Interval between polls (ms), 100 to 60000. @default 2000 */
43
64
  interval?: number;
44
- /** Maximum recheck attempts */
65
+ /** Most polls per call, 1 to 60; `interval × (maxAttempts − 1)` must be 2 minutes or less. @default 5 */
45
66
  maxAttempts?: number;
46
67
  };
47
68
  /**
48
- * Webhook mode configuration. Only `challengeTtl` is used; no request is sent and no callback route is served.
69
+ * Webhook mode: ask an approval system by webhook. With `url`, a call that needs an approval it doesn't have sends
70
+ * one signed JSON POST (`WebhookPayload`) there per caller and tool, and is refused as pending; the system decides by
71
+ * POSTing `{ codeVerifier, approved, scope?, ttlMs?, grantedBy?, reason? }`, signed with the same secret, to
72
+ * `callbackPath`. Needs `mode: 'webhook'`.
49
73
  */
50
74
  webhook?: {
51
- /** URL to send approval requests */
75
+ /** Where approval requests are sent: `https://`, or `http://localhost` when NODE_ENV is not production. */
52
76
  url?: string;
53
- /** Include JWT in webhook payload */
77
+ /**
78
+ * Signs each request and verifies each callback (HMAC-SHA256 in the Standard Webhooks format); required with
79
+ * `url`, at least 24 bytes. A `whsec_` secret (a Standard Webhooks secret) is base64 after the prefix.
80
+ */
81
+ secret?: string;
82
+ /**
83
+ * Forward the caller's access token to `url`, as the request's `jwt` field. Only set it when the approval system
84
+ * must act as the caller: the token reaches that system as is.
85
+ * @default false
86
+ */
54
87
  includeJwt?: boolean;
55
- /** Challenge TTL in seconds */
88
+ /** Challenge TTL in seconds: how long a request waits for its decision, and a denial without `ttlMs` lasts */
56
89
  challengeTtl?: number;
57
- /** Callback path for approval responses */
90
+ /** The path the server takes decisions on (`POST`). @default '/approval/callback' */
58
91
  callbackPath?: string;
59
92
  };
60
93
  /**
61
- * Enable approval audit logging.
62
- * @default true
94
+ * Log an audit trail through the server's logger (logger `ApprovalAudit`, level `info`): one line per call that had
95
+ * no approval it could use (`approval.requested`, with what became of it) and per approval or denial recorded,
96
+ * revoked or expired (`approval.granted`, `approval.denied`, `approval.revoked`, `approval.expired`). Each line names
97
+ * the tool, scope, user, grantor or revoker and reason, never a session id, a token or a record's `metadata`.
98
+ * Off by default: up to 1.11.2 the option did nothing, and turning it on adds lines with user ids to the logs.
99
+ * @default false
63
100
  */
64
101
  enableAudit?: boolean;
65
102
  /**
66
- * Maximum delegation depth for delegated approvals.
103
+ * The deepest delegation chain a delegated approval may name (`grantedBy.delegationContext`, its `chain` included):
104
+ * a grant with a deeper or broken chain is refused (`ApprovalOperationError`), and a stored one doesn't let a call
105
+ * through. `1` allows only direct delegation, `0` no delegated approval at all. A whole number from 0 to 64.
67
106
  * @default 3
68
107
  */
69
108
  maxDelegationDepth?: number;
@@ -73,14 +112,18 @@ export interface ApprovalPluginOptions {
73
112
  */
74
113
  cleanupIntervalSeconds?: number;
75
114
  }
115
+ /** The headers `recheck.auth: 'custom'` sends with a poll. */
116
+ export type RecheckHeaders = (request: RecheckRequest) => Record<string, string> | Promise<Record<string, string>>;
76
117
  /**
77
118
  * ApprovalPlugin for tool authorization workflows.
78
119
  *
79
120
  * Features:
80
121
  * - Tool approval checking via hook
81
122
  * - Multiple approval scopes (session, user, time-limited, context-specific)
82
- * - PKCE challenges (`mode: 'webhook'`) to build an external approval flow on
83
- * - Full audit trail support
123
+ * - Signed approval requests to an external system, decided on a PKCE-bound callback (`mode: 'webhook'`)
124
+ * - Polling an external approval API (`mode: 'recheck'` with `recheck.url`)
125
+ * - Who granted or revoked each approval, kept with it, and an audit trail in the server's log (`enableAudit`)
126
+ * - Delegation chains, bounded by `maxDelegationDepth`
84
127
  *
85
128
  * @example Basic usage
86
129
  * ```typescript
@@ -100,6 +143,7 @@ export interface ApprovalPluginOptions {
100
143
  * mode: 'webhook',
101
144
  * webhook: {
102
145
  * url: 'https://approval.example.com/webhook',
146
+ * secret: process.env.APPROVAL_WEBHOOK_SECRET,
103
147
  * challengeTtl: 300,
104
148
  * },
105
149
  * }),
@@ -1 +1 @@
1
- {"version":3,"file":"approval.plugin.d.ts","sourceRoot":"","sources":["../src/approval.plugin.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,aAAa,EAOb,KAAK,oBAAoB,EACzB,KAAK,YAAY,EAClB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,iBAAiB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAUrF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAM5C;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;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;;;;;OAKG;IACH,IAAI,CAAC,EAAE,YAAY,CAAC;IAEpB;;OAEG;IACH,OAAO,CAAC,EAAE;QACR,uCAAuC;QACvC,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,4BAA4B;QAC5B,IAAI,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;QAC5C,qCAAqC;QACrC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,+BAA+B;QAC/B,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC;IAEF;;OAEG;IACH,OAAO,CAAC,EAAE;QACR,oCAAoC;QACpC,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,qCAAqC;QACrC,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,+BAA+B;QAC/B,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,2CAA2C;QAC3C,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB,CAAC;IAEF;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAE5B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;AAMD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAaH,MAAM,CAAC,OAAO,OAAO,cAAe,SAAQ,aAAa,CAAC,qBAAqB,CAAC;IAC9E,MAAM,CAAC,cAAc,EAAE,qBAAqB,CAM1C;IAEF,OAAO,EAAE,qBAAqB,CAAC;gBAEnB,OAAO,GAAE,qBAA0B;IAQ/C,mHAAmH;IACnH,OAAgB,aAAa,GAAI,8BAA8B,qBAAqB,KAAG,oBAAoB,EAAE,CAS3G;IAEF;;OAEG;IACH,OAAgB,gBAAgB,GAAI,SAAS,qBAAqB,KAAG,YAAY,EAAE,CA4EjF;CACH;AAGD,OAAO,EAAE,cAAc,EAAE,CAAC"}
1
+ {"version":3,"file":"approval.plugin.d.ts","sourceRoot":"","sources":["../src/approval.plugin.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,aAAa,EAQb,KAAK,oBAAoB,EACzB,KAAK,YAAY,EAClB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,iBAAiB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAqBrF,OAAO,EAAmB,KAAK,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAMnF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AA0C5C;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;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;;;;;;;;OAQG;IACH,IAAI,CAAC,EAAE,YAAY,CAAC;IAEpB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE;QACR,2GAA2G;QAC3G,GAAG,CAAC,EAAE,MAAM,CAAC;QACb;;;;;;;WAOG;QACH,IAAI,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;QAC5C,wCAAwC;QACxC,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,+DAA+D;QAC/D,OAAO,CAAC,EAAE,cAAc,CAAC;QACzB,gHAAgH;QAChH,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,+DAA+D;QAC/D,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,yGAAyG;QACzG,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC;IAEF;;;;;OAKG;IACH,OAAO,CAAC,EAAE;QACR,2GAA2G;QAC3G,GAAG,CAAC,EAAE,MAAM,CAAC;QACb;;;WAGG;QACH,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB;;;;WAIG;QACH,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,8GAA8G;QAC9G,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,qFAAqF;QACrF,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB,CAAC;IAEF;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAE5B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;AAED,8DAA8D;AAC9D,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,EAAE,cAAc,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAMnH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAaH,MAAM,CAAC,OAAO,OAAO,cAAe,SAAQ,aAAa,CAAC,qBAAqB,CAAC;IAC9E,MAAM,CAAC,cAAc,EAAE,qBAAqB,CAM1C;IAEF,OAAO,EAAE,qBAAqB,CAAC;gBAEnB,OAAO,GAAE,qBAA0B;IAQ/C,mHAAmH;IACnH,OAAgB,aAAa,GAAI,8BAA8B,qBAAqB,KAAG,oBAAoB,EAAE,CAS3G;IAEF;;OAEG;IACH,OAAgB,gBAAgB,GAAI,SAAS,qBAAqB,KAAG,YAAY,EAAE,CAsFjF;CACH;AAGD,OAAO,EAAE,cAAc,EAAE,CAAC"}
@@ -3,10 +3,12 @@
3
3
  *
4
4
  * @module @frontmcp/plugin-approval
5
5
  */
6
- import { Reference } from '@frontmcp/sdk';
7
- import type { ApprovalStore } from './stores/approval-store.interface';
6
+ import type { Reference } from '@frontmcp/sdk';
7
+ import type { ApprovalAuditSink } from './audit/approval-audit';
8
+ import type { ExternalApprover } from './external/approval-decisions';
8
9
  import type { ApprovalService } from './services/approval.service';
9
10
  import type { ChallengeService } from './services/challenge.service';
11
+ import type { ApprovalStore } from './stores/approval-store.interface';
10
12
  /**
11
13
  * Token for injecting the ApprovalStore.
12
14
  */
@@ -19,4 +21,11 @@ export declare const ApprovalServiceToken: Reference<ApprovalService>;
19
21
  * Token for injecting the ChallengeService (PKCE challenge management).
20
22
  */
21
23
  export declare const ChallengeServiceToken: Reference<ChallengeService>;
24
+ /**
25
+ * Token for the external approval system a call without an approval asks: present when `webhook.url` or
26
+ * `recheck.url` is set.
27
+ */
28
+ export declare const ExternalApproverToken: Reference<ExternalApprover>;
29
+ /** Token for the audit trail: present with `enableAudit: true`. */
30
+ export declare const ApprovalAuditToken: Reference<ApprovalAuditSink>;
22
31
  //# sourceMappingURL=approval.symbols.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"approval.symbols.d.ts","sourceRoot":"","sources":["../src/approval.symbols.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAErE;;GAEG;AACH,eAAO,MAAM,kBAAkB,EAAE,SAAS,CAAC,aAAa,CAE3B,CAAC;AAE9B;;GAEG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAAS,CAAC,eAAe,CAE7B,CAAC;AAEhC;;GAEG;AACH,eAAO,MAAM,qBAAqB,EAAE,SAAS,CAAC,gBAAgB,CAE9B,CAAC"}
1
+ {"version":3,"file":"approval.symbols.d.ts","sourceRoot":"","sources":["../src/approval.symbols.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAEvE;;GAEG;AACH,eAAO,MAAM,kBAAkB,EAAE,SAAS,CAAC,aAAa,CAE3B,CAAC;AAE9B;;GAEG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAAS,CAAC,eAAe,CAE7B,CAAC;AAEhC;;GAEG;AACH,eAAO,MAAM,qBAAqB,EAAE,SAAS,CAAC,gBAAgB,CAE9B,CAAC;AAEjC;;;GAGG;AACH,eAAO,MAAM,qBAAqB,EAAE,SAAS,CAAC,gBAAgB,CAE9B,CAAC;AAEjC,mEAAmE;AACnE,eAAO,MAAM,kBAAkB,EAAE,SAAS,CAAC,iBAAiB,CAE3B,CAAC"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The approval audit trail `enableAudit` turns on: one log line per request, grant, denial, revocation and expiry.
3
+ *
4
+ * @module @frontmcp/plugin-approval
5
+ */
6
+ import type { FrontMcpLogger } from '@frontmcp/sdk';
7
+ import type { ApprovalContext, ApprovalGrantor, ApprovalRecord, ApprovalRevoker } from '../types';
8
+ /**
9
+ * - `approval.requested`: a call had no approval it could use. `state` says what became of it: `pending` or `expired`
10
+ * (refused), `denied` (refused by a recorded denial or the recheck system), or `approved` (the recheck system
11
+ * approved it). `via` names the external system asked, if any.
12
+ * - `approval.granted` / `approval.denied`: an approval or a denial was recorded.
13
+ * - `approval.revoked`: an approval was revoked, or a session's approvals were cleared (`count`).
14
+ * - `approval.expired`: the cleanup deleted an expired approval or denial.
15
+ */
16
+ export type ApprovalAuditEventType = 'approval.requested' | 'approval.granted' | 'approval.denied' | 'approval.revoked' | 'approval.expired';
17
+ /** One audit line's fields. It never carries a session id, a token or a record's `metadata`. */
18
+ export interface ApprovalAuditEvent {
19
+ type: ApprovalAuditEventType;
20
+ toolId?: string;
21
+ scope?: string;
22
+ userId?: string;
23
+ context?: Pick<ApprovalContext, 'type' | 'identifier'>;
24
+ state?: 'pending' | 'expired' | 'denied' | 'approved';
25
+ via?: 'webhook' | 'recheck';
26
+ grantedBy?: ApprovalGrantor;
27
+ revokedBy?: ApprovalRevoker;
28
+ reason?: string;
29
+ expiresAt?: number;
30
+ count?: number;
31
+ }
32
+ /** Where audit events go. */
33
+ export interface ApprovalAuditSink {
34
+ record(event: ApprovalAuditEvent): void;
35
+ }
36
+ /** The audit fields of a stored record. */
37
+ export declare function auditFieldsOf(record: ApprovalRecord): Omit<ApprovalAuditEvent, 'type'>;
38
+ /** Writes each event as an `info` line of the `ApprovalAudit` logger: `<type> <toolId>`, then the event's fields. */
39
+ export declare class LoggerAuditSink implements ApprovalAuditSink {
40
+ private readonly logger;
41
+ constructor(logger: FrontMcpLogger);
42
+ record(event: ApprovalAuditEvent): void;
43
+ }
44
+ //# sourceMappingURL=approval-audit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-audit.d.ts","sourceRoot":"","sources":["../../src/audit/approval-audit.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAElG;;;;;;;GAOG;AACH,MAAM,MAAM,sBAAsB,GAC9B,oBAAoB,GACpB,kBAAkB,GAClB,iBAAiB,GACjB,kBAAkB,GAClB,kBAAkB,CAAC;AAEvB,gGAAgG;AAChG,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,sBAAsB,CAAC;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,IAAI,CAAC,eAAe,EAAE,MAAM,GAAG,YAAY,CAAC,CAAC;IACvD,KAAK,CAAC,EAAE,SAAS,GAAG,SAAS,GAAG,QAAQ,GAAG,UAAU,CAAC;IACtD,GAAG,CAAC,EAAE,SAAS,GAAG,SAAS,CAAC;IAC5B,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,6BAA6B;AAC7B,MAAM,WAAW,iBAAiB;IAChC,MAAM,CAAC,KAAK,EAAE,kBAAkB,GAAG,IAAI,CAAC;CACzC;AAED,2CAA2C;AAC3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAUtF;AAED,qHAAqH;AACrH,qBAAa,eAAgB,YAAW,iBAAiB;IAC3C,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,cAAc;IAEnD,MAAM,CAAC,KAAK,EAAE,kBAAkB,GAAG,IAAI;CAIxC"}
package/esm/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : undefined;
2
2
  const require = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || 'file:///') : undefined;
3
3
  // __frontmcpCreateRequire
4
- var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);import{DynamicPlugin as DynamicPlugin2,FRONTMCP_CONTEXT,Plugin as Plugin2,ProviderScope as ProviderScope4,ScopeEntry as ScopeEntry2,storeProvider}from"@frontmcp/sdk";import{randomUUID}from"@frontmcp/utils";function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function resolveApprovalIdentity(ctx){const extra=ctx?.authInfo?.extra;const userId=nonEmptyString(extra?.["userId"])??nonEmptyString(extra?.["sub"])??nonEmptyString(ctx?.authInfo?.clientId);const sessionId=nonEmptyString(ctx?.verifiedSessionId);if(sessionId){return{sessionId,userId}}return{sessionId:userId?`stateless-user:${userId}`:`unidentified:${randomUUID()}`,userId}}var ApprovalStoreToken=Symbol.for("plugin:approval:store");var ApprovalServiceToken=Symbol.for("plugin:approval:service");var ChallengeServiceToken=Symbol.for("plugin:approval:challenge-service");import{PublicMcpError}from"@frontmcp/sdk";var ApprovalError=class extends PublicMcpError{constructor(message,code="APPROVAL_REQUIRED",statusCode=403){super(message,code,statusCode);this.name="ApprovalError"}};var ApprovalRequiredError=class extends ApprovalError{constructor(details){super(details.message);this.details=details;this.name="ApprovalRequiredError"}details;toJsonRpcError(){return{code:-32600,message:this.details.message,data:{type:"approval_required",toolId:this.details.toolId,state:this.details.state,options:this.details.approvalOptions}}}};var ApprovalOperationError=class extends ApprovalError{constructor(operation,reason){super(`Approval ${operation} failed: ${reason}`,"APPROVAL_OPERATION_FAILED",400);this.operation=operation;this.reason=reason;this.name="ApprovalOperationError"}operation;reason;toJsonRpcError(){return{code:-32603,message:"Approval operation failed",data:{type:"approval_operation_error",operation:this.operation}}}};var ApprovalScopeNotAllowedError=class extends ApprovalError{constructor(requestedScope,allowedScopes){super(`Approval scope '${requestedScope}' is not allowed for this tool. Allowed scopes: ${allowedScopes.join(", ")}`,"APPROVAL_SCOPE_NOT_ALLOWED",400);this.requestedScope=requestedScope;this.allowedScopes=allowedScopes;this.name="ApprovalScopeNotAllowedError"}requestedScope;allowedScopes;toJsonRpcError(){return{code:-32602,message:this.message,data:{type:"approval_scope_not_allowed",requestedScope:this.requestedScope,allowedScopes:this.allowedScopes}}}};var ApprovalExpiredError=class extends ApprovalError{constructor(toolId,expiredAt){super(`Approval for tool '${toolId}' expired at ${new Date(expiredAt).toISOString()}`,"APPROVAL_EXPIRED",403);this.toolId=toolId;this.expiredAt=expiredAt;this.name="ApprovalExpiredError"}toolId;expiredAt;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"approval_expired",toolId:this.toolId,expiredAt:this.expiredAt}}}};var ChallengeValidationError=class extends ApprovalError{constructor(reason="invalid",message){super(message??`PKCE challenge validation failed: ${reason}`,"CHALLENGE_VALIDATION_FAILED",400);this.reason=reason;this.name="ChallengeValidationError"}reason;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"challenge_validation_error",reason:this.reason}}}};var ApprovalScope=(ApprovalScope2=>{ApprovalScope2["SESSION"]="session";ApprovalScope2["USER"]="user";ApprovalScope2["TIME_LIMITED"]="time_limited";ApprovalScope2["TOOL_SPECIFIC"]="tool_specific";ApprovalScope2["CONTEXT_SPECIFIC"]="context_specific";return ApprovalScope2})(ApprovalScope||{});var ApprovalState=(ApprovalState2=>{ApprovalState2["PENDING"]="pending";ApprovalState2["APPROVED"]="approved";ApprovalState2["DENIED"]="denied";ApprovalState2["EXPIRED"]="expired";return ApprovalState2})(ApprovalState||{});function resolveApprovalRequirement(config){if(config===true){return{required:true,defaultScope:"session"}}if(config===false||config===void 0){return{required:false}}return{...config,required:config.required??true,defaultScope:config.defaultScope??"session"}}function effectiveExpiresAt(record,requirement){const capped=requirement.maxTtlMs!==void 0?record.grantedAt+requirement.maxTtlMs:void 0;if(record.expiresAt===void 0)return capped;return capped===void 0?record.expiresAt:Math.min(record.expiresAt,capped)}function isApprovalExpired(record,requirement,now){const expiresAt=effectiveExpiresAt(record,requirement);return expiresAt!==void 0&&now>expiresAt}function isApprovalUsable(record,requirement,now){if(record.state!=="approved")return false;if(requirement.allowedScopes?.length&&!requirement.allowedScopes.includes(record.scope))return false;return!isApprovalExpired(record,requirement,now)}function assertValidTtl(ttlMs){if(ttlMs===void 0)return;if(!Number.isFinite(ttlMs)||ttlMs<=0){throw new ApprovalOperationError("grant",`ttlMs must be a positive number of milliseconds, got ${ttlMs}`)}}function checkGrantAgainstPolicy(toolId,scope,ttlMs,requirement){assertValidTtl(ttlMs);if(!requirement)return ttlMs;if(requirement.allowedScopes?.length&&!requirement.allowedScopes.includes(scope)){throw new ApprovalScopeNotAllowedError(scope,requirement.allowedScopes)}const{maxTtlMs}=requirement;if(maxTtlMs===void 0)return ttlMs;if(ttlMs===void 0)return maxTtlMs;if(ttlMs>maxTtlMs){throw new ApprovalOperationError("grant",`ttlMs ${ttlMs} exceeds the maximum of ${maxTtlMs} ms that tool "${toolId}" allows`)}return ttlMs}import{DynamicPlugin,isEntryGatedBy,Plugin,ScopeEntry,ToolHook}from"@frontmcp/sdk";import{z}from"@frontmcp/lazy-zod";var approvalScopeSchema=z.nativeEnum(ApprovalScope);var approvalStateSchema=z.nativeEnum(ApprovalState);var approvalMethodSchema=z.enum(["interactive","implicit","delegation","batch","api"]);var approvalSourceTypeSchema=z.string().min(1);var revocationMethodSchema=z.enum(["interactive","implicit","policy","expiry"]);var approvalCategorySchema=z.enum(["read","write","delete","execute","admin"]);var riskLevelSchema=z.enum(["low","medium","high","critical"]);var approvalContextSchema=z.object({type:z.string().min(1),identifier:z.string().min(1),metadata:z.record(z.string(),z.unknown()).optional()});var delegationContextSchema=z.object({delegatorId:z.string().min(1),delegateId:z.string().min(1),purpose:z.string().optional(),constraints:z.record(z.string(),z.unknown()).optional()});var approvalGrantorSchema=z.object({source:approvalSourceTypeSchema,identifier:z.string().optional(),displayName:z.string().optional(),method:approvalMethodSchema.optional(),origin:z.string().optional(),delegationContext:delegationContextSchema.optional()});var approvalRevokerSchema=z.object({source:z.string().min(1),identifier:z.string().optional(),displayName:z.string().optional(),method:revocationMethodSchema.optional()});var approvalRecordSchema=z.object({toolId:z.string().min(1),state:approvalStateSchema,scope:approvalScopeSchema,grantedAt:z.number(),expiresAt:z.number().optional(),ttlMs:z.number().optional(),sessionId:z.string().optional(),userId:z.string().optional(),context:approvalContextSchema.optional(),grantedBy:approvalGrantorSchema,approvalChain:z.array(approvalGrantorSchema).optional(),reason:z.string().optional(),metadata:z.record(z.string(),z.unknown()).optional(),revokedAt:z.number().optional(),revokedBy:approvalRevokerSchema.optional(),revocationReason:z.string().optional()});var toolApprovalRequirementSchema=z.object({required:z.boolean().optional(),defaultScope:approvalScopeSchema.optional(),allowedScopes:z.array(approvalScopeSchema).optional(),maxTtlMs:z.number().positive().optional(),alwaysPrompt:z.boolean().optional(),skipApproval:z.boolean().optional(),approvalMessage:z.string().optional(),category:approvalCategorySchema.optional(),riskLevel:riskLevelSchema.optional(),preApprovedContexts:z.array(approvalContextSchema).optional()});function userGrantor(userId,displayName,options){return{source:"user",identifier:userId,displayName,method:options?.method??"interactive",origin:options?.origin}}function policyGrantor(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"implicit"}}function adminGrantor(adminId,displayName,options){return{source:"admin",identifier:adminId,displayName,method:options?.method??"interactive",origin:options?.origin}}function systemGrantor(systemId="system"){return{source:"system",identifier:systemId,method:"implicit"}}function agentGrantor(agentId,delegationContext,displayName){return{source:"agent",identifier:agentId,displayName,method:"delegation",delegationContext}}function apiGrantor(apiKeyPrefix,serviceName){return{source:"api",identifier:apiKeyPrefix,displayName:serviceName,method:"api",origin:"api"}}function oauthGrantor(tokenId,provider){return{source:"oauth",identifier:tokenId,displayName:provider,method:"api",origin:"oauth"}}function testGrantor(){return{source:"test",identifier:"test",method:"implicit"}}function customGrantor(source,identifier,options){return{source,identifier,displayName:options?.displayName,method:options?.method,origin:options?.origin,delegationContext:options?.delegationContext}}function userRevoker(userId,displayName){return{source:"user",identifier:userId,displayName,method:"interactive"}}function adminRevoker(adminId,displayName){return{source:"admin",identifier:adminId,displayName,method:"interactive"}}function expiryRevoker(){return{source:"expiry",method:"expiry"}}function sessionEndRevoker(sessionId){return{source:"session_end",identifier:sessionId,method:"implicit"}}function policyRevoker(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"policy"}}function normalizeGrantor(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function normalizeRevoker(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function isGrantorSource(grantor,source){return grantor.source===source}function isHumanGrantor(grantor){return grantor.source==="user"||grantor.source==="admin"}function isAutoGrantor(grantor){return grantor.source==="policy"||grantor.source==="system"||grantor.source==="test"}function isDelegatedGrantor(grantor){return grantor.source==="agent"&&!!grantor.delegationContext}function isApiGrantor(grantor){return grantor.source==="api"||grantor.source==="oauth"}var decidedCalls=new WeakSet;var ApprovalCheckPlugin=class extends DynamicPlugin{async checkApproval(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;const metadata=tool.metadata;const approvalConfig=resolveApprovalRequirement(metadata["approval"]);if(!approvalConfig.required){return}if(approvalConfig.skipApproval){return}if(decidedCalls.has(toolContext))return;await this.enforceApproval(flowCtx,tool,toolContext,approvalConfig,this.coveringStores(tool));decidedCalls.add(toolContext)}async enforceApproval(flowCtx,tool,toolContext,approvalConfig,stores){const{sessionId,userId}=resolveApprovalIdentity(toolContext.tryGetContext?.());const currentContext=this.getCurrentContext(flowCtx);const stored=[];for(const store of stores){const records2=await this.readApprovals(store,tool.fullName,sessionId,userId,currentContext);stored.push(...records2.map(record=>({store,record})))}const records=stored.map(({record})=>record);if(records.some(record=>record.state==="denied")){throw new ApprovalRequiredError({toolId:tool.fullName,state:"denied",message:`Tool "${tool.fullName}" execution denied.`})}if(!approvalConfig.alwaysPrompt&&this.isPreApprovedContext(approvalConfig,currentContext)){return}const approved=records.filter(record=>record.state==="approved");const now=Date.now();const usable=stored.filter(({record})=>isApprovalUsable(record,approvalConfig,now));if(approvalConfig.alwaysPrompt){for(const{store,record}of usable){if(await this.consumeApproval(store,record,sessionId,userId,currentContext))return}}else if(usable.length>0){return}await this.handleApprovalRequired(flowCtx,approvalConfig,approved.find(record=>isApprovalExpired(record,approvalConfig,now))??approved[0])}coveringStores(tool){const stores=new Set([this.get(ApprovalStoreToken)]);let scope;try{scope=this.get(ScopeEntry)}catch{scope=void 0}if(!scope?.hooks)return[...stores];for(const hook of scope.hooks.getFlowHooks("tools:call-tool")){const gate=hook.metadata.target;if(gate instanceof ApprovalCheckPlugin&&isEntryGatedBy(scope,{tool},gate)){stores.add(gate.get(ApprovalStoreToken))}}return[...stores]}async consumeApproval(store,record,sessionId,userId,context){if(store.consumeApproval){return store.consumeApproval(record,sessionId,userId,context)}return store.revokeApproval({toolId:record.toolId,sessionId,userId,revokedBy:"system",reason:"Used by a call of an alwaysPrompt tool"})}async readApprovals(store,toolId,sessionId,userId,context){if(store.getApprovals){return store.getApprovals(toolId,sessionId,userId,context)}const record=await store.getApproval(toolId,sessionId,userId,context);return record?[record]:[]}getCurrentContext(flowCtx){const ctx=flowCtx.state.toolContext?.tryGetContext?.();const sessionContext=ctx?.authInfo?.extra?.["approvalContext"];return this.isApprovalContext(sessionContext)?sessionContext:void 0}isApprovalContext(value){return typeof value==="object"&&value!==null&&"type"in value&&"identifier"in value&&typeof value.type==="string"&&typeof value.identifier==="string"}isPreApprovedContext(config,currentContext){if(!currentContext||!config.preApprovedContexts?.length){return false}return config.preApprovedContexts.some(preApproved=>preApproved.type===currentContext.type&&preApproved.identifier===currentContext.identifier)}async handleApprovalRequired(flowCtx,config,existingApproval){const{tool}=flowCtx.state;const message=config.approvalMessage??`Tool "${tool?.fullName}" requires approval to execute. Allow?`;const isExpiredApproval=existingApproval?isApprovalExpired(existingApproval,config,Date.now()):false;throw new ApprovalRequiredError({toolId:tool?.fullName??"unknown",state:isExpiredApproval?"expired":"pending",message,approvalOptions:{allowedScopes:config.allowedScopes,defaultScope:config.defaultScope,maxTtlMs:config.maxTtlMs,category:config.category,riskLevel:config.riskLevel}})}};__decorateClass([ToolHook.Will("execute",{priority:100,appliesTo:"uncovered-apps"})],ApprovalCheckPlugin.prototype,"checkApproval",1);ApprovalCheckPlugin=__decorateClass([Plugin({name:"approval:check",description:"Checks tool approval state before execution",enforcesMetadata:["approval"]})],ApprovalCheckPlugin);import{isAnonymousSubject,Provider,ProviderScope}from"@frontmcp/sdk";var ApprovalService=class{constructor(store,sessionId,userId,requirementOf=()=>void 0){this.store=store;this.sessionId=sessionId;this.userId=userId;this.requirementOf=requirementOf}store;sessionId;userId;requirementOf;checkGrant(toolId,scope,ttlMs){return checkGrantAgainstPolicy(toolId,scope,ttlMs,this.requirementOf(toolId))}get signedInUserId(){return this.userId&&!isAnonymousSubject(this.userId)?this.userId:void 0}defaultGrantor(){const userId=this.signedInUserId;return userId?userGrantor(userId,void 0,{method:"implicit"}):{source:"user",method:"implicit"}}defaultRevoker(){const userId=this.signedInUserId;return userId?{source:"user",identifier:userId,method:"implicit"}:{source:"user",method:"implicit"}}async isApproved(toolId,context){const requirement=this.requirementOf(toolId);if(!requirement||!this.store.getApprovals){return this.store.isApproved(toolId,this.sessionId,this.userId,context)}const records=await this.store.getApprovals(toolId,this.sessionId,this.userId,context);if(records.some(record=>record.state==="denied"))return false;const now=Date.now();return records.some(record=>isApprovalUsable(record,requirement,now))}async getApproval(toolId){return this.store.getApproval(toolId,this.sessionId,this.userId)}async getSessionApprovals(){return this.store.queryApprovals({sessionId:this.sessionId,states:["approved"],includeExpired:false})}async getUserApprovals(){if(!this.userId)return[];return this.store.queryApprovals({userId:this.userId,scope:"user",states:["approved"],includeExpired:false})}async queryApprovals(query){const records=await this.store.queryApprovals(query);return records.filter(record=>record.sessionId===this.sessionId||this.userId!==void 0&&record.userId===this.userId)}async getRevocations(toolId){return await this.store.getRevocations?.(toolId,this.sessionId,this.userId)??[]}async grantSessionApproval(toolId,options={}){const ttlMs=this.checkGrant(toolId,"session");return this.store.grantApproval({toolId,scope:"session",ttlMs,sessionId:this.sessionId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantUserApproval(toolId,options={}){if(!this.userId){throw new Error("Cannot grant user approval without userId")}const ttlMs=this.checkGrant(toolId,"user");return this.store.grantApproval({toolId,scope:"user",ttlMs,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantTimeLimitedApproval(toolId,ttlMs,options={}){this.checkGrant(toolId,"time_limited",ttlMs);return this.store.grantApproval({toolId,scope:"time_limited",ttlMs,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantContextApproval(toolId,context,options={}){const ttlMs=this.checkGrant(toolId,"context_specific");return this.store.grantApproval({toolId,scope:"context_specific",ttlMs,context,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async revokeApproval(toolId,options={}){return this.store.revokeApproval({toolId,sessionId:this.sessionId,userId:this.userId,revokedBy:options.revokedBy??this.defaultRevoker(),reason:options.reason})}async clearSessionApprovals(){return this.store.clearSessionApprovals(this.sessionId)}};ApprovalService=__decorateClass([Provider({name:"provider:approval:service",description:"Service for managing tool approvals",scope:ProviderScope.CONTEXT})],ApprovalService);function createApprovalService(store,sessionId,userId,requirementOf){return new ApprovalService(store,sessionId,userId,requirementOf)}import{Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";import{generatePkcePair,generateCodeChallenge,createStorage,createMemoryStorage}from"@frontmcp/utils";var ChallengeService=class{storage;options;initialized=false;ownedStorage=false;constructor(options={}){this.options={storage:options.storage??{type:"auto"},storageInstance:options.storageInstance,namespace:options.namespace??"approval:challenge",defaultTtlSeconds:options.defaultTtlSeconds??300}}async initialize(){if(this.initialized)return;if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await createStorage(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}this.initialized=true}ensureInitialized(){if(!this.initialized){throw new Error("ChallengeService not initialized. Call initialize() first.")}}async createChallenge(options){this.ensureInitialized();const{codeVerifier,codeChallenge}=generatePkcePair();const now=Date.now();const ttlSeconds=options.ttlSeconds??this.options.defaultTtlSeconds;const expiresAt=now+ttlSeconds*1e3;const record={toolId:options.toolId,sessionId:options.sessionId,userId:options.userId,requestedScope:options.requestedScope,requestInfo:options.requestInfo,createdAt:now,expiresAt,webhookSent:false};await this.storage.set(codeChallenge,JSON.stringify(record),{ttlSeconds});return{codeVerifier,codeChallenge,expiresAt}}async verifyAndConsume(codeVerifier){this.ensureInitialized();const{codeChallenge}=generatePkcePairFromVerifier(codeVerifier);const recordJson=await this.storage.get(codeChallenge);if(!recordJson){throw new ChallengeValidationError("not_found","Invalid or expired challenge")}const record=JSON.parse(recordJson);if(Date.now()>record.expiresAt){await this.storage.delete(codeChallenge);throw new ChallengeValidationError("expired","Challenge expired")}await this.storage.delete(codeChallenge);return record}async markWebhookSent(codeChallenge){this.ensureInitialized();const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return false;const record=JSON.parse(recordJson);record.webhookSent=true;const remainingMs=record.expiresAt-Date.now();if(remainingMs<=0){await this.storage.delete(codeChallenge);return false}const ttlSeconds=Math.ceil(remainingMs/1e3);await this.storage.set(codeChallenge,JSON.stringify(record),{ttlSeconds});return true}async getChallenge(codeChallenge){this.ensureInitialized();const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return null;const record=JSON.parse(recordJson);if(Date.now()>record.expiresAt){await this.storage.delete(codeChallenge);return null}return record}async deleteChallenge(codeChallenge){this.ensureInitialized();const exists=await this.storage.exists(codeChallenge);if(exists){await this.storage.delete(codeChallenge);return true}return false}async close(){if(this.ownedStorage&&this.storage){await this.storage.root.disconnect()}this.initialized=false}};ChallengeService=__decorateClass([Provider2({name:"provider:approval:challenge-service",description:"PKCE challenge service for webhook approval flows",scope:ProviderScope2.GLOBAL})],ChallengeService);function generatePkcePairFromVerifier(codeVerifier){return{codeVerifier,codeChallenge:generateCodeChallenge(codeVerifier)}}function createMemoryChallengeService(options={}){const memoryStorage=createMemoryStorage();return new ChallengeService({...options,storageInstance:memoryStorage})}import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{createMemoryStorage as createMemoryStorage2,createNamespacedStorage,createStorage as createStorage2,StorageNotSupportedError}from"@frontmcp/utils";function escapePattern(str){return str.replace(/[*?[\]\\]/g,"\\$&")}function isSameRecord(a,b){return a.toolId===b.toolId&&a.state===b.state&&a.scope===b.scope&&a.grantedAt===b.grantedAt&&a.sessionId===b.sessionId&&a.userId===b.userId&&a.context?.type===b.context?.type&&a.context?.identifier===b.context?.identifier}var REVOCATION_RETENTION_SECONDS=24*60*60;var TIME_LIMITED_KEY_SEGMENT=`scope:${"time_limited"}`;var ApprovalStorageStore=class{storage;revocationStorage;options;cleanupInterval;initialized=false;ownedStorage=false;constructor(options={}){this.options={storage:options.storage??{type:"auto"},storageInstance:options.storageInstance,namespace:options.namespace??"approval",cleanupIntervalSeconds:options.cleanupIntervalSeconds??60}}async initialize(){if(this.initialized){return}if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await createStorage2(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}if(this.options.cleanupIntervalSeconds>0){this.cleanupInterval=setInterval(()=>{void this.clearExpiredApprovals()},this.options.cleanupIntervalSeconds*1e3);this.cleanupInterval.unref?.()}this.initialized=true}get revocations(){this.revocationStorage??=createNamespacedStorage(this.storage.root,`${this.storage.prefix.replace(/:$/,"")}-revoked`);return this.revocationStorage}ensureInitialized(){if(!this.initialized){throw new Error("ApprovalStorageStore not initialized. Call initialize() first.")}}buildKey(toolId,sessionId,userId,context){const parts=[toolId];if(sessionId)parts.push(`session:${sessionId}`);if(userId)parts.push(`user:${userId}`);if(context)parts.push(`ctx:${context.type}:${context.identifier}`);return parts.join(":")}timeLimitedKey(toolId,sessionId,userId){return`${this.buildKey(toolId,sessionId,userId)}:${TIME_LIMITED_KEY_SEGMENT}`}recordKey(options){const{toolId,scope,sessionId,userId,context}=options;if(scope==="time_limited"&&!context&&!(sessionId&&userId)){return this.timeLimitedKey(toolId,sessionId,userId)}return this.buildKey(toolId,sessionId,userId,context)}parseRecord(value){if(!value)return void 0;try{const parsed=JSON.parse(value);const result=approvalRecordSchema.safeParse(parsed);if(!result.success){return void 0}return result.data}catch{return void 0}}isExpired(approval){return approval.expiresAt!==void 0&&Date.now()>approval.expiresAt}callerKeys(toolId,sessionId,userId,context){const keys=[this.buildKey(toolId,sessionId),this.timeLimitedKey(toolId,sessionId)];if(userId){keys.push(this.buildKey(toolId,void 0,userId),this.timeLimitedKey(toolId,void 0,userId),this.buildKey(toolId,sessionId,userId))}if(context){keys.push(this.buildKey(toolId,sessionId,void 0,context));if(userId)keys.push(this.buildKey(toolId,sessionId,userId,context))}return[...new Set(keys)]}async getApprovals(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const key of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.storage.get(key));if(record&&record.toolId===toolId&&!this.isExpired(record)){records.push(record)}}return records}async getApproval(toolId,sessionId,userId,context){const records=await this.getApprovals(toolId,sessionId,userId,context);return records.find(record=>record.state==="denied")??records[0]}async queryApprovals(query){this.ensureInitialized();const results=[];const pattern=query.toolId?`${escapePattern(query.toolId)}:*`:"*";const keys=await this.storage.keys(pattern);const values=await this.storage.mget(keys);for(const value of values){const approval=this.parseRecord(value);if(!approval)continue;if(!query.includeExpired&&this.isExpired(approval)){continue}if(query.toolId&&approval.toolId!==query.toolId)continue;if(query.toolIds&&!query.toolIds.includes(approval.toolId))continue;if(query.scope&&approval.scope!==query.scope)continue;if(query.scopes&&!query.scopes.includes(approval.scope))continue;if(query.state&&approval.state!==query.state)continue;if(query.states&&!query.states.includes(approval.state))continue;if(query.sessionId&&approval.sessionId!==query.sessionId)continue;if(query.userId&&approval.userId!==query.userId)continue;if(query.context){if(!approval.context||approval.context.type!==query.context.type||approval.context.identifier!==query.context.identifier){continue}}results.push(approval)}return results}async grantApproval(options){this.ensureInitialized();assertValidTtl(options.ttlMs);if(options.scope==="time_limited"&&options.ttlMs===void 0){throw new ApprovalOperationError("grant","a time-limited approval needs ttlMs")}const now=Date.now();const expiresAt=options.ttlMs!==void 0?now+options.ttlMs:void 0;const grantedBy=normalizeGrantor(options.grantedBy);const record={toolId:options.toolId,state:"approved",scope:options.scope,grantedAt:now,expiresAt,ttlMs:options.ttlMs,sessionId:options.sessionId,userId:options.userId,context:options.context,grantedBy,reason:options.reason,metadata:options.metadata};const key=this.recordKey(options);const ttlSeconds=options.ttlMs!==void 0?Math.ceil(options.ttlMs/1e3):void 0;await this.storage.set(key,JSON.stringify(record),{ttlSeconds});return record}async revokeApproval(options){this.ensureInitialized();const{toolId,sessionId,userId,context}=options;if(!sessionId&&!userId&&!context){return false}const keys=await this.storage.keys(`${escapePattern(toolId)}:*`);const values=await this.storage.mget(keys);const keysToDelete=[];const revoked=new Map;for(let i=0;i<keys.length;i++){const record=this.parseRecord(values[i]);if(!record||record.toolId!==toolId||record.state==="denied")continue;const matches=keysToDelete.length;if(context){const sameSession=sessionId!==void 0&&record.sessionId===sessionId;if(record.context?.type===context.type&&record.context.identifier===context.identifier&&(!sessionId||sameSession)&&(!userId||record.userId===userId||sameSession&&record.userId===void 0)){keysToDelete.push(keys[i])}}else if(sessionId&&record.sessionId===sessionId||userId&&record.userId===userId){keysToDelete.push(keys[i])}if(keysToDelete.length>matches)revoked.set(keys[i],record)}if(keysToDelete.length===0){return false}const revokedAt=Date.now();const revokedBy=normalizeRevoker(options.revokedBy);for(const[key,record]of revoked){const entry={...record,revokedAt,revokedBy,revocationReason:options.reason};await this.revocations.set(key,JSON.stringify(entry),{ttlSeconds:REVOCATION_RETENTION_SECONDS})}await this.storage.mdelete(keysToDelete);return true}async consumeApproval(record,sessionId,userId,context){this.ensureInitialized();for(const key of this.callerKeys(record.toolId,sessionId,userId,context)){const storedValue=await this.storage.get(key);const stored=this.parseRecord(storedValue);if(storedValue!==null&&stored&&isSameRecord(stored,record)){return this.deleteIfUnchanged(key,storedValue)}}return false}async deleteIfUnchanged(key,storedValue){try{return await this.storage.deleteIfEquals(key,storedValue)}catch(error){if(!(error instanceof StorageNotSupportedError))throw error;return this.storage.delete(key)}}async getRevocations(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const key of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.revocations.get(key));if(record&&record.toolId===toolId)records.push(record)}return records.sort((a,b)=>(a.revokedAt??0)-(b.revokedAt??0))}async isApproved(toolId,sessionId,userId,context){const approval=await this.getApproval(toolId,sessionId,userId,context);return approval?.state==="approved"}async clearSessionApprovals(sessionId){this.ensureInitialized();const escapedSessionId=escapePattern(sessionId);const keys=[...new Set([...await this.storage.keys(`*:session:${escapedSessionId}`),...await this.storage.keys(`*:session:${escapedSessionId}:*`)])];if(keys.length===0){return 0}return await this.storage.mdelete(keys)}async clearExpiredApprovals(){this.ensureInitialized();const now=Date.now();const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);const keysToDelete=[];for(let i=0;i<keys.length;i++){const approval=this.parseRecord(values[i]);if(approval&&approval.expiresAt&&approval.expiresAt<=now){keysToDelete.push(keys[i])}}if(keysToDelete.length>0){return await this.storage.mdelete(keysToDelete)}return 0}async getStats(){this.ensureInitialized();const byScope={["session"]:0,["user"]:0,["time_limited"]:0,["tool_specific"]:0,["context_specific"]:0};const byState={["pending"]:0,["approved"]:0,["denied"]:0,["expired"]:0};const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);let total=0;for(const value of values){const approval=this.parseRecord(value);if(approval){total++;byScope[approval.scope]++;byState[approval.state]++}}return{totalApprovals:total,byScope,byState}}async close(){if(this.cleanupInterval){clearInterval(this.cleanupInterval);this.cleanupInterval=void 0}if(this.ownedStorage&&this.storage){await this.storage.root.disconnect()}this.revocationStorage=void 0;this.initialized=false}};ApprovalStorageStore=__decorateClass([Provider3({name:"provider:approval:store:storage",description:"Storage-backed approval store (supports Memory, Redis, Vercel KV, Upstash)",scope:ProviderScope3.GLOBAL})],ApprovalStorageStore);function createApprovalMemoryStore(options={}){const memoryStorage=createMemoryStorage2();return new ApprovalStorageStore({...options,storageInstance:memoryStorage})}var ApprovalPlugin=class extends DynamicPlugin2{options;constructor(options={}){super();this.options={...ApprovalPlugin.defaultOptions,...options}}};__publicField(ApprovalPlugin,"defaultOptions",{namespace:"approval",mode:"recheck",enableAudit:true,maxDelegationDepth:3,cleanupIntervalSeconds:60});__publicField(ApprovalPlugin,"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(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(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:ProviderScope4.CONTEXT,inject:()=>[ApprovalStoreToken,FRONTMCP_CONTEXT,ScopeEntry2],useFactory:(store,ctx,scope)=>{const{sessionId,userId}=resolveApprovalIdentity(ctx);const requirementOf=toolId=>{const tool=scope.tools.getTools(true).find(entry=>entry.fullName===toolId);if(!tool)return void 0;const approval=tool.metadata.approval;return resolveApprovalRequirement(approval)};return createApprovalService(store,sessionId,userId,requirementOf)}});return providers});ApprovalPlugin=__decorateClass([Plugin2({name:"approval",description:"Tool authorization workflow with PKCE webhook security",plugins:[ApprovalCheckPlugin],contextExtensions:[{property:"approval",token:ApprovalServiceToken,errorMessage:"ApprovalPlugin is not installed. Add ApprovalPlugin.init() to your plugins array."}]})],ApprovalPlugin);var installed=false;function installApprovalContextExtension(){if(installed)return;const{ExecutionContextBase}=__require("@frontmcp/sdk");Object.defineProperty(ExecutionContextBase.prototype,"approval",{get:function(){return this.get(ApprovalServiceToken)},configurable:true,enumerable:false});installed=true}export{ApprovalCheckPlugin,ApprovalError,ApprovalExpiredError,ApprovalOperationError,ApprovalPlugin,ApprovalPlugin as ApprovalPluginClass,ApprovalRequiredError,ApprovalScope,ApprovalScopeNotAllowedError,ApprovalService,ApprovalServiceToken,ApprovalState,ApprovalStorageStore,ApprovalStoreToken,ChallengeService,ChallengeServiceToken,ChallengeValidationError,adminGrantor,adminRevoker,agentGrantor,apiGrantor,createApprovalMemoryStore,createApprovalService,createMemoryChallengeService,customGrantor,expiryRevoker,installApprovalContextExtension,isApiGrantor,isAutoGrantor,isDelegatedGrantor,isGrantorSource,isHumanGrantor,normalizeGrantor,normalizeRevoker,oauthGrantor,policyGrantor,policyRevoker,sessionEndRevoker,systemGrantor,testGrantor,userGrantor,userRevoker};
4
+ var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __require=(x=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(x,{get:(a,b)=>(typeof require!=="undefined"?require:a)[b]}):x)(function(x){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);import{DynamicPlugin as DynamicPlugin2,FRONTMCP_CONTEXT,Plugin as Plugin2,ProviderRegistry,ProviderScope as ProviderScope4,ScopeEntry as ScopeEntry2,storeProvider}from"@frontmcp/sdk";import{randomUUID}from"@frontmcp/utils";var UNIDENTIFIED_SESSION_PREFIX="unidentified:";function isUnidentifiedSession(sessionId){return sessionId.startsWith(UNIDENTIFIED_SESSION_PREFIX)}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function resolveApprovalIdentity(ctx){const extra=ctx?.authInfo?.extra;const userId=nonEmptyString(extra?.["userId"])??nonEmptyString(extra?.["sub"])??nonEmptyString(ctx?.authInfo?.clientId);const sessionId=nonEmptyString(ctx?.verifiedSessionId);if(sessionId){return{sessionId,userId}}return{sessionId:userId?`stateless-user:${userId}`:`${UNIDENTIFIED_SESSION_PREFIX}${randomUUID()}`,userId}}import{isProduction}from"@frontmcp/utils";var ApprovalScope=(ApprovalScope2=>{ApprovalScope2["SESSION"]="session";ApprovalScope2["USER"]="user";ApprovalScope2["TIME_LIMITED"]="time_limited";ApprovalScope2["TOOL_SPECIFIC"]="tool_specific";ApprovalScope2["CONTEXT_SPECIFIC"]="context_specific";return ApprovalScope2})(ApprovalScope||{});var ApprovalState=(ApprovalState2=>{ApprovalState2["PENDING"]="pending";ApprovalState2["APPROVED"]="approved";ApprovalState2["DENIED"]="denied";ApprovalState2["EXPIRED"]="expired";return ApprovalState2})(ApprovalState||{});import{z}from"@frontmcp/lazy-zod";var approvalScopeSchema=z.nativeEnum(ApprovalScope);var approvalStateSchema=z.nativeEnum(ApprovalState);var approvalMethodSchema=z.enum(["interactive","implicit","delegation","batch","api"]);var approvalSourceTypeSchema=z.string().min(1);var revocationMethodSchema=z.enum(["interactive","implicit","policy","expiry"]);var approvalCategorySchema=z.enum(["read","write","delete","execute","admin"]);var riskLevelSchema=z.enum(["low","medium","high","critical"]);var approvalContextSchema=z.object({type:z.string().min(1),identifier:z.string().min(1),metadata:z.record(z.string(),z.unknown()).optional()});var MAX_DELEGATION_CHAIN_LINKS=64;var delegationLinkSchema=z.object({delegatorId:z.string().min(1),delegateId:z.string().min(1),purpose:z.string().optional()});var delegationContextSchema=z.object({delegatorId:z.string().min(1),delegateId:z.string().min(1),purpose:z.string().optional(),constraints:z.record(z.string(),z.unknown()).optional(),chain:z.array(delegationLinkSchema).max(MAX_DELEGATION_CHAIN_LINKS).optional()});var approvalGrantorSchema=z.object({source:approvalSourceTypeSchema,identifier:z.string().optional(),displayName:z.string().optional(),method:approvalMethodSchema.optional(),origin:z.string().optional(),delegationContext:delegationContextSchema.optional()});var approvalRevokerSchema=z.object({source:z.string().min(1),identifier:z.string().optional(),displayName:z.string().optional(),method:revocationMethodSchema.optional()});var approvalRecordSchema=z.object({toolId:z.string().min(1),state:approvalStateSchema,scope:approvalScopeSchema,grantedAt:z.number(),expiresAt:z.number().optional(),ttlMs:z.number().optional(),sessionId:z.string().optional(),userId:z.string().optional(),context:approvalContextSchema.optional(),grantedBy:approvalGrantorSchema,approvalChain:z.array(approvalGrantorSchema).optional(),reason:z.string().optional(),metadata:z.record(z.string(),z.unknown()).optional(),revokedAt:z.number().optional(),revokedBy:approvalRevokerSchema.optional(),revocationReason:z.string().optional()});var toolApprovalRequirementSchema=z.object({required:z.boolean().optional(),defaultScope:approvalScopeSchema.optional(),allowedScopes:z.array(approvalScopeSchema).optional(),maxTtlMs:z.number().positive().optional(),alwaysPrompt:z.boolean().optional(),skipApproval:z.boolean().optional(),approvalMessage:z.string().optional(),category:approvalCategorySchema.optional(),riskLevel:riskLevelSchema.optional(),preApprovedContexts:z.array(approvalContextSchema).optional()});function userGrantor(userId,displayName,options){return{source:"user",identifier:userId,displayName,method:options?.method??"interactive",origin:options?.origin}}function policyGrantor(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"implicit"}}function adminGrantor(adminId,displayName,options){return{source:"admin",identifier:adminId,displayName,method:options?.method??"interactive",origin:options?.origin}}function systemGrantor(systemId="system"){return{source:"system",identifier:systemId,method:"implicit"}}function agentGrantor(agentId,delegationContext,displayName){return{source:"agent",identifier:agentId,displayName,method:"delegation",delegationContext}}function apiGrantor(apiKeyPrefix,serviceName){return{source:"api",identifier:apiKeyPrefix,displayName:serviceName,method:"api",origin:"api"}}function oauthGrantor(tokenId,provider){return{source:"oauth",identifier:tokenId,displayName:provider,method:"api",origin:"oauth"}}function testGrantor(){return{source:"test",identifier:"test",method:"implicit"}}function customGrantor(source,identifier,options){return{source,identifier,displayName:options?.displayName,method:options?.method,origin:options?.origin,delegationContext:options?.delegationContext}}function userRevoker(userId,displayName){return{source:"user",identifier:userId,displayName,method:"interactive"}}function adminRevoker(adminId,displayName){return{source:"admin",identifier:adminId,displayName,method:"interactive"}}function expiryRevoker(){return{source:"expiry",method:"expiry"}}function sessionEndRevoker(sessionId){return{source:"session_end",identifier:sessionId,method:"implicit"}}function policyRevoker(policyId,policyName){return{source:"policy",identifier:policyId,displayName:policyName,method:"policy"}}function normalizeGrantor(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function normalizeRevoker(input){if(!input){return{source:"user"}}if(typeof input==="string"){return{source:input}}return input}function delegationDepth(context){return(context.chain?.length??0)+1}function delegationProblem(context,maxDepth){const links=[...context.chain??[],context];if(links.length>maxDepth){return`the delegation chain is ${links.length} deep, and maxDelegationDepth is ${maxDepth}`}const parties=new Set([links[0].delegatorId]);for(let index=0;index<links.length;index++){const link=links[index];if(index>0&&link.delegatorId!==links[index-1].delegateId){return`the delegation chain is broken: ${link.delegatorId} was not delegated to by ${links[index-1].delegatorId}`}if(parties.has(link.delegateId))return`the delegation chain names ${link.delegateId} twice`;parties.add(link.delegateId)}return void 0}function grantorDelegationProblem(grantor,maxDepth){return grantor.delegationContext?delegationProblem(grantor.delegationContext,maxDepth):void 0}function extendDelegation(context,delegateId,options={}){const{delegatorId,delegateId:delegate,purpose}=context;return{delegatorId:delegate,delegateId,...options,chain:[...context.chain??[],{delegatorId,delegateId:delegate,...purpose?{purpose}:{}}]}}function isGrantorSource(grantor,source){return grantor.source===source}function isHumanGrantor(grantor){return grantor.source==="user"||grantor.source==="admin"}function isAutoGrantor(grantor){return grantor.source==="policy"||grantor.source==="system"||grantor.source==="test"}function isDelegatedGrantor(grantor){return grantor.source==="agent"&&!!grantor.delegationContext}function isApiGrantor(grantor){return grantor.source==="api"||grantor.source==="oauth"}import{InternalMcpError,PublicMcpError}from"@frontmcp/sdk";var ApprovalConfigurationError=class extends InternalMcpError{name="ApprovalConfigurationError";constructor(message){super(message,"APPROVAL_CONFIGURATION")}};var ApprovalError=class extends PublicMcpError{constructor(message,code="APPROVAL_REQUIRED",statusCode=403){super(message,code,statusCode);this.name="ApprovalError"}};var ApprovalRequiredError=class extends ApprovalError{constructor(details){super(details.message);this.details=details;this.name="ApprovalRequiredError"}details;toJsonRpcError(){return{code:-32600,message:this.details.message,data:{type:"approval_required",toolId:this.details.toolId,state:this.details.state,options:this.details.approvalOptions}}}};var ApprovalOperationError=class extends ApprovalError{constructor(operation,reason){super(`Approval ${operation} failed: ${reason}`,"APPROVAL_OPERATION_FAILED",400);this.operation=operation;this.reason=reason;this.name="ApprovalOperationError"}operation;reason;toJsonRpcError(){return{code:-32603,message:"Approval operation failed",data:{type:"approval_operation_error",operation:this.operation}}}};var ApprovalScopeNotAllowedError=class extends ApprovalError{constructor(requestedScope,allowedScopes){super(`Approval scope '${requestedScope}' is not allowed for this tool. Allowed scopes: ${allowedScopes.join(", ")}`,"APPROVAL_SCOPE_NOT_ALLOWED",400);this.requestedScope=requestedScope;this.allowedScopes=allowedScopes;this.name="ApprovalScopeNotAllowedError"}requestedScope;allowedScopes;toJsonRpcError(){return{code:-32602,message:this.message,data:{type:"approval_scope_not_allowed",requestedScope:this.requestedScope,allowedScopes:this.allowedScopes}}}};var ApprovalExpiredError=class extends ApprovalError{constructor(toolId,expiredAt){super(`Approval for tool '${toolId}' expired at ${new Date(expiredAt).toISOString()}`,"APPROVAL_EXPIRED",403);this.toolId=toolId;this.expiredAt=expiredAt;this.name="ApprovalExpiredError"}toolId;expiredAt;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"approval_expired",toolId:this.toolId,expiredAt:this.expiredAt}}}};var ChallengeValidationError=class extends ApprovalError{constructor(reason="invalid",message){super(message??`PKCE challenge validation failed: ${reason}`,"CHALLENGE_VALIDATION_FAILED",400);this.reason=reason;this.name="ChallengeValidationError"}reason;toJsonRpcError(){return{code:-32600,message:this.message,data:{type:"challenge_validation_error",reason:this.reason}}}};import{randomUUID as randomUUID2,verifyWebhookSignature,webhookSignatureHeaders}from"@frontmcp/utils";import{signingKeyOf,WEBHOOK_ID_HEADER,WEBHOOK_SIGNATURE_HEADER,WEBHOOK_TIMESTAMP_HEADER}from"@frontmcp/utils";function signatureHeaders(signingKey,body,now=Date.now()){const message={id:`msg_${randomUUID2()}`,timestamp:Math.floor(now/1e3),body};return webhookSignatureHeaders(message,[signingKey])}function checkSignature(signingKey,message,now=Date.now()){return verifyWebhookSignature(message,[signingKey],now)}import{Provider,ProviderScope}from"@frontmcp/sdk";import{createMemoryStorage,createNamespacedStorage,createStorage,StorageNotSupportedError}from"@frontmcp/utils";function resolveApprovalRequirement(config){if(config===true){return{required:true,defaultScope:"session"}}if(config===false||config===void 0){return{required:false}}return{...config,required:config.required??true,defaultScope:config.defaultScope??"session"}}function effectiveExpiresAt(record,requirement){const capped=requirement.maxTtlMs!==void 0?record.grantedAt+requirement.maxTtlMs:void 0;if(record.expiresAt===void 0)return capped;return capped===void 0?record.expiresAt:Math.min(record.expiresAt,capped)}function isApprovalExpired(record,requirement,now){const expiresAt=effectiveExpiresAt(record,requirement);return expiresAt!==void 0&&now>expiresAt}function isApprovalUsable(record,requirement,now){if(record.state!=="approved")return false;if(requirement.allowedScopes?.length&&!requirement.allowedScopes.includes(record.scope))return false;return!isApprovalExpired(record,requirement,now)}function assertValidTtl(ttlMs){if(ttlMs===void 0)return;if(!Number.isFinite(ttlMs)||ttlMs<=0){throw new ApprovalOperationError("grant",`ttlMs must be a positive number of milliseconds, got ${ttlMs}`)}}function checkGrantAgainstPolicy(toolId,scope,ttlMs,requirement){assertValidTtl(ttlMs);if(!requirement)return ttlMs;if(requirement.allowedScopes?.length&&!requirement.allowedScopes.includes(scope)){throw new ApprovalScopeNotAllowedError(scope,requirement.allowedScopes)}const{maxTtlMs}=requirement;if(maxTtlMs===void 0)return ttlMs;if(ttlMs===void 0)return maxTtlMs;if(ttlMs>maxTtlMs){throw new ApprovalOperationError("grant",`ttlMs ${ttlMs} exceeds the maximum of ${maxTtlMs} ms that tool "${toolId}" allows`)}return ttlMs}function auditFieldsOf(record){return{toolId:record.toolId,scope:record.scope,userId:record.userId,context:record.context?{type:record.context.type,identifier:record.context.identifier}:void 0,grantedBy:record.grantedBy,reason:record.reason,expiresAt:record.expiresAt}}var LoggerAuditSink=class{constructor(logger){this.logger=logger}logger;record(event){const fields=Object.fromEntries(Object.entries(event).filter(([,value])=>value!==void 0));this.logger.info(event.toolId?`${event.type} ${event.toolId}`:event.type,fields)}};function escapePattern(str){return str.replace(/[*?[\]\\]/g,"\\$&")}function isSameRecord(a,b){return a.toolId===b.toolId&&a.state===b.state&&a.scope===b.scope&&a.grantedAt===b.grantedAt&&a.sessionId===b.sessionId&&a.userId===b.userId&&a.context?.type===b.context?.type&&a.context?.identifier===b.context?.identifier}var REVOCATION_RETENTION_SECONDS=24*60*60;var TIME_LIMITED_KEY_SEGMENT=`scope:${"time_limited"}`;var DEFAULT_MAX_DELEGATION_DEPTH=3;var ApprovalStorageStore=class{storage;revocationStorage;options;cleanupInterval;initialized=false;ownedStorage=false;constructor(options={}){this.options={storage:options.storage??{type:"auto"},storageInstance:options.storageInstance,namespace:options.namespace??"approval",cleanupIntervalSeconds:options.cleanupIntervalSeconds??60,maxDelegationDepth:options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH,audit:options.audit}}async initialize(){if(this.initialized){return}if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await createStorage(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}if(this.options.cleanupIntervalSeconds>0){this.cleanupInterval=setInterval(()=>{void this.clearExpiredApprovals()},this.options.cleanupIntervalSeconds*1e3);this.cleanupInterval.unref?.()}this.initialized=true}get revocations(){this.revocationStorage??=createNamespacedStorage(this.storage.root,`${this.storage.prefix.replace(/:$/,"")}-revoked`);return this.revocationStorage}ensureInitialized(){if(!this.initialized){throw new Error("ApprovalStorageStore not initialized. Call initialize() first.")}}buildKey(toolId,sessionId,userId,context){const parts=[toolId];if(sessionId)parts.push(`session:${sessionId}`);if(userId)parts.push(`user:${userId}`);if(context)parts.push(`ctx:${context.type}:${context.identifier}`);return parts.join(":")}timeLimitedKey(toolId,sessionId,userId){return`${this.buildKey(toolId,sessionId,userId)}:${TIME_LIMITED_KEY_SEGMENT}`}recordKey(options){const{toolId,scope,sessionId,userId,context}=options;if(scope==="time_limited"&&!context&&!(sessionId&&userId)){return this.timeLimitedKey(toolId,sessionId,userId)}return this.buildKey(toolId,sessionId,userId,context)}parseRecord(value){if(!value)return void 0;try{const parsed=JSON.parse(value);const result=approvalRecordSchema.safeParse(parsed);if(!result.success){return void 0}return result.data}catch{return void 0}}isExpired(approval){return approval.expiresAt!==void 0&&Date.now()>approval.expiresAt}isOverDelegated(record){return record.state==="approved"&&grantorDelegationProblem(record.grantedBy,this.options.maxDelegationDepth)!==void 0}callerKeys(toolId,sessionId,userId,context){const keys=[this.buildKey(toolId,sessionId),this.timeLimitedKey(toolId,sessionId)];if(userId){keys.push(this.buildKey(toolId,void 0,userId),this.timeLimitedKey(toolId,void 0,userId),this.buildKey(toolId,sessionId,userId))}if(context){keys.push(this.buildKey(toolId,sessionId,void 0,context));if(userId)keys.push(this.buildKey(toolId,sessionId,userId,context))}return[...new Set(keys)]}async getApprovals(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const key of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.storage.get(key));if(record&&record.toolId===toolId&&!this.isExpired(record)&&!this.isOverDelegated(record)){records.push(record)}}return records}async getApproval(toolId,sessionId,userId,context){const records=await this.getApprovals(toolId,sessionId,userId,context);return records.find(record=>record.state==="denied")??records[0]}async queryApprovals(query){this.ensureInitialized();const results=[];const pattern=query.toolId?`${escapePattern(query.toolId)}:*`:"*";const keys=await this.storage.keys(pattern);const values=await this.storage.mget(keys);for(const value of values){const approval=this.parseRecord(value);if(!approval)continue;if(!query.includeExpired&&this.isExpired(approval)){continue}if(query.toolId&&approval.toolId!==query.toolId)continue;if(query.toolIds&&!query.toolIds.includes(approval.toolId))continue;if(query.scope&&approval.scope!==query.scope)continue;if(query.scopes&&!query.scopes.includes(approval.scope))continue;if(query.state&&approval.state!==query.state)continue;if(query.states&&!query.states.includes(approval.state))continue;if(query.sessionId&&approval.sessionId!==query.sessionId)continue;if(query.userId&&approval.userId!==query.userId)continue;if(query.context){if(!approval.context||approval.context.type!==query.context.type||approval.context.identifier!==query.context.identifier){continue}}results.push(approval)}return results}async grantApproval(options){return this.writeRecord(options,"approved")}async denyApproval(options){return this.writeRecord(options,"denied")}async writeRecord(options,state){this.ensureInitialized();assertValidTtl(options.ttlMs);if(options.scope==="time_limited"&&options.ttlMs===void 0){throw new ApprovalOperationError("grant","a time-limited approval needs ttlMs")}const now=Date.now();const expiresAt=options.ttlMs!==void 0?now+options.ttlMs:void 0;const grantedBy=normalizeGrantor(options.grantedBy);const delegationProblem2=state==="approved"&&grantorDelegationProblem(grantedBy,this.options.maxDelegationDepth);if(delegationProblem2)throw new ApprovalOperationError("grant",delegationProblem2);const record={toolId:options.toolId,state,scope:options.scope,grantedAt:now,expiresAt,ttlMs:options.ttlMs,sessionId:options.sessionId,userId:options.userId,context:options.context,grantedBy,reason:options.reason,metadata:options.metadata};const key=this.recordKey(options);const ttlSeconds=options.ttlMs!==void 0?Math.ceil(options.ttlMs/1e3):void 0;await this.storage.set(key,JSON.stringify(record),{ttlSeconds});this.options.audit?.record({type:state==="denied"?"approval.denied":"approval.granted",...auditFieldsOf(record)});return record}async revokeApproval(options){this.ensureInitialized();const{toolId,sessionId,userId,context}=options;if(!sessionId&&!userId&&!context){return false}const keys=await this.storage.keys(`${escapePattern(toolId)}:*`);const values=await this.storage.mget(keys);const keysToDelete=[];const revoked=new Map;for(let i=0;i<keys.length;i++){const record=this.parseRecord(values[i]);if(!record||record.toolId!==toolId||record.state==="denied")continue;const matches=keysToDelete.length;if(context){const sameSession=sessionId!==void 0&&record.sessionId===sessionId;if(record.context?.type===context.type&&record.context.identifier===context.identifier&&(!sessionId||sameSession)&&(!userId||record.userId===userId||sameSession&&record.userId===void 0)){keysToDelete.push(keys[i])}}else if(sessionId&&record.sessionId===sessionId||userId&&record.userId===userId){keysToDelete.push(keys[i])}if(keysToDelete.length>matches)revoked.set(keys[i],record)}if(keysToDelete.length===0){return false}const revokedAt=Date.now();const revokedBy=normalizeRevoker(options.revokedBy);for(const[key,record]of revoked){const entry={...record,revokedAt,revokedBy,revocationReason:options.reason};await this.revocations.set(key,JSON.stringify(entry),{ttlSeconds:REVOCATION_RETENTION_SECONDS})}await this.storage.mdelete(keysToDelete);for(const record of revoked.values()){this.options.audit?.record({type:"approval.revoked",...auditFieldsOf(record),revokedBy,reason:options.reason})}return true}async consumeApproval(record,sessionId,userId,context){this.ensureInitialized();for(const key of this.callerKeys(record.toolId,sessionId,userId,context)){const storedValue=await this.storage.get(key);const stored=this.parseRecord(storedValue);if(storedValue!==null&&stored&&isSameRecord(stored,record)){return this.deleteIfUnchanged(key,storedValue)}}return false}async deleteIfUnchanged(key,storedValue){try{return await this.storage.deleteIfEquals(key,storedValue)}catch(error){if(!(error instanceof StorageNotSupportedError))throw error;return this.storage.delete(key)}}async getRevocations(toolId,sessionId,userId,context){this.ensureInitialized();const records=[];for(const key of this.callerKeys(toolId,sessionId,userId,context)){const record=this.parseRecord(await this.revocations.get(key));if(record&&record.toolId===toolId)records.push(record)}return records.sort((a,b)=>(a.revokedAt??0)-(b.revokedAt??0))}async isApproved(toolId,sessionId,userId,context){const approval=await this.getApproval(toolId,sessionId,userId,context);return approval?.state==="approved"}async clearSessionApprovals(sessionId){this.ensureInitialized();const escapedSessionId=escapePattern(sessionId);const keys=[...new Set([...await this.storage.keys(`*:session:${escapedSessionId}`),...await this.storage.keys(`*:session:${escapedSessionId}:*`)])];if(keys.length===0){return 0}const count=await this.storage.mdelete(keys);this.options.audit?.record({type:"approval.revoked",count,reason:"session approvals cleared"});return count}async clearExpiredApprovals(){this.ensureInitialized();const now=Date.now();const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);const keysToDelete=[];const expired=[];for(let i=0;i<keys.length;i++){const approval=this.parseRecord(values[i]);if(approval&&approval.expiresAt&&approval.expiresAt<=now){keysToDelete.push(keys[i]);expired.push(approval)}}if(keysToDelete.length===0)return 0;const deleted=await this.storage.mdelete(keysToDelete);for(const record of expired)this.options.audit?.record({type:"approval.expired",...auditFieldsOf(record)});return deleted}async getStats(){this.ensureInitialized();const byScope={["session"]:0,["user"]:0,["time_limited"]:0,["tool_specific"]:0,["context_specific"]:0};const byState={["pending"]:0,["approved"]:0,["denied"]:0,["expired"]:0};const keys=await this.storage.keys("*");const values=await this.storage.mget(keys);let total=0;for(const value of values){const approval=this.parseRecord(value);if(approval){total++;byScope[approval.scope]++;byState[approval.state]++}}return{totalApprovals:total,byScope,byState}}async close(){if(this.cleanupInterval){clearInterval(this.cleanupInterval);this.cleanupInterval=void 0}if(this.ownedStorage&&this.storage){await this.storage.root.disconnect()}this.revocationStorage=void 0;this.initialized=false}};ApprovalStorageStore=__decorateClass([Provider({name:"provider:approval:store:storage",description:"Storage-backed approval store (supports Memory, Redis, Vercel KV, Upstash)",scope:ProviderScope.GLOBAL})],ApprovalStorageStore);function createApprovalMemoryStore(options={}){const memoryStorage=createMemoryStorage();return new ApprovalStorageStore({...options,storageInstance:memoryStorage})}var DEFAULT_CALLBACK_PATH="/approval/callback";var DEFAULT_RECHECK_INTERVAL_MS=2e3;var DEFAULT_RECHECK_MAX_ATTEMPTS=5;var MAX_RECHECK_WAIT_MS=12e4;var MIN_SECRET_BYTES=24;var LOOPBACK_HOSTNAMES=new Set(["localhost","127.0.0.1","[::1]"]);var CALLBACK_PATH_PATTERN=/^(\/[A-Za-z0-9._~-]+)+$/;function refuse(message){throw new ApprovalConfigurationError(`ApprovalPlugin ${message}`)}function setOptions(values){return Object.entries(values).filter(([,value])=>value!==void 0).map(([name2])=>name2)}function checkOutboundUrl(option,url){let parsed;try{parsed=new URL(url)}catch{return refuse(`\`${option}\` is not a URL`)}if(parsed.username||parsed.password){refuse(`\`${option}\` must not carry credentials; use the auth options instead`)}const loopbackInDevelopment=parsed.protocol==="http:"&&LOOPBACK_HOSTNAMES.has(parsed.hostname)&&!isProduction();if(parsed.protocol!=="https:"&&!loopbackInDevelopment){refuse(`\`${option}\` must be an https:// URL (http://localhost is accepted when NODE_ENV is not production), got ${parsed.protocol}//${parsed.host}`)}return parsed.toString()}function checkSecret(option,secret){if(secret===void 0||secret.trim()===""){return refuse(`needs \`${option}\` to sign its requests and verify callbacks`)}let signingKey;try{signingKey=signingKeyOf(secret)}catch{return refuse(`\`${option}\` starts with whsec_ but the rest is not base64`)}if(signingKey.length<MIN_SECRET_BYTES){refuse(`\`${option}\` must be at least ${MIN_SECRET_BYTES} bytes (32 characters or more is recommended)`)}return signingKey}function checkWholeNumber(option,value,min,max){if(!Number.isInteger(value)||value<min||value>max){refuse(`\`${option}\` must be a whole number from ${min} to ${max}, got ${value}`)}return value}function resolveWebhook(options){const{url,secret,includeJwt,callbackPath,challengeTtl}=options.webhook??{};const external=setOptions({url,secret,includeJwt,callbackPath}).map(name2=>`\`webhook.${name2}\``);if(external.length===0)return void 0;if(options.mode!=="webhook")refuse(`${external.join(", ")} need \`mode: 'webhook'\``);if(url===void 0)refuse(`${external.join(", ")} need \`webhook.url\``);const path=callbackPath??DEFAULT_CALLBACK_PATH;if(!CALLBACK_PATH_PATTERN.test(path)||path.length>256){refuse(`\`webhook.callbackPath\` must be a path such as ${DEFAULT_CALLBACK_PATH}, got ${JSON.stringify(path)}`)}return{url:checkOutboundUrl("webhook.url",url),signingKey:checkSecret("webhook.secret",secret),includeJwt:includeJwt===true,callbackPath:path,challengeTtlSeconds:challengeTtl??300}}function resolveRecheck(options){if(options.recheck===void 0)return void 0;const{url,auth="none",token,headers,secret,interval,maxAttempts}=options.recheck;if(options.mode==="webhook")refuse("`recheck` needs `mode: 'recheck'`");if(url===void 0){const others=setOptions({auth:options.recheck.auth,token,headers,secret,interval,maxAttempts});refuse(`${others.map(name2=>`\`recheck.${name2}\``).join(", ")||"`recheck`"} need \`recheck.url\``)}if(!["jwt","bearer","none","custom"].includes(auth)){refuse(`\`recheck.auth\` must be 'jwt', 'bearer', 'none' or 'custom', got ${JSON.stringify(auth)}`)}if(auth==="bearer"&&!token)refuse("`recheck.auth: 'bearer'` needs `recheck.token`");if(auth!=="bearer"&&token!==void 0)refuse("`recheck.token` is only sent with `recheck.auth: 'bearer'`");if(auth==="custom"&&typeof headers!=="function")refuse("`recheck.auth: 'custom'` needs a `recheck.headers` function");if(auth!=="custom"&&headers!==void 0)refuse("`recheck.headers` is only used with `recheck.auth: 'custom'`");const intervalMs=checkWholeNumber("recheck.interval",interval??DEFAULT_RECHECK_INTERVAL_MS,100,6e4);const attempts=checkWholeNumber("recheck.maxAttempts",maxAttempts??DEFAULT_RECHECK_MAX_ATTEMPTS,1,60);if(intervalMs*(attempts-1)>MAX_RECHECK_WAIT_MS){refuse(`would keep a call waiting ${intervalMs*(attempts-1)} ms: \`recheck.interval\` \xD7 (\`recheck.maxAttempts\` \u2212 1) must be ${MAX_RECHECK_WAIT_MS} ms or less`)}return{url:checkOutboundUrl("recheck.url",url),auth,token,headers,signingKey:secret===void 0?void 0:checkSecret("recheck.secret",secret),intervalMs,maxAttempts:attempts}}function resolveExternalApproval(options){return{webhook:resolveWebhook(options),recheck:resolveRecheck(options)}}function resolveMaxDelegationDepth(options){const depth=options.maxDelegationDepth??DEFAULT_MAX_DELEGATION_DEPTH;return checkWholeNumber("maxDelegationDepth",depth,0,MAX_DELEGATION_CHAIN_LINKS)}var ApprovalStoreToken=Symbol.for("plugin:approval:store");var ApprovalServiceToken=Symbol.for("plugin:approval:service");var ChallengeServiceToken=Symbol.for("plugin:approval:challenge-service");var ExternalApproverToken=Symbol.for("plugin:approval:external-approver");var ApprovalAuditToken=Symbol.for("plugin:approval:audit");import"reflect-metadata";import{z as z2}from"@frontmcp/lazy-zod";import{enforceGlobalRateLimit,enforceIpFilter,Flow,FlowBase,FlowHooksOf,httpInputSchema,HttpJsonSchema,normalizeEntryPrefix,normalizeScopeBase}from"@frontmcp/sdk";var plan={pre:["checkIpFilter","acquireQuota"],execute:["handleCallback"]};var approvalCallbackStateSchema=z2.object({});var callbackRoutes=new WeakMap;var name="approval:webhook-callback";var{Stage}=FlowHooksOf(name);var ApprovalCallbackFlow=class extends FlowBase{static canActivate(request,scope){return callbackRoutes.get(scope)?.has(request.path)??false}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async handleCallback(){const request=this.rawInput.request;const handler=callbackRoutes.get(this.scope)?.get(request.path);if(!handler)return this.next();this.respond(await handler.handleCallback({headers:request.headers,bodyBytes:request.bodyBytes}))}};__decorateClass([Stage("checkIpFilter")],ApprovalCallbackFlow.prototype,"checkIpFilter",1);__decorateClass([Stage("acquireQuota")],ApprovalCallbackFlow.prototype,"acquireQuota",1);__decorateClass([Stage("handleCallback")],ApprovalCallbackFlow.prototype,"handleCallback",1);ApprovalCallbackFlow=__decorateClass([Flow({name,plan,access:"public",inputSchema:httpInputSchema,outputSchema:HttpJsonSchema,middleware:{method:"POST"}})],ApprovalCallbackFlow);function mcpPaths(scope){const base=`${normalizeEntryPrefix(scope.entryPath)}${normalizeScopeBase(scope.routeBase)}`;return[base||"/",`${base}/sse`,`${base}/message`,`${base}/server-card`]}async function serveApprovalCallback(scope,path,handler){if(mcpPaths(scope).includes(path)||/^\/(oauth|\.well-known)(\/|$)/.test(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is a path the server reserves`)}let routes=callbackRoutes.get(scope);const firstRoute=!routes;routes??=new Map;if(routes.has(path)){throw new ApprovalConfigurationError(`ApprovalPlugin \`webhook.callbackPath\` ${path} is served by another ApprovalPlugin; give each its own`)}routes.set(path,handler);callbackRoutes.set(scope,routes);if(firstRoute)await scope.registryFlows(ApprovalCallbackFlow)}import{sha256Hex}from"@frontmcp/utils";function pendingRequestKey(subject){return sha256Hex(JSON.stringify([subject.toolId,subject.sessionId,subject.userId??null]))}function grantTarget(scope,subject){const{sessionId,userId,context}=subject;switch(scope){case"session":return{sessionId};case"user":return userId?{userId}:void 0;case"time_limited":return{sessionId,userId};case"context_specific":return context?{context,sessionId,userId}:void 0;default:return void 0}}var ApprovalDecisionRecorder=class{constructor(store,requirementOf,logger){this.store=store;this.requirementOf=requirementOf;this.logger=logger}store;requirementOf;logger;async approve(subject,decision,origin){const requirement=this.requirementOf(subject.toolId);const scope=decision.scope??requirement?.defaultScope??"session";const target=grantTarget(scope,subject);if(!target){this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: no ${scope} to grant it to`);return false}try{const ttlMs=checkGrantAgainstPolicy(subject.toolId,scope,decision.ttlMs,requirement);await this.store.grantApproval({toolId:subject.toolId,scope,ttlMs,...target,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason});return true}catch(error){if(!(error instanceof ApprovalError))throw error;this.logger.warn(`ApprovalPlugin: the ${origin} approval of ${subject.toolId} was not recorded: ${error.message}`);return false}}async deny(subject,decision,ttlMs,origin){if(!this.store.denyApproval){this.logger.warn(`ApprovalPlugin: the ${origin} denial of ${subject.toolId} was not recorded: the store keeps no denials`);return}await this.store.denyApproval({toolId:subject.toolId,scope:"session",ttlMs,sessionId:subject.sessionId,userId:subject.userId,grantedBy:{...decision.decidedBy??{source:"api",method:"api"},origin},reason:decision.reason})}};import{z as z3}from"@frontmcp/lazy-zod";import{isRedirectResponse}from"@frontmcp/utils";var OUTBOUND_TIMEOUT_MS=1e4;var OUTBOUND_MAX_RESPONSE_BYTES=64*1024;var OutboundRequestError=class extends Error{name="OutboundRequestError"};async function readBounded(response){const declaredLength=Number(response.headers.get("content-length")??0);if(declaredLength>OUTBOUND_MAX_RESPONSE_BYTES){await response.body?.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}if(!response.body)return"";const reader=response.body.getReader();const chunks=[];let received2=0;for(;;){const{done,value}=await reader.read();if(done)break;received2+=value.byteLength;if(received2>OUTBOUND_MAX_RESPONSE_BYTES){await reader.cancel();throw new OutboundRequestError(`answered with more than ${OUTBOUND_MAX_RESPONSE_BYTES} bytes`)}chunks.push(value)}const bytes=new Uint8Array(received2);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.byteLength}return new TextDecoder().decode(bytes)}function failureCode(error){const cause=error?.cause;return typeof cause?.code==="string"?cause.code:error instanceof Error?error.name:"unknown error"}async function postJson(request){const timeoutMs=request.timeoutMs??OUTBOUND_TIMEOUT_MS;const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeoutMs);const cancel=()=>controller.abort();request.signal?.addEventListener("abort",cancel,{once:true});try{const response=await fetch(request.url,{method:"POST",headers:{...request.headers,"content-type":"application/json",accept:"application/json"},body:request.body,redirect:"manual",signal:controller.signal});if(isRedirectResponse(response)){await response.body?.cancel();throw new OutboundRequestError(`answered with a redirect (${response.status}), which is not followed`)}return{status:response.status,body:await readBounded(response)}}catch(error){if(error instanceof OutboundRequestError)throw error;if(request.signal?.aborted)throw new OutboundRequestError("the tool call was cancelled");if(controller.signal.aborted)throw new OutboundRequestError(`no answer within ${timeoutMs} ms`);throw new OutboundRequestError(`the request failed (${failureCode(error)})`)}finally{clearTimeout(timer);request.signal?.removeEventListener("abort",cancel)}}function originOf(url){return new URL(url).origin}var recheckAnswerSchema=z3.object({approved:z3.boolean(),pending:z3.boolean().optional(),scope:approvalScopeSchema.optional(),ttlMs:z3.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),denialReason:z3.string().max(1e3).optional()});function wait(ms,signal){if(signal?.aborted)return Promise.resolve(false);return new Promise(resolve=>{const done=completed=>{clearTimeout(timer);signal?.removeEventListener("abort",cancelled);resolve(completed)};const cancelled=()=>done(false);const timer=setTimeout(()=>done(true),ms);signal?.addEventListener("abort",cancelled,{once:true})})}var RecheckApprover=class{constructor(recheck,dependencies,logger){this.recheck=recheck;this.dependencies=dependencies;this.logger=logger}recheck;dependencies;logger;via="recheck";async requestApproval(call){for(let attempt=1;attempt<=this.recheck.maxAttempts;attempt++){if(attempt>1&&!await wait(this.recheck.intervalMs,call.signal))return"pending";let answer;try{answer=await this.poll(call,attempt)}catch(error){if(!(error instanceof OutboundRequestError))throw error;this.logger.warn(`ApprovalPlugin: polling ${originOf(this.recheck.url)} for ${call.toolId} failed: ${error.message}`);return"pending"}if(!answer)return"pending";if(answer.approved)return await this.approve(call,answer)?"approved":"pending";if(!answer.pending)return"denied"}return"pending"}async approve(call,answer){if(call.requirement.alwaysPrompt)return true;return this.dependencies.decisions.approve(call,{scope:answer.scope,ttlMs:answer.ttlMs,decidedBy:answer.grantedBy},"recheck")}async poll(call,attempt){const{requirement}=call;const request={type:"approval.status",requestId:pendingRequestKey(call),attempt,toolId:call.toolId,toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,approvalMessage:requirement.approvalMessage,requestedScope:requirement.defaultScope??"session",allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,timestamp:Date.now()};const authorization=await this.authorization(call,request);if(!authorization)return void 0;const body=JSON.stringify(request);const signing=this.recheck.signingKey?signatureHeaders(this.recheck.signingKey,body):{};const answer=await postJson({url:this.recheck.url,body,headers:{...authorization,...signing},signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);try{return recheckAnswerSchema.parse(JSON.parse(answer.body))}catch{throw new OutboundRequestError("answered with something other than { approved, pending?, scope?, ttlMs?, ... }")}}async authorization(call,request){switch(this.recheck.auth){case"jwt":if(!call.accessToken){this.logger.verbose(`ApprovalPlugin: not polling for ${call.toolId}: the call has no token to forward`);return void 0}return{authorization:`Bearer ${call.accessToken}`};case"bearer":return{authorization:`Bearer ${this.recheck.token}`};case"custom":return{...await this.recheck.headers?.(request)};default:return{}}}};import{z as z4}from"@frontmcp/lazy-zod";import{getPinnedPublicUrl,httpRespond}from"@frontmcp/sdk";var MAX_CALLBACK_BYTES=16*1024;var callbackSchema=z4.object({codeVerifier:z4.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),approved:z4.boolean(),scope:approvalScopeSchema.optional(),ttlMs:z4.number().positive().finite().optional(),grantedBy:approvalGrantorSchema.optional(),reason:z4.string().max(1e3).optional()});function refusal(status,error,description){return httpRespond.json({error,error_description:description},{status})}function headerOf(headers,name2){const value=headers[name2];return typeof value==="string"?value:void 0}function received(){return httpRespond.json({status:"received"},{status:202})}var WebhookApprover=class{constructor(webhook,dependencies,logger){this.webhook=webhook;this.dependencies=dependencies;this.logger=logger}webhook;dependencies;logger;via="webhook";get challenges(){return this.dependencies.challenges}async requestApproval(call){const pendingKey=pendingRequestKey(call);const ttlSeconds=this.webhook.challengeTtlSeconds;if(!await this.challenges.claimPendingRequest(pendingKey,ttlSeconds))return"pending";const{requirement}=call;const requestedScope=requirement.defaultScope??"session";const requestInfo={toolName:call.toolName,category:requirement.category,riskLevel:requirement.riskLevel,customMessage:requirement.approvalMessage};const{codeVerifier,codeChallenge,expiresAt}=await this.challenges.createChallenge({toolId:call.toolId,sessionId:call.sessionId,userId:call.userId,context:call.context,requestedScope,requestInfo,ttlSeconds});const publicUrl=getPinnedPublicUrl();const payload={type:"approval.requested",codeChallenge,codeVerifier,toolId:call.toolId,toolName:call.toolName,category:requestInfo.category,riskLevel:requestInfo.riskLevel,approvalMessage:requestInfo.customMessage,requestedScope,allowedScopes:requirement.allowedScopes,maxTtlMs:requirement.maxTtlMs,userId:call.userId,callbackPath:this.webhook.callbackPath,callbackUrl:publicUrl?`${publicUrl}${this.webhook.callbackPath}`:void 0,expiresAt,timestamp:Date.now(),jwt:this.webhook.includeJwt?call.accessToken:void 0};const body=JSON.stringify(payload);try{const answer=await postJson({url:this.webhook.url,body,headers:signatureHeaders(this.webhook.signingKey,body),signal:call.signal});if(answer.status<200||answer.status>=300)throw new OutboundRequestError(`answered ${answer.status}`);await this.challenges.markWebhookSent(codeChallenge)}catch(error){if(!(error instanceof OutboundRequestError))throw error;await this.challenges.deleteChallenge(codeChallenge);await this.challenges.releasePendingRequest(pendingKey);this.logger.warn(`ApprovalPlugin: the approval request for ${call.toolId} to ${originOf(this.webhook.url)} failed: ${error.message}`)}return"pending"}async handleCallback(request){const{bodyBytes}=request;if(!bodyBytes||bodyBytes.byteLength===0){return refusal(400,"invalid_request","the body must be the decision, as JSON")}if(bodyBytes.byteLength>MAX_CALLBACK_BYTES){return refusal(413,"payload_too_large",`the body must be ${MAX_CALLBACK_BYTES} bytes or less`)}const body=new TextDecoder().decode(bodyBytes);const signature=checkSignature(this.webhook.signingKey,{id:headerOf(request.headers,WEBHOOK_ID_HEADER),timestamp:headerOf(request.headers,WEBHOOK_TIMESTAMP_HEADER),signature:headerOf(request.headers,WEBHOOK_SIGNATURE_HEADER),body});if(signature!=="valid"){this.logger.warn(`ApprovalPlugin: refused an approval callback: signature ${signature}`);return refusal(401,"invalid_signature","the callback must be signed with webhook.secret, within five minutes")}let decision;try{decision=callbackSchema.parse(JSON.parse(body))}catch{return refusal(400,"invalid_request","the body must be { codeVerifier, approved, scope?, ttlMs?, grantedBy?, reason? }")}const pending=await this.challenges.consume(decision.codeVerifier);if(!pending)return received();await this.challenges.releasePendingRequest(pendingRequestKey(pending));const subject={toolId:pending.toolId,sessionId:pending.sessionId,userId:pending.userId,context:pending.context};const outcome={scope:decision.scope,ttlMs:decision.ttlMs,decidedBy:decision.grantedBy,reason:decision.reason};if(decision.approved){await this.dependencies.decisions.approve(subject,outcome,"webhook")}else{await this.dependencies.decisions.deny(subject,outcome,decision.ttlMs??this.webhook.challengeTtlSeconds*1e3,"webhook")}return received()}};import{DynamicPlugin,isEntryGatedBy,Plugin,ProviderNotAvailableError,ScopeEntry,ToolHook}from"@frontmcp/sdk";var decidedCalls=new WeakSet;var ApprovalCheckPlugin=class extends DynamicPlugin{async checkApproval(flowCtx){const{tool,toolContext}=flowCtx.state;if(!tool||!toolContext)return;const metadata=tool.metadata;const approvalConfig=resolveApprovalRequirement(metadata["approval"]);if(!approvalConfig.required){return}if(approvalConfig.skipApproval){return}if(decidedCalls.has(toolContext))return;await this.enforceApproval(flowCtx,tool,toolContext,approvalConfig,this.coveringStores(tool));decidedCalls.add(toolContext)}async enforceApproval(flowCtx,tool,toolContext,approvalConfig,stores){const callerContext=toolContext.tryGetContext?.();const{sessionId,userId}=resolveApprovalIdentity(callerContext);const currentContext=this.getCurrentContext(flowCtx);const stored=[];for(const store of stores){const records2=await this.readApprovals(store,tool.fullName,sessionId,userId,currentContext);stored.push(...records2.map(record=>({store,record})))}const records=stored.map(({record})=>record);const requested=(state,via)=>this.optional(ApprovalAuditToken)?.record({type:"approval.requested",toolId:tool.fullName,userId,context:currentContext&&{type:currentContext.type,identifier:currentContext.identifier},state,via});if(records.some(record=>record.state==="denied")){requested("denied");throw new ApprovalRequiredError({toolId:tool.fullName,state:"denied",message:`Tool "${tool.fullName}" execution denied.`})}if(!approvalConfig.alwaysPrompt&&this.isPreApprovedContext(approvalConfig,currentContext)){return}const approved=records.filter(record=>record.state==="approved");const now=Date.now();const usable=stored.filter(({record})=>isApprovalUsable(record,approvalConfig,now));if(approvalConfig.alwaysPrompt){for(const{store,record}of usable){if(await this.consumeApproval(store,record,sessionId,userId,currentContext))return}}else if(usable.length>0){return}const external=isUnidentifiedSession(sessionId)?void 0:this.optional(ExternalApproverToken);const outcome=await external?.requestApproval({toolId:tool.fullName,toolName:tool.name,sessionId,userId,context:currentContext,requirement:approvalConfig,accessToken:callerContext?.authInfo?.token,signal:toolContext.signal});const expiredApproval=approved.find(record=>isApprovalExpired(record,approvalConfig,now));const callState=outcome==="approved"||outcome==="denied"?outcome:expiredApproval?"expired":"pending";requested(callState,external?.via);if(outcome==="approved")return;if(outcome==="denied"){throw new ApprovalRequiredError({toolId:tool.fullName,state:"denied",message:`Tool "${tool.fullName}" execution denied.`})}await this.handleApprovalRequired(flowCtx,approvalConfig,expiredApproval??approved[0])}optional(token){try{return this.get(token)}catch(error){if(error instanceof ProviderNotAvailableError)return void 0;throw error}}coveringStores(tool){const stores=new Set([this.get(ApprovalStoreToken)]);let scope;try{scope=this.get(ScopeEntry)}catch{scope=void 0}if(!scope?.hooks)return[...stores];for(const hook of scope.hooks.getFlowHooks("tools:call-tool")){const gate=hook.metadata.target;if(gate instanceof ApprovalCheckPlugin&&isEntryGatedBy(scope,{tool},gate)){stores.add(gate.get(ApprovalStoreToken))}}return[...stores]}async consumeApproval(store,record,sessionId,userId,context){if(store.consumeApproval){return store.consumeApproval(record,sessionId,userId,context)}return store.revokeApproval({toolId:record.toolId,sessionId,userId,revokedBy:"system",reason:"Used by a call of an alwaysPrompt tool"})}async readApprovals(store,toolId,sessionId,userId,context){if(store.getApprovals){return store.getApprovals(toolId,sessionId,userId,context)}const record=await store.getApproval(toolId,sessionId,userId,context);return record?[record]:[]}getCurrentContext(flowCtx){const ctx=flowCtx.state.toolContext?.tryGetContext?.();const sessionContext=ctx?.authInfo?.extra?.["approvalContext"];return this.isApprovalContext(sessionContext)?sessionContext:void 0}isApprovalContext(value){return typeof value==="object"&&value!==null&&"type"in value&&"identifier"in value&&typeof value.type==="string"&&typeof value.identifier==="string"}isPreApprovedContext(config,currentContext){if(!currentContext||!config.preApprovedContexts?.length){return false}return config.preApprovedContexts.some(preApproved=>preApproved.type===currentContext.type&&preApproved.identifier===currentContext.identifier)}async handleApprovalRequired(flowCtx,config,existingApproval){const{tool}=flowCtx.state;const message=config.approvalMessage??`Tool "${tool?.fullName}" requires approval to execute. Allow?`;const isExpiredApproval=existingApproval?isApprovalExpired(existingApproval,config,Date.now()):false;throw new ApprovalRequiredError({toolId:tool?.fullName??"unknown",state:isExpiredApproval?"expired":"pending",message,approvalOptions:{allowedScopes:config.allowedScopes,defaultScope:config.defaultScope,maxTtlMs:config.maxTtlMs,category:config.category,riskLevel:config.riskLevel}})}};__decorateClass([ToolHook.Will("execute",{priority:100,appliesTo:"uncovered-apps"})],ApprovalCheckPlugin.prototype,"checkApproval",1);ApprovalCheckPlugin=__decorateClass([Plugin({name:"approval:check",description:"Checks tool approval state before execution",enforcesMetadata:["approval"]})],ApprovalCheckPlugin);import{isAnonymousSubject,Provider as Provider2,ProviderScope as ProviderScope2}from"@frontmcp/sdk";var ApprovalService=class{constructor(store,sessionId,userId,requirementOf=()=>void 0){this.store=store;this.sessionId=sessionId;this.userId=userId;this.requirementOf=requirementOf}store;sessionId;userId;requirementOf;checkGrant(toolId,scope,ttlMs){return checkGrantAgainstPolicy(toolId,scope,ttlMs,this.requirementOf(toolId))}get signedInUserId(){return this.userId&&!isAnonymousSubject(this.userId)?this.userId:void 0}defaultGrantor(){const userId=this.signedInUserId;return userId?userGrantor(userId,void 0,{method:"implicit"}):{source:"user",method:"implicit"}}defaultRevoker(){const userId=this.signedInUserId;return userId?{source:"user",identifier:userId,method:"implicit"}:{source:"user",method:"implicit"}}async isApproved(toolId,context){const requirement=this.requirementOf(toolId);if(!requirement||!this.store.getApprovals){return this.store.isApproved(toolId,this.sessionId,this.userId,context)}const records=await this.store.getApprovals(toolId,this.sessionId,this.userId,context);if(records.some(record=>record.state==="denied"))return false;const now=Date.now();return records.some(record=>isApprovalUsable(record,requirement,now))}async getApproval(toolId){return this.store.getApproval(toolId,this.sessionId,this.userId)}async getSessionApprovals(){return this.store.queryApprovals({sessionId:this.sessionId,states:["approved"],includeExpired:false})}async getUserApprovals(){if(!this.userId)return[];return this.store.queryApprovals({userId:this.userId,scope:"user",states:["approved"],includeExpired:false})}async queryApprovals(query){const records=await this.store.queryApprovals(query);return records.filter(record=>record.sessionId===this.sessionId||this.userId!==void 0&&record.userId===this.userId)}async getRevocations(toolId){return await this.store.getRevocations?.(toolId,this.sessionId,this.userId)??[]}async grantSessionApproval(toolId,options={}){const ttlMs=this.checkGrant(toolId,"session");return this.store.grantApproval({toolId,scope:"session",ttlMs,sessionId:this.sessionId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantUserApproval(toolId,options={}){if(!this.userId){throw new Error("Cannot grant user approval without userId")}const ttlMs=this.checkGrant(toolId,"user");return this.store.grantApproval({toolId,scope:"user",ttlMs,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantTimeLimitedApproval(toolId,ttlMs,options={}){this.checkGrant(toolId,"time_limited",ttlMs);return this.store.grantApproval({toolId,scope:"time_limited",ttlMs,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async grantContextApproval(toolId,context,options={}){const ttlMs=this.checkGrant(toolId,"context_specific");return this.store.grantApproval({toolId,scope:"context_specific",ttlMs,context,sessionId:this.sessionId,userId:this.userId,grantedBy:options.grantedBy??this.defaultGrantor(),reason:options.reason,metadata:options.metadata})}async revokeApproval(toolId,options={}){return this.store.revokeApproval({toolId,sessionId:this.sessionId,userId:this.userId,revokedBy:options.revokedBy??this.defaultRevoker(),reason:options.reason})}async clearSessionApprovals(){return this.store.clearSessionApprovals(this.sessionId)}};ApprovalService=__decorateClass([Provider2({name:"provider:approval:service",description:"Service for managing tool approvals",scope:ProviderScope2.CONTEXT})],ApprovalService);function createApprovalService(store,sessionId,userId,requirementOf){return new ApprovalService(store,sessionId,userId,requirementOf)}import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{createMemoryStorage as createMemoryStorage2,createStorage as createStorage2,generateCodeChallenge,generatePkcePair,randomUUID as randomUUID3,StorageNotSupportedError as StorageNotSupportedError2}from"@frontmcp/utils";var PENDING_REQUEST_PREFIX="pending:";var ChallengeService=class{storage;options;initialized=false;ownedStorage=false;constructor(options={}){this.options={storage:options.storage??{type:"auto"},storageInstance:options.storageInstance,namespace:options.namespace??"approval:challenge",defaultTtlSeconds:options.defaultTtlSeconds??300}}async initialize(){if(this.initialized)return;if(this.options.storageInstance){this.storage=this.options.storageInstance.namespace(this.options.namespace);this.ownedStorage=false}else{const rootStorage=await createStorage2(this.options.storage);this.storage=rootStorage.namespace(this.options.namespace);this.ownedStorage=true}this.initialized=true}ensureInitialized(){if(!this.initialized){throw new Error("ChallengeService not initialized. Call initialize() first.")}}async createChallenge(options){this.ensureInitialized();const{codeVerifier,codeChallenge}=generatePkcePair();const now=Date.now();const ttlSeconds=options.ttlSeconds??this.options.defaultTtlSeconds;const expiresAt=now+ttlSeconds*1e3;const record={toolId:options.toolId,sessionId:options.sessionId,userId:options.userId,context:options.context,requestedScope:options.requestedScope,requestInfo:options.requestInfo,createdAt:now,expiresAt,webhookSent:false};await this.storage.set(codeChallenge,JSON.stringify(record),{ttlSeconds});return{codeVerifier,codeChallenge,expiresAt}}async verifyAndConsume(codeVerifier){const consumed=await this.take(codeVerifier);if(!consumed){throw new ChallengeValidationError("not_found","Invalid or expired challenge")}if(Date.now()>consumed.expiresAt){throw new ChallengeValidationError("expired","Challenge expired")}return consumed}async consume(codeVerifier){const consumed=await this.take(codeVerifier);return consumed&&Date.now()<=consumed.expiresAt?consumed:void 0}async take(codeVerifier){this.ensureInitialized();const codeChallenge=generateCodeChallenge(codeVerifier);const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return void 0;if(!await this.deleteIfUnchanged(codeChallenge,recordJson))return void 0;return JSON.parse(recordJson)}async deleteIfUnchanged(key,value){try{return await this.storage.deleteIfEquals(key,value)}catch(error){if(!(error instanceof StorageNotSupportedError2))throw error;return this.storage.delete(key)}}async claimPendingRequest(key,ttlSeconds=this.options.defaultTtlSeconds){this.ensureInitialized();const claim=randomUUID3();const pendingKey=`${PENDING_REQUEST_PREFIX}${key}`;try{await this.storage.set(pendingKey,claim,{ttlSeconds,ifNotExists:true})}catch(error){if(!(error instanceof StorageNotSupportedError2))throw error;if(await this.storage.exists(pendingKey))return false;await this.storage.set(pendingKey,claim,{ttlSeconds})}return await this.storage.get(pendingKey)===claim}async releasePendingRequest(key){this.ensureInitialized();await this.storage.delete(`${PENDING_REQUEST_PREFIX}${key}`)}async markWebhookSent(codeChallenge){this.ensureInitialized();const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return false;const record=JSON.parse(recordJson);record.webhookSent=true;const remainingMs=record.expiresAt-Date.now();if(remainingMs<=0){await this.storage.delete(codeChallenge);return false}const ttlSeconds=Math.ceil(remainingMs/1e3);await this.storage.set(codeChallenge,JSON.stringify(record),{ttlSeconds});return true}async getChallenge(codeChallenge){this.ensureInitialized();const recordJson=await this.storage.get(codeChallenge);if(!recordJson)return null;const record=JSON.parse(recordJson);if(Date.now()>record.expiresAt){await this.storage.delete(codeChallenge);return null}return record}async deleteChallenge(codeChallenge){this.ensureInitialized();const exists=await this.storage.exists(codeChallenge);if(exists){await this.storage.delete(codeChallenge);return true}return false}async close(){if(this.ownedStorage&&this.storage){await this.storage.root.disconnect()}this.initialized=false}};ChallengeService=__decorateClass([Provider3({name:"provider:approval:challenge-service",description:"PKCE challenge service for webhook approval flows",scope:ProviderScope3.GLOBAL})],ChallengeService);function createMemoryChallengeService(options={}){const memoryStorage=createMemoryStorage2();return new ChallengeService({...options,storageInstance:memoryStorage})}function toolRequirementLookup(scope){return toolId=>{const tool=scope.tools.getTools(true).find(entry=>entry.fullName===toolId);if(!tool)return void 0;const approval=tool.metadata.approval;return resolveApprovalRequirement(approval)}}function externalApproverProvider(external){const{webhook,recheck}=external;if(!webhook&&!recheck)return void 0;return{name:"approval:external-approver",provide:ExternalApproverToken,inject:()=>[ProviderRegistry,ScopeEntry2],useFactory:async(providers,scope)=>{const logger=scope.logger.child("ApprovalPlugin");const requirementOf=toolRequirementLookup(scope);const dependencies={get challenges(){return providers.get(ChallengeServiceToken)},get decisions(){return new ApprovalDecisionRecorder(providers.get(ApprovalStoreToken),requirementOf,logger)}};if(!webhook)return new RecheckApprover(recheck,dependencies,logger);const approver=new WebhookApprover(webhook,dependencies,logger);await serveApprovalCallback(scope,webhook.callbackPath,approver);return approver}}}var ApprovalPlugin=class extends DynamicPlugin2{options;constructor(options={}){super();this.options={...ApprovalPlugin.defaultOptions,...options}}};__publicField(ApprovalPlugin,"defaultOptions",{namespace:"approval",mode:"recheck",enableAudit:false,maxDelegationDepth:DEFAULT_MAX_DELEGATION_DEPTH,cleanupIntervalSeconds:60});__publicField(ApprovalPlugin,"browserStores",({storage,storageInstance})=>{const type=storageInstance?void 0:storage?.type;return[{plugin:"ApprovalPlugin",option:type==="redis"||type==="sqlite"?`storage: { type: '${type}' }`:void 0,memory:"storage: { type: 'memory' }"}]});__publicField(ApprovalPlugin,"dynamicProviders",options=>{const providers=[];const config={...ApprovalPlugin.defaultOptions,...options};const external=resolveExternalApproval(config);const maxDelegationDepth=resolveMaxDelegationDepth(config);providers.push(storeProvider({name:"approval:store",provide:ApprovalStoreToken,inject:()=>[ScopeEntry2],useFactory:async scope=>{const store=new ApprovalStorageStore({storage:config.storage,storageInstance:config.storageInstance,namespace:config.namespace,cleanupIntervalSeconds:config.cleanupIntervalSeconds,maxDelegationDepth,audit:config.enableAudit?new LoggerAuditSink(scope.logger.child("ApprovalAudit")):void 0});await store.initialize();return store}}));if(config.mode==="webhook"){providers.push(storeProvider({name:"approval:challenge-service",provide:ChallengeServiceToken,inject:()=>[],useFactory:async()=>{const service=new ChallengeService({storage:config.storage,storageInstance:config.storageInstance,namespace:`${config.namespace}:challenge`,defaultTtlSeconds:config.webhook?.challengeTtl??300});await service.initialize();return service}}))}const externalApprover=externalApproverProvider(external);if(externalApprover)providers.push(externalApprover);if(config.enableAudit){providers.push({name:"approval:audit",provide:ApprovalAuditToken,inject:()=>[ScopeEntry2],useFactory:scope=>new LoggerAuditSink(scope.logger.child("ApprovalAudit"))})}providers.push({name:"approval:service",provide:ApprovalServiceToken,scope:ProviderScope4.CONTEXT,inject:()=>[ApprovalStoreToken,FRONTMCP_CONTEXT,ScopeEntry2],useFactory:(store,ctx,scope)=>{const{sessionId,userId}=resolveApprovalIdentity(ctx);return createApprovalService(store,sessionId,userId,toolRequirementLookup(scope))}});return providers});ApprovalPlugin=__decorateClass([Plugin2({name:"approval",description:"Tool authorization workflow with PKCE webhook security",plugins:[ApprovalCheckPlugin],contextExtensions:[{property:"approval",token:ApprovalServiceToken,errorMessage:"ApprovalPlugin is not installed. Add ApprovalPlugin.init() to your plugins array."}]})],ApprovalPlugin);var installed=false;function installApprovalContextExtension(){if(installed)return;const{ExecutionContextBase}=__require("@frontmcp/sdk");Object.defineProperty(ExecutionContextBase.prototype,"approval",{get:function(){return this.get(ApprovalServiceToken)},configurable:true,enumerable:false});installed=true}export{ApprovalCheckPlugin,ApprovalConfigurationError,ApprovalError,ApprovalExpiredError,ApprovalOperationError,ApprovalPlugin,ApprovalPlugin as ApprovalPluginClass,ApprovalRequiredError,ApprovalScope,ApprovalScopeNotAllowedError,ApprovalService,ApprovalServiceToken,ApprovalState,ApprovalStorageStore,ApprovalStoreToken,ChallengeService,ChallengeServiceToken,ChallengeValidationError,adminGrantor,adminRevoker,agentGrantor,apiGrantor,createApprovalMemoryStore,createApprovalService,createMemoryChallengeService,customGrantor,delegationDepth,delegationProblem,expiryRevoker,extendDelegation,installApprovalContextExtension,isApiGrantor,isAutoGrantor,isDelegatedGrantor,isGrantorSource,isHumanGrantor,normalizeGrantor,normalizeRevoker,oauthGrantor,policyGrantor,policyRevoker,sessionEndRevoker,systemGrantor,testGrantor,userGrantor,userRevoker};
package/esm/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontmcp/plugin-approval",
3
- "version": "1.11.2",
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.11.2",
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.11.2",
59
- "@frontmcp/sdk": "1.11.2",
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.11.2",
68
+ "@frontmcp/sdk": "1.12.0-rc.1",
69
69
  "reflect-metadata": "^0.2.2"
70
70
  }
71
71
  }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `POST <webhook.callbackPath>`: where an approval system sends its decisions, through a hookable flow.
3
+ *
4
+ * @module @frontmcp/plugin-approval
5
+ */
6
+ import 'reflect-metadata';
7
+ import { FlowBase, httpInputSchema, HttpJsonSchema, type FlowRunOptions, type ScopeEntry, type ServerRequest } from '@frontmcp/sdk';
8
+ import type { CallbackAnswer, CallbackRequest } from './webhook-approver';
9
+ declare const plan: {
10
+ readonly pre: ["checkIpFilter", "acquireQuota"];
11
+ readonly execute: ["handleCallback"];
12
+ };
13
+ export declare const approvalCallbackStateSchema: import("@frontmcp/lazy-zod").ZodObject<{}, import("zod/v4/core").$strip>;
14
+ declare global {
15
+ interface ExtendFlows {
16
+ 'approval:webhook-callback': FlowRunOptions<ApprovalCallbackFlow, typeof plan, typeof httpInputSchema, typeof HttpJsonSchema, typeof approvalCallbackStateSchema>;
17
+ }
18
+ }
19
+ /** Takes the decisions posted to one callback path. */
20
+ export interface ApprovalCallbackHandler {
21
+ handleCallback(request: CallbackRequest): Promise<CallbackAnswer>;
22
+ }
23
+ declare const name: "approval:webhook-callback";
24
+ export default class ApprovalCallbackFlow extends FlowBase<typeof name> {
25
+ static canActivate(request: ServerRequest, scope: ScopeEntry): boolean;
26
+ checkIpFilter(): Promise<void>;
27
+ acquireQuota(): Promise<void>;
28
+ handleCallback(): Promise<void>;
29
+ }
30
+ /**
31
+ * Serves `POST <path>` on the scope for `handler`. Throws `ApprovalConfigurationError` for a path another
32
+ * `ApprovalPlugin` already serves, the MCP endpoint's, or one under `/oauth` or `/.well-known`.
33
+ */
34
+ export declare function serveApprovalCallback(scope: ScopeEntry, path: string, handler: ApprovalCallbackHandler): Promise<void>;
35
+ export {};
36
+ //# sourceMappingURL=approval-callback.flow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-callback.flow.d.ts","sourceRoot":"","sources":["../../src/external/approval-callback.flow.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,kBAAkB,CAAC;AAG1B,OAAO,EAIL,QAAQ,EAER,eAAe,EACf,cAAc,EAId,KAAK,cAAc,EACnB,KAAK,UAAU,EACf,KAAK,aAAa,EACnB,MAAM,eAAe,CAAC;AAGvB,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAE1E,QAAA,MAAM,IAAI;;;CAG2B,CAAC;AAEtC,eAAO,MAAM,2BAA2B,0EAAe,CAAC;AAExD,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,WAAW;QACnB,2BAA2B,EAAE,cAAc,CACzC,oBAAoB,EACpB,OAAO,IAAI,EACX,OAAO,eAAe,EACtB,OAAO,cAAc,EACrB,OAAO,2BAA2B,CACnC,CAAC;KACH;CACF;AAED,uDAAuD;AACvD,MAAM,WAAW,uBAAuB;IACtC,cAAc,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;CACnE;AAKD,QAAA,MAAM,IAAI,EAAG,2BAAoC,CAAC;AAWlD,MAAM,CAAC,OAAO,OAAO,oBAAqB,SAAQ,QAAQ,CAAC,OAAO,IAAI,CAAC;IACrE,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO;IAKhE,aAAa;IAKb,YAAY;IAKZ,cAAc;CAMrB;AAQD;;;GAGG;AACH,wBAAsB,qBAAqB,CACzC,KAAK,EAAE,UAAU,EACjB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,IAAI,CAAC,CAiBf"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * What an external approval system's decision does: an approval recorded under the tool's policy, or a denial.
3
+ *
4
+ * @module @frontmcp/plugin-approval
5
+ */
6
+ import type { FrontMcpLogger } from '@frontmcp/sdk';
7
+ import type { ApprovalRequirementLookup } from '../services/approval.service';
8
+ import type { ApprovalStore } from '../stores/approval-store.interface';
9
+ import { ApprovalScope, type ApprovalContext, type ApprovalGrantor, type ToolApprovalRequirement } from '../types';
10
+ /** A call the gate refused for want of an approval, which an external system is asked about. */
11
+ export interface PendingApprovalCall {
12
+ toolId: string;
13
+ toolName: string;
14
+ sessionId: string;
15
+ userId?: string;
16
+ context?: ApprovalContext;
17
+ requirement: ToolApprovalRequirement;
18
+ /** The caller's access token, sent only where an option asks for it. */
19
+ accessToken?: string;
20
+ signal?: AbortSignal;
21
+ }
22
+ /** What an external system decided for a call: run it, refuse it as denied, or refuse it as still pending. */
23
+ export type ExternalApprovalOutcome = 'approved' | 'denied' | 'pending';
24
+ /** Asks an external approval system about a call the gate would refuse. */
25
+ export interface ExternalApprover {
26
+ /** How it asks, as the audit trail names it. */
27
+ readonly via: 'webhook' | 'recheck';
28
+ requestApproval(call: PendingApprovalCall): Promise<ExternalApprovalOutcome>;
29
+ }
30
+ /** Who an approval or denial is for. */
31
+ export interface DecisionSubject {
32
+ toolId: string;
33
+ sessionId: string;
34
+ userId?: string;
35
+ context?: ApprovalContext;
36
+ }
37
+ export interface ExternalDecision {
38
+ scope?: ApprovalScope;
39
+ ttlMs?: number;
40
+ decidedBy?: ApprovalGrantor;
41
+ reason?: string;
42
+ }
43
+ /** A request's id: the same for every call of one caller to one tool, and naming neither. */
44
+ export declare function pendingRequestKey(subject: Pick<DecisionSubject, 'toolId' | 'sessionId' | 'userId'>): string;
45
+ /** Records external decisions in the plugin's store. */
46
+ export declare class ApprovalDecisionRecorder {
47
+ private readonly store;
48
+ private readonly requirementOf;
49
+ private readonly logger;
50
+ constructor(store: ApprovalStore, requirementOf: ApprovalRequirementLookup, logger: FrontMcpLogger);
51
+ /**
52
+ * Records an approval, held to the tool's `allowedScopes` and `maxTtlMs` like one granted through `this.approval`.
53
+ * Returns `false`, and records nothing, for one the policy refuses or that can't be stored for this caller (a
54
+ * `user` approval for a caller with no user).
55
+ */
56
+ approve(subject: DecisionSubject, decision: ExternalDecision, origin: string): Promise<boolean>;
57
+ /** Records a denial of the tool for the caller's session, lasting `ttlMs`. */
58
+ deny(subject: DecisionSubject, decision: ExternalDecision, ttlMs: number, origin: string): Promise<void>;
59
+ }
60
+ //# sourceMappingURL=approval-decisions.d.ts.map