ebay-mcp 1.13.2 → 1.14.0

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 (169) hide show
  1. package/README.de.md +3 -3
  2. package/README.es.md +3 -3
  3. package/README.fr.md +3 -3
  4. package/README.ja.md +3 -3
  5. package/README.ko.md +3 -3
  6. package/README.md +163 -41
  7. package/README.pt-BR.md +3 -3
  8. package/README.ru.md +3 -3
  9. package/README.zh-CN.md +3 -3
  10. package/build/api/account-management/account.js +633 -297
  11. package/build/api/analytics-and-report/analytics.js +111 -65
  12. package/build/api/client.js +199 -140
  13. package/build/api/clientRequestError.js +23 -0
  14. package/build/api/clientTrading.js +213 -0
  15. package/build/api/clientTradingError.js +4 -0
  16. package/build/api/communication/feedback.js +147 -59
  17. package/build/api/communication/message.js +134 -81
  18. package/build/api/communication/negotiation.js +65 -53
  19. package/build/api/communication/notification.js +458 -164
  20. package/build/api/developer/developer.js +99 -45
  21. package/build/api/index.js +23 -8
  22. package/build/api/listing-management/inventory.js +884 -338
  23. package/build/api/listing-metadata/metadata.js +416 -170
  24. package/build/api/listing-metadata/taxonomy.js +187 -42
  25. package/build/api/marketing-and-promotions/marketing.js +1392 -598
  26. package/build/api/marketing-and-promotions/recommendation.js +49 -24
  27. package/build/api/order-management/dispute.js +226 -45
  28. package/build/api/order-management/fulfillment.js +144 -71
  29. package/build/api/order-management/orderIssueHelpers.js +61 -0
  30. package/build/api/other/compliance.js +50 -38
  31. package/build/api/other/edelivery.js +603 -159
  32. package/build/api/other/finding.js +280 -0
  33. package/build/api/other/identity.js +30 -15
  34. package/build/api/other/translation.js +29 -14
  35. package/build/api/other/vero.js +113 -27
  36. package/build/api/rateLimitTracker.js +55 -0
  37. package/build/api/shared/request.js +189 -98
  38. package/build/api/trading/trading.js +154 -87
  39. package/build/auth/credentialSession.js +250 -0
  40. package/build/auth/oauth.js +298 -171
  41. package/build/auth/{oauth-metadata.js → oauthMetadata.js} +22 -6
  42. package/build/auth/oauthMiddleware.js +104 -0
  43. package/build/auth/{scope-utils.js → scopeUtils.js} +101 -28
  44. package/build/auth/tokenVerifier.js +243 -0
  45. package/build/auth/tokenVerifierError.js +21 -0
  46. package/build/config/environment.js +148 -113
  47. package/build/config/{tool-families.js → toolFamilies.js} +30 -14
  48. package/build/index.js +25 -19
  49. package/build/mcp/{http-transport.js → httpTransport.js} +102 -52
  50. package/build/mcp/readOnlyFilter.js +67 -0
  51. package/build/mcp/runtime.js +31 -13
  52. package/build/mcp/{tool-gating.js → toolGating.js} +77 -49
  53. package/build/mcp/{ui-bridge.js → uiBridge.js} +80 -23
  54. package/build/schemas/account-management/account.js +144 -6
  55. package/build/schemas/analytics/analytics.js +33 -19
  56. package/build/schemas/communication/messages.js +12 -42
  57. package/build/schemas/developer/developer.js +135 -0
  58. package/build/schemas/fulfillment/orders.js +183 -21
  59. package/build/schemas/index.js +27 -19
  60. package/build/schemas/inventory-management/inventory.js +17 -9
  61. package/build/schemas/marketing/marketing.js +480 -25
  62. package/build/schemas/metadata/metadata.js +11 -6
  63. package/build/schemas/other/finding.js +27 -0
  64. package/build/schemas/other/otherApis.js +424 -0
  65. package/build/schemas/taxonomy/taxonomy.js +11 -5
  66. package/build/scripts/{auto-setup.js → autoSetup.js} +87 -74
  67. package/build/scripts/{build-ui.js → buildUi.js} +6 -1
  68. package/build/scripts/{dev-sync.js → devSync.js} +169 -110
  69. package/build/scripts/diagnostics.js +52 -44
  70. package/build/scripts/{download-specs.js → downloadSpecs.js} +29 -21
  71. package/build/scripts/{interactive-setup.js → interactiveSetup.js} +84 -78
  72. package/build/scripts/setup.js +241 -178
  73. package/build/scripts/{setup-shared.js → setupShared.js} +29 -7
  74. package/build/scripts/skills.js +35 -27
  75. package/build/scripts/updateApiStatusDoc.js +71 -0
  76. package/build/serverHttp.js +90 -0
  77. package/build/skills/content.js +124 -118
  78. package/build/skills/index.js +22 -10
  79. package/build/skills/install.js +21 -10
  80. package/build/skills/markers.js +50 -15
  81. package/build/skills/{registry-snapshot.js → registrySnapshot.js} +8 -2
  82. package/build/skills/render.js +41 -14
  83. package/build/skills/targets.js +49 -17
  84. package/build/tools/categories/account.js +166 -264
  85. package/build/tools/categories/analytics.js +11 -22
  86. package/build/tools/categories/browse.js +17 -0
  87. package/build/tools/categories/communication.js +124 -399
  88. package/build/tools/categories/connector.js +23 -20
  89. package/build/tools/categories/developer.js +46 -159
  90. package/build/tools/categories/fulfillment.js +84 -215
  91. package/build/tools/categories/index.js +6 -14
  92. package/build/tools/categories/inventory.js +238 -293
  93. package/build/tools/categories/marketing.js +677 -39
  94. package/build/tools/categories/metadata.js +190 -117
  95. package/build/tools/categories/other.js +81 -208
  96. package/build/tools/categories/taxonomy.js +29 -20
  97. package/build/tools/categories/{token-management.js → tokenManagement.js} +187 -192
  98. package/build/tools/categories/trading.js +16 -47
  99. package/build/tools/contracts.js +34 -24
  100. package/build/tools/{define-tool.js → defineTool.js} +44 -29
  101. package/build/tools/registry.js +87 -29
  102. package/build/tools/schemas.js +3 -57
  103. package/build/tools/ui/archetypes.js +1 -0
  104. package/build/tools/ui/{map-helpers.js → mapHelpers.js} +69 -19
  105. package/build/tools/ui/maps.js +294 -80
  106. package/build/types/index.js +1 -1
  107. package/build/ui/card.html +14 -14
  108. package/build/ui/chart.html +14 -14
  109. package/build/ui/stat.html +87 -0
  110. package/build/ui/table.html +14 -14
  111. package/build/utils/apiStatusFeed.js +95 -0
  112. package/build/utils/cliOutput.js +15 -0
  113. package/build/utils/cliUi.js +108 -0
  114. package/build/utils/communication/feedback.js +57 -77
  115. package/build/utils/communication/message.js +69 -98
  116. package/build/utils/communication/negotiation.js +30 -57
  117. package/build/utils/communication/notification.js +112 -252
  118. package/build/utils/{date-converter.js → dateConverter.js} +62 -30
  119. package/build/utils/effectSchema.js +203 -0
  120. package/build/utils/effectSchemaAdapter.js +121 -0
  121. package/build/utils/effectSchemaChainMethods.js +146 -0
  122. package/build/utils/effectSchemaRefinements.js +104 -0
  123. package/build/utils/effectSchemaStringMethods.js +63 -0
  124. package/build/utils/effectSchemaTypes.js +47 -0
  125. package/build/utils/{env-parser.js → envParser.js} +10 -2
  126. package/build/utils/errors.js +7 -3
  127. package/build/utils/http.js +148 -89
  128. package/build/utils/{llm-client-detector.js → llmClientDetector.js} +295 -274
  129. package/build/utils/logger.js +127 -51
  130. package/build/utils/{oauth-helper.js → oauthHelper.js} +127 -90
  131. package/build/utils/other/compliance.js +18 -38
  132. package/build/utils/other/identity.js +2 -2
  133. package/build/utils/other/translation.js +4 -4
  134. package/build/utils/other/vero.js +36 -20
  135. package/build/utils/schemaHelpers.js +22 -0
  136. package/build/utils/scopeHelper.js +270 -0
  137. package/build/utils/securityChecker.js +316 -0
  138. package/build/utils/{setup-validator.js → setupValidator.js} +113 -94
  139. package/build/utils/{setup-wizard.js → setupWizard.js} +57 -46
  140. package/build/utils/{token-utils.js → tokenUtils.js} +2 -2
  141. package/build/utils/trading/trading.js +35 -0
  142. package/build/utils/typeGuards.js +12 -0
  143. package/build/utils/version.js +65 -29
  144. package/package.json +10 -8
  145. package/build/api/client-trading.js +0 -124
  146. package/build/api/communication/shared.js +0 -59
  147. package/build/api/shared/query-params.js +0 -16
  148. package/build/auth/credential-session.js +0 -166
  149. package/build/auth/oauth-middleware.js +0 -100
  150. package/build/auth/token-verifier.js +0 -186
  151. package/build/schemas/other/other-apis.js +0 -390
  152. package/build/scripts/update-api-status-doc.js +0 -44
  153. package/build/server-http.js +0 -85
  154. package/build/tools/definitions/marketing.js +0 -1381
  155. package/build/tools/tool-handlers/marketing.js +0 -312
  156. package/build/utils/account-management/account.js +0 -818
  157. package/build/utils/api-status-feed.js +0 -84
  158. package/build/utils/cli-ui.js +0 -47
  159. package/build/utils/order-management/dispute.js +0 -369
  160. package/build/utils/order-management/fulfillment.js +0 -205
  161. package/build/utils/other/edelivery.js +0 -235
  162. package/build/utils/schema-helpers.js +0 -13
  163. package/build/utils/scope-helper.js +0 -207
  164. package/build/utils/security-checker.js +0 -248
  165. package/build/utils/type-guards.js +0 -6
  166. /package/build/auth/{oauth-types.js → oauthTypes.js} +0 -0
  167. /package/build/{server-http.d.ts → serverHttp.d.ts} +0 -0
  168. /package/build/tools/ui/{view-models.js → viewModels.js} +0 -0
  169. /package/build/types/{ebay-enums.js → ebayEnums.js} +0 -0
@@ -0,0 +1,104 @@
1
+ /**
2
+ * OAuth 2.1 middleware for Express
3
+ * Implements RFC 6750 Bearer Token authentication
4
+ */
5
+ import { getErrorMessage } from '../utils/errors.js';
6
+ import { Effect, Either } from 'effect';
7
+ /**
8
+ * Create Bearer token authentication middleware
9
+ *
10
+ * @param config - Token verifier and RFC 6750 challenge settings.
11
+ * @returns Express middleware that verifies bearer tokens and attaches `req.auth`.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const middleware = createBearerAuthMiddleware({ verifier, resourceMetadataUrl });
16
+ * ```
17
+ */
18
+ export const createBearerAuthMiddleware = (config) => {
19
+ const realm = config.realm || 'mcp';
20
+ return async (req, res, next) => {
21
+ // Extract token from Authorization header
22
+ const authHeader = req.headers.authorization;
23
+ if (!authHeader) {
24
+ sendUnauthorized(res, realm, config.resourceMetadataUrl, {
25
+ error: 'invalid_token',
26
+ error_description: 'No authorization header provided',
27
+ });
28
+ return;
29
+ }
30
+ // Check Bearer scheme
31
+ const parts = authHeader.split(' ');
32
+ if (parts.length !== 2 || parts[0] !== 'Bearer') {
33
+ sendUnauthorized(res, realm, config.resourceMetadataUrl, {
34
+ error: 'invalid_token',
35
+ error_description: 'Invalid authorization header format. Expected: Bearer <token>',
36
+ });
37
+ return;
38
+ }
39
+ const token = parts[1];
40
+ const verified = await Effect.runPromise(Effect.either(config.verifier.verifyToken(token)));
41
+ if (Either.isLeft(verified)) {
42
+ const errorMessage = getErrorMessage(verified.left, 'Token verification failed');
43
+ sendUnauthorized(res, realm, config.resourceMetadataUrl, {
44
+ error: 'invalid_token',
45
+ error_description: errorMessage,
46
+ });
47
+ return;
48
+ }
49
+ req.auth = verified.right;
50
+ next();
51
+ };
52
+ };
53
+ /**
54
+ * Send 401 Unauthorized response with RFC 6750 compliant WWW-Authenticate header
55
+ */
56
+ const sendUnauthorized = (res, realm, resourceMetadataUrl, challenge) => {
57
+ // Build WWW-Authenticate header per RFC 6750
58
+ let authenticateValue = `Bearer realm="${realm}", resource_metadata="${resourceMetadataUrl}"`;
59
+ if (challenge.error) {
60
+ authenticateValue += `, error="${challenge.error}"`;
61
+ }
62
+ if (challenge.error_description) {
63
+ authenticateValue += `, error_description="${challenge.error_description}"`;
64
+ }
65
+ if (challenge.scope) {
66
+ authenticateValue += `, scope="${challenge.scope}"`;
67
+ }
68
+ res.setHeader('WWW-Authenticate', authenticateValue);
69
+ res.status(401).json({
70
+ error: challenge.error || 'unauthorized',
71
+ error_description: challenge.error_description || 'Authorization required',
72
+ });
73
+ };
74
+ /**
75
+ * Optional middleware to check specific scopes
76
+ *
77
+ * @param requiredScopes - OAuth scopes required by the protected route.
78
+ * @returns Express middleware that rejects unauthenticated or under-scoped requests.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * app.get('/admin', requireScopes(['mcp:admin']), handler);
83
+ * ```
84
+ */
85
+ export const requireScopes = (requiredScopes) => (req, res, next) => {
86
+ if (!req.auth) {
87
+ res.status(401).json({
88
+ error: 'unauthorized',
89
+ error_description: 'No authentication information found',
90
+ });
91
+ return;
92
+ }
93
+ const hasRequiredScopes = requiredScopes.every((scope) => req.auth.scopes.includes(scope));
94
+ if (!hasRequiredScopes) {
95
+ res.status(403).json({
96
+ error: 'insufficient_scope',
97
+ error_description: `Missing required scopes: ${requiredScopes.join(', ')}`,
98
+ required_scopes: requiredScopes,
99
+ provided_scopes: req.auth.scopes,
100
+ });
101
+ return;
102
+ }
103
+ next();
104
+ };
@@ -4,8 +4,17 @@
4
4
  import { getDefaultScopes, validateScopes } from '../config/environment.js';
5
5
  /**
6
6
  * Validate scopes and provide detailed validation results
7
+ *
8
+ * @param scopes - OAuth scopes to validate.
9
+ * @param environment - eBay environment whose scope catalogue should be used.
10
+ * @returns Validity flag plus accepted and rejected scope lists.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const result = validateScopesDetailed(scopes, 'production');
15
+ * ```
7
16
  */
8
- export function validateScopesDetailed(scopes, environment) {
17
+ export const validateScopesDetailed = (scopes, environment) => {
9
18
  const validation = validateScopes(scopes, environment);
10
19
  const validScopeSet = new Set(getDefaultScopes(environment));
11
20
  const validScopes = [];
@@ -24,12 +33,20 @@ export function validateScopesDetailed(scopes, environment) {
24
33
  validScopes,
25
34
  invalidScopes,
26
35
  };
27
- }
36
+ };
28
37
  /**
29
38
  * Get required scopes for a specific tool
30
39
  * This maps tool names to their required eBay OAuth scopes
40
+ *
41
+ * @param toolName - MCP tool name to look up.
42
+ * @returns Scope requirement for the tool, or null when unknown.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const requirement = getRequiredScopesForTool('ebay_get_inventory_items');
47
+ * ```
31
48
  */
32
- export function getRequiredScopesForTool(toolName) {
49
+ export const getRequiredScopesForTool = (toolName) => {
33
50
  // Scope requirements mapping based on eBay API documentation
34
51
  const scopeMap = {
35
52
  // Inventory Management Tools
@@ -49,7 +66,7 @@ export function getRequiredScopesForTool(toolName) {
49
66
  minimumScope: 'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
50
67
  description: 'Requires read access to inventory',
51
68
  },
52
- ebay_create_inventory_item: {
69
+ ebay_create_or_replace_inventory_item: {
53
70
  requiredScopes: ['https://api.ebay.com/oauth/api_scope/sell.inventory'],
54
71
  minimumScope: 'https://api.ebay.com/oauth/api_scope/sell.inventory',
55
72
  description: 'Requires write access to inventory',
@@ -150,20 +167,36 @@ export function getRequiredScopesForTool(toolName) {
150
167
  },
151
168
  };
152
169
  return scopeMap[toolName] || null;
153
- }
170
+ };
154
171
  /**
155
172
  * Check if a token has all required scopes for a tool
173
+ *
174
+ * @param tokenScopes - OAuth scopes present on the token.
175
+ * @param requiredScopes - Alternative scopes that can satisfy the requirement.
176
+ * @returns True when the token has at least one required scope.
177
+ *
178
+ * @example
179
+ * ```ts
180
+ * const allowed = hasRequiredScopes(tokenScopes, requirement.requiredScopes);
181
+ * ```
156
182
  */
157
- export function hasRequiredScopes(tokenScopes, requiredScopes) {
183
+ export const hasRequiredScopes = (tokenScopes, requiredScopes) => {
158
184
  const tokenScopeSet = new Set(tokenScopes);
159
185
  // Check if at least one of the required scopes is present
160
186
  // (Some tools accept either readonly or write scope)
161
187
  return requiredScopes.some((scope) => tokenScopeSet.has(scope));
162
- }
188
+ };
163
189
  /**
164
190
  * Get the differences between production and sandbox scopes
191
+ *
192
+ * @returns Scopes grouped by production/sandbox availability.
193
+ *
194
+ * @example
195
+ * ```ts
196
+ * const diff = getScopeDifferences();
197
+ * ```
165
198
  */
166
- export function getScopeDifferences() {
199
+ export const getScopeDifferences = () => {
167
200
  const productionScopes = getDefaultScopes('production');
168
201
  const sandboxScopes = getDefaultScopes('sandbox');
169
202
  const productionSet = new Set(productionScopes);
@@ -191,21 +224,37 @@ export function getScopeDifferences() {
191
224
  productionOnly,
192
225
  sandboxOnly,
193
226
  };
194
- }
227
+ };
195
228
  /**
196
229
  * Format scope for display (remove common prefix for readability)
230
+ *
231
+ * @param scope - OAuth scope URL or custom scope string.
232
+ * @returns Scope without the common eBay OAuth URL prefix when present.
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * const label = formatScopeForDisplay('https://api.ebay.com/oauth/api_scope/sell.inventory');
237
+ * ```
197
238
  */
198
- export function formatScopeForDisplay(scope) {
239
+ export const formatScopeForDisplay = (scope) => {
199
240
  const prefix = 'https://api.ebay.com/oauth/';
200
241
  if (scope.startsWith(prefix)) {
201
242
  return scope.substring(prefix.length);
202
243
  }
203
244
  return scope;
204
- }
245
+ };
205
246
  /**
206
247
  * Group scopes by API category
248
+ *
249
+ * @param scopes - OAuth scopes to group.
250
+ * @returns Scopes grouped into sell, buy, commerce, and other buckets.
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * const grouped = groupScopesByCategory(scopes);
255
+ * ```
207
256
  */
208
- export function groupScopesByCategory(scopes) {
257
+ export const groupScopesByCategory = (scopes) => {
209
258
  const categories = {
210
259
  sell: [],
211
260
  buy: [],
@@ -227,26 +276,48 @@ export function groupScopesByCategory(scopes) {
227
276
  }
228
277
  });
229
278
  return categories;
230
- }
279
+ };
231
280
  /**
232
281
  * Check if a scope is readonly
282
+ *
283
+ * @param scope - OAuth scope to inspect.
284
+ * @returns True when the scope name includes `.readonly`.
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * const readonly = isScopeReadonly(scope);
289
+ * ```
233
290
  */
234
- export function isScopeReadonly(scope) {
235
- return scope.includes('.readonly');
236
- }
291
+ export const isScopeReadonly = (scope) => scope.includes('.readonly');
237
292
  /**
238
293
  * Get the write version of a readonly scope
294
+ *
295
+ * @param readonlyScope - Readonly OAuth scope to convert.
296
+ * @returns Write scope equivalent, or null when the input is already write-capable.
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * const writeScope = getWriteScope('https://api.ebay.com/oauth/api_scope/sell.inventory.readonly');
301
+ * ```
239
302
  */
240
- export function getWriteScope(readonlyScope) {
303
+ export const getWriteScope = (readonlyScope) => {
241
304
  if (!isScopeReadonly(readonlyScope)) {
242
305
  return null; // Already a write scope
243
306
  }
244
307
  return readonlyScope.replace('.readonly', '');
245
- }
308
+ };
246
309
  /**
247
310
  * Get the readonly version of a write scope
311
+ *
312
+ * @param writeScope - Write-capable OAuth scope to convert.
313
+ * @returns Readonly scope equivalent when eBay exposes one, otherwise null.
314
+ *
315
+ * @example
316
+ * ```ts
317
+ * const readonlyScope = getReadonlyScope('https://api.ebay.com/oauth/api_scope/sell.inventory');
318
+ * ```
248
319
  */
249
- export function getReadonlyScope(writeScope) {
320
+ export const getReadonlyScope = (writeScope) => {
250
321
  if (isScopeReadonly(writeScope)) {
251
322
  return null; // Already a readonly scope
252
323
  }
@@ -268,11 +339,19 @@ export function getReadonlyScope(writeScope) {
268
339
  return `${writeScope}.readonly`;
269
340
  }
270
341
  return null;
271
- }
342
+ };
272
343
  /**
273
344
  * Get scope description from scope name
345
+ *
346
+ * @param scope - OAuth scope URL or scope type string.
347
+ * @returns Human description for the scope.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * const description = getScopeTypeDescription('https://api.ebay.com/oauth/api_scope/sell.inventory');
352
+ * ```
274
353
  */
275
- export function getScopeTypeDescription(scope) {
354
+ export const getScopeTypeDescription = (scope) => {
276
355
  // Extract the last part of the scope
277
356
  const parts = scope.split('/');
278
357
  const scopeType = parts[parts.length - 1];
@@ -301,10 +380,4 @@ export function getScopeTypeDescription(scope) {
301
380
  'sell.stores.readonly': 'View eBay stores',
302
381
  };
303
382
  return descriptions[scopeType] || `Access to ${scopeType}`;
304
- }
305
- /**
306
- * Backward-compatible alias for scope description lookup.
307
- */
308
- export function getScopeDescription(scope) {
309
- return getScopeTypeDescription(scope);
310
- }
383
+ };
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Token verification using OAuth 2.0 Token Introspection (RFC 7662)
3
+ * and JWT validation
4
+ */
5
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
6
+ import { tokenVerifierError, } from '../auth/tokenVerifierError.js';
7
+ import { getErrorMessage } from '../utils/errors.js';
8
+ import { describeHttpError, httpRequestEffect } from '../utils/http.js';
9
+ import { Effect } from 'effect';
10
+ /**
11
+ * Verifies MCP Bearer tokens using OAuth introspection or JWT validation.
12
+ */
13
+ export class TokenVerifier {
14
+ config;
15
+ metadata = null;
16
+ constructor(config) {
17
+ this.config = config;
18
+ }
19
+ /**
20
+ * Execute an OAuth verifier HTTP request and return its decoded body.
21
+ */
22
+ requestVerifierData(operation, reason, failureMessage, options) {
23
+ return httpRequestEffect(options).pipe(Effect.map((response) => response.data), Effect.mapError((cause) => tokenVerifierError({
24
+ operation,
25
+ reason,
26
+ message: `${failureMessage}: ${describeHttpError(cause)}`,
27
+ cause,
28
+ })));
29
+ }
30
+ /**
31
+ * Initialize the verifier by loading OAuth server metadata.
32
+ *
33
+ * @returns An Effect that completes after metadata is loaded or assigned.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * await Effect.runPromise(verifier.initialize());
38
+ * ```
39
+ */
40
+ initialize = () => Effect.gen(this, function* () {
41
+ if (typeof this.config.authServerMetadata === 'string') {
42
+ this.metadata = yield* this.requestVerifierData('initialize', 'metadataRequest', 'Failed to load OAuth server metadata', {
43
+ url: this.config.authServerMetadata,
44
+ });
45
+ }
46
+ else {
47
+ this.metadata = this.config.authServerMetadata;
48
+ }
49
+ });
50
+ /**
51
+ * Verify an access token.
52
+ *
53
+ * @param token - Bearer token received by the MCP HTTP transport.
54
+ * @returns An Effect that succeeds with verified token claims.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * const verified = await Effect.runPromise(verifier.verifyToken(token));
59
+ * ```
60
+ */
61
+ verifyToken = (token) => Effect.gen(this, function* () {
62
+ if (!this.metadata) {
63
+ return yield* Effect.fail(tokenVerifierError({
64
+ operation: 'verifyToken',
65
+ reason: 'notInitialized',
66
+ message: 'Token verifier not initialized',
67
+ }));
68
+ }
69
+ if (this.config.useIntrospection === false) {
70
+ return yield* this.verifyViaJWT(token);
71
+ }
72
+ return yield* this.verifyViaIntrospection(token);
73
+ });
74
+ /**
75
+ * Verify token using OAuth 2.0 Token Introspection (RFC 7662)
76
+ */
77
+ verifyViaIntrospection = (token) => Effect.gen(this, function* () {
78
+ if (!this.metadata) {
79
+ return yield* Effect.fail(tokenVerifierError({
80
+ operation: 'verifyViaIntrospection',
81
+ reason: 'notInitialized',
82
+ message: 'Token verifier not initialized',
83
+ }));
84
+ }
85
+ // Check if introspection endpoint is available
86
+ const introspectionEndpoint = this.metadata.introspection_endpoint;
87
+ if (!introspectionEndpoint) {
88
+ return yield* Effect.fail(tokenVerifierError({
89
+ operation: 'verifyViaIntrospection',
90
+ reason: 'missingIntrospectionEndpoint',
91
+ message: 'Introspection endpoint not available in OAuth server metadata',
92
+ }));
93
+ }
94
+ // Prepare introspection request. Client credentials authenticate via HTTP
95
+ // Basic (RFC 7662 §2.1) rather than form body fields.
96
+ const requestData = {
97
+ token,
98
+ token_type_hint: 'access_token',
99
+ };
100
+ const headers = {
101
+ 'Content-Type': 'application/x-www-form-urlencoded',
102
+ };
103
+ if (this.config.clientId && this.config.clientSecret) {
104
+ headers.Authorization = `Basic ${Buffer.from(`${this.config.clientId}:${this.config.clientSecret}`).toString('base64')}`;
105
+ }
106
+ const params = new URLSearchParams({
107
+ token: requestData.token,
108
+ });
109
+ // Make introspection request
110
+ const data = yield* this.requestVerifierData('verifyViaIntrospection', 'introspectionRequest', 'Token introspection failed', {
111
+ method: 'POST',
112
+ url: introspectionEndpoint,
113
+ body: params,
114
+ headers,
115
+ });
116
+ // Check if token is active
117
+ if (!data.active) {
118
+ return yield* Effect.fail(tokenVerifierError({
119
+ operation: 'verifyViaIntrospection',
120
+ reason: 'inactiveToken',
121
+ message: 'Token is not active',
122
+ }));
123
+ }
124
+ // Validate audience
125
+ if (!this.validateAudience(data.aud)) {
126
+ return yield* Effect.fail(tokenVerifierError({
127
+ operation: 'verifyViaIntrospection',
128
+ reason: 'invalidAudience',
129
+ message: `Invalid audience. Expected: ${this.config.expectedAudience}, Got: ${data.aud}`,
130
+ }));
131
+ }
132
+ // Validate scopes
133
+ const scopes = data.scope ? data.scope.split(' ') : [];
134
+ if (this.config.requiredScopes) {
135
+ const hasRequiredScopes = this.config.requiredScopes.every((scope) => scopes.includes(scope));
136
+ if (!hasRequiredScopes) {
137
+ return yield* Effect.fail(tokenVerifierError({
138
+ operation: 'verifyViaIntrospection',
139
+ reason: 'missingScopes',
140
+ message: `Missing required scopes. Required: ${this.config.requiredScopes.join(', ')}, Got: ${scopes.join(', ')}`,
141
+ }));
142
+ }
143
+ }
144
+ return {
145
+ token,
146
+ clientId: data.client_id || 'missing-client-id',
147
+ scopes,
148
+ expiresAt: data.exp,
149
+ audience: data.aud,
150
+ subject: data.sub,
151
+ };
152
+ });
153
+ /**
154
+ * Verify token using JWT validation
155
+ */
156
+ verifyViaJWT = (token) => Effect.gen(this, function* () {
157
+ if (!this.metadata) {
158
+ return yield* Effect.fail(tokenVerifierError({
159
+ operation: 'verifyViaJWT',
160
+ reason: 'notInitialized',
161
+ message: 'Token verifier not initialized',
162
+ }));
163
+ }
164
+ const metadata = this.metadata;
165
+ const jwksUri = metadata.jwks_uri;
166
+ if (!jwksUri) {
167
+ return yield* Effect.fail(tokenVerifierError({
168
+ operation: 'verifyViaJWT',
169
+ reason: 'missingJwksUri',
170
+ message: 'JWKS URI not available in OAuth server metadata',
171
+ }));
172
+ }
173
+ const JWKS = yield* Effect.try({
174
+ try: () => createRemoteJWKSet(new URL(jwksUri)),
175
+ catch: (cause) => tokenVerifierError({
176
+ operation: 'verifyViaJWT',
177
+ reason: 'jwtVerification',
178
+ message: `JWT verification failed: ${getErrorMessage(cause)}`,
179
+ cause,
180
+ }),
181
+ });
182
+ const { payload } = yield* Effect.tryPromise({
183
+ try: () => jwtVerify(token, JWKS, {
184
+ issuer: metadata.issuer,
185
+ audience: this.config.expectedAudience,
186
+ }),
187
+ catch: (cause) => tokenVerifierError({
188
+ operation: 'verifyViaJWT',
189
+ reason: 'jwtVerification',
190
+ message: `JWT verification failed: ${getErrorMessage(cause)}`,
191
+ cause,
192
+ }),
193
+ });
194
+ let scopes = [];
195
+ if (typeof payload.scope === 'string') {
196
+ scopes = payload.scope.split(' ');
197
+ }
198
+ else if (Array.isArray(payload.scope)) {
199
+ scopes = payload.scope.filter((scope) => typeof scope === 'string');
200
+ }
201
+ if (this.config.requiredScopes) {
202
+ const hasRequiredScopes = this.config.requiredScopes.every((scope) => scopes.includes(scope));
203
+ if (!hasRequiredScopes) {
204
+ return yield* Effect.fail(tokenVerifierError({
205
+ operation: 'verifyViaJWT',
206
+ reason: 'missingScopes',
207
+ message: `Missing required scopes. Required: ${this.config.requiredScopes.join(', ')}, Got: ${scopes.join(', ')}`,
208
+ }));
209
+ }
210
+ }
211
+ let clientId = 'missing-client-id';
212
+ if (typeof payload.client_id === 'string') {
213
+ clientId = payload.client_id;
214
+ }
215
+ else if (typeof payload.azp === 'string') {
216
+ clientId = payload.azp;
217
+ }
218
+ return {
219
+ token,
220
+ clientId,
221
+ scopes,
222
+ expiresAt: payload.exp,
223
+ audience: payload.aud,
224
+ subject: payload.sub,
225
+ };
226
+ });
227
+ /**
228
+ * Validate audience claim
229
+ */
230
+ validateAudience(audience) {
231
+ if (!audience) {
232
+ return false;
233
+ }
234
+ const audiences = Array.isArray(audience) ? audience : [audience];
235
+ const normalizedExpected = this.config.expectedAudience.replace(/\/$/, '');
236
+ return audiences.some((aud) => {
237
+ const normalizedAud = aud.replace(/\/$/, '');
238
+ return (normalizedAud === normalizedExpected ||
239
+ normalizedAud === normalizedExpected + '/' ||
240
+ normalizedExpected === normalizedAud + '/');
241
+ });
242
+ }
243
+ }
@@ -0,0 +1,21 @@
1
+ import { Data } from 'effect';
2
+ /** Tagged failure returned by token verifier Effects. */
3
+ export class TokenVerifierError extends Data.TaggedError('TokenVerifierError') {
4
+ }
5
+ /**
6
+ * Builds a tagged token-verifier error while omitting absent optional fields.
7
+ *
8
+ * @param input - Token verifier failure fields captured at the failing boundary.
9
+ * @returns Tagged verifier error returned by token verifier Effects.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * tokenVerifierError({ operation: 'verifyToken', reason: 'notInitialized', message });
14
+ * ```
15
+ */
16
+ export const tokenVerifierError = ({ operation, reason, message, cause, }) => new TokenVerifierError({
17
+ operation,
18
+ reason,
19
+ message,
20
+ ...(cause === undefined ? {} : { cause }),
21
+ });