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
@@ -1,166 +0,0 @@
1
- import dotenv from 'dotenv';
2
- import stringify from 'dotenv-stringify';
3
- import { existsSync, readFileSync, writeFileSync } from 'fs';
4
- import { join } from 'path';
5
- /**
6
- * Default lifetime for stored eBay user access tokens when eBay omits an expiry.
7
- */
8
- export const DEFAULT_USER_ACCESS_TOKEN_TTL_SECONDS = 7200;
9
- /**
10
- * Default lifetime for stored eBay user refresh tokens when eBay omits an expiry.
11
- */
12
- export const DEFAULT_USER_REFRESH_TOKEN_TTL_SECONDS = 18 * 30 * 24 * 60 * 60;
13
- /**
14
- * Safety buffer removed from app-token expiry to avoid using near-expired tokens.
15
- */
16
- export const APP_ACCESS_TOKEN_EXPIRY_BUFFER_SECONDS = 60;
17
- /**
18
- * Credential store that merges token updates into the project .env file.
19
- */
20
- export class DotEnvCredentialStore {
21
- getEnvPath;
22
- constructor(getEnvPath = () => join(process.cwd(), '.env')) {
23
- this.getEnvPath = getEnvPath;
24
- }
25
- write(updates) {
26
- try {
27
- const envPath = this.getEnvPath();
28
- const existingEnv = existsSync(envPath) ? dotenv.parse(readFileSync(envPath, 'utf-8')) : {};
29
- const safeEnvContent = stringify({ ...existingEnv, ...updates });
30
- writeFileSync(envPath, safeEnvContent, 'utf-8');
31
- }
32
- catch (_error) {
33
- // Silent failure keeps MCP stdout clean for JSON-RPC clients.
34
- }
35
- }
36
- }
37
- /**
38
- * Redact token values for status and credential display output.
39
- */
40
- export function maskToken(token) {
41
- if (!token || token.length < 12) {
42
- return '***';
43
- }
44
- return `${token.substring(0, 6)}...${token.substring(token.length - 6)}`;
45
- }
46
- /**
47
- * Convert an expires-in duration from eBay into an absolute timestamp.
48
- */
49
- export function createExpiryTimestamp(expiresInSeconds, now = Date.now()) {
50
- return now + expiresInSeconds * 1000;
51
- }
52
- /**
53
- * Create the fallback expiry timestamp for a stored eBay user access token.
54
- */
55
- export function createDefaultAccessTokenExpiry(now = Date.now()) {
56
- return createExpiryTimestamp(DEFAULT_USER_ACCESS_TOKEN_TTL_SECONDS, now);
57
- }
58
- /**
59
- * Create the fallback expiry timestamp for a stored eBay user refresh token.
60
- */
61
- export function createDefaultRefreshTokenExpiry(now = Date.now()) {
62
- return createExpiryTimestamp(DEFAULT_USER_REFRESH_TOKEN_TTL_SECONDS, now);
63
- }
64
- /**
65
- * Create the cached app-token expiry timestamp with an early refresh buffer.
66
- */
67
- export function createAppAccessTokenExpiry(expiresInSeconds, now = Date.now()) {
68
- return createExpiryTimestamp(Math.max(0, expiresInSeconds - APP_ACCESS_TOKEN_EXPIRY_BUFFER_SECONDS), now);
69
- }
70
- /**
71
- * Determine whether a stored token expiry is missing or no longer valid.
72
- */
73
- export function isTokenExpired(expiry, now = Date.now()) {
74
- return expiry ? now >= expiry : true;
75
- }
76
- /**
77
- * Build a StoredTokenData object from normalized eBay user-token fields.
78
- */
79
- export function createStoredUserTokens(input) {
80
- const now = input.now ?? Date.now();
81
- return {
82
- clientId: input.config.clientId,
83
- clientSecret: input.config.clientSecret,
84
- redirectUri: input.config.redirectUri,
85
- locale: input.config.locale,
86
- marketplaceId: input.config.marketplaceId,
87
- contentLanguage: input.config.contentLanguage,
88
- envAppToken: input.envAppToken ?? input.config.appAccessToken,
89
- userAccessToken: input.accessToken,
90
- userRefreshToken: input.refreshToken,
91
- tokenType: input.tokenType ?? 'Bearer',
92
- userAccessTokenExpiry: input.accessTokenExpiry ?? createDefaultAccessTokenExpiry(now),
93
- userRefreshTokenExpiry: input.refreshTokenExpiry ?? createDefaultRefreshTokenExpiry(now),
94
- scope: input.scope,
95
- };
96
- }
97
- /**
98
- * Build stored token data from an eBay token endpoint response.
99
- */
100
- export function createStoredUserTokensFromResponse(input) {
101
- const now = input.now ?? Date.now();
102
- const previousTokens = input.previousTokens;
103
- return createStoredUserTokens({
104
- config: input.config,
105
- envAppToken: input.envAppToken ?? previousTokens?.envAppToken,
106
- accessToken: input.tokenData.access_token,
107
- refreshToken: input.tokenData.refresh_token ?? previousTokens?.userRefreshToken ?? '',
108
- tokenType: input.tokenData.token_type ?? previousTokens?.tokenType,
109
- accessTokenExpiry: createExpiryTimestamp(input.tokenData.expires_in, now),
110
- refreshTokenExpiry: input.tokenData.refresh_token_expires_in
111
- ? createExpiryTimestamp(input.tokenData.refresh_token_expires_in, now)
112
- : previousTokens?.userRefreshTokenExpiry,
113
- scope: input.tokenData.scope ?? previousTokens?.scope,
114
- now,
115
- });
116
- }
117
- function tokenExpiry(expiry) {
118
- if (!expiry) {
119
- return 'Not available';
120
- }
121
- return {
122
- timestamp: expiry,
123
- date: new Date(expiry).toISOString(),
124
- expired: Date.now() >= expiry,
125
- };
126
- }
127
- /**
128
- * Build redacted credential and token status data for auth diagnostics.
129
- */
130
- export function buildCredentialDisplay(input) {
131
- const { appAccessToken, appAccessTokenExpiry, authenticated, env, tokenInfo, userTokens } = input;
132
- const clientId = env.EBAY_CLIENT_ID ?? '';
133
- const clientSecret = env.EBAY_CLIENT_SECRET ?? '';
134
- const environment = env.EBAY_ENVIRONMENT ?? 'sandbox';
135
- const redirectUri = env.EBAY_REDIRECT_URI ?? '';
136
- const refreshToken = env.EBAY_USER_REFRESH_TOKEN ?? '';
137
- return {
138
- credentials: {
139
- clientId: clientId ? maskToken(clientId) : 'Not set',
140
- clientSecret: clientSecret ? '****** (set)' : 'Not set',
141
- environment,
142
- redirectUri: redirectUri || 'Not set',
143
- },
144
- tokens: {
145
- refreshToken: refreshToken ? maskToken(refreshToken) : 'Not set (in .env)',
146
- accessToken: userTokens?.userAccessToken
147
- ? maskToken(userTokens.userAccessToken)
148
- : 'Not available',
149
- accessTokenExpiry: tokenExpiry(userTokens?.userAccessTokenExpiry),
150
- refreshTokenExpiry: tokenExpiry(userTokens?.userRefreshTokenExpiry),
151
- appToken: appAccessToken ? maskToken(appAccessToken) : 'Not cached',
152
- appTokenExpiry: tokenExpiry(appAccessTokenExpiry),
153
- },
154
- status: {
155
- hasUserToken: tokenInfo.hasUserToken,
156
- hasAppAccessToken: tokenInfo.hasAppAccessToken,
157
- authenticated,
158
- currentTokenType: tokenInfo.hasUserToken
159
- ? 'user_token (10,000-50,000 req/day)'
160
- : tokenInfo.hasAppAccessToken
161
- ? 'app_access_token (1,000 req/day)'
162
- : 'none',
163
- },
164
- scopes: userTokens?.scope ? userTokens.scope.split(' ') : [],
165
- };
166
- }
@@ -1,100 +0,0 @@
1
- /**
2
- * OAuth 2.1 middleware for Express
3
- * Implements RFC 6750 Bearer Token authentication
4
- */
5
- import { getErrorMessage } from '../utils/errors.js';
6
- /**
7
- * Create Bearer token authentication middleware
8
- */
9
- export function createBearerAuthMiddleware(config) {
10
- const realm = config.realm || 'mcp';
11
- return async (req, res, next) => {
12
- try {
13
- // Extract token from Authorization header
14
- const authHeader = req.headers.authorization;
15
- if (!authHeader) {
16
- sendUnauthorized(res, realm, config.resourceMetadataUrl, {
17
- error: 'invalid_token',
18
- error_description: 'No authorization header provided',
19
- });
20
- return;
21
- }
22
- // Check Bearer scheme
23
- const parts = authHeader.split(' ');
24
- if (parts.length !== 2 || parts[0] !== 'Bearer') {
25
- sendUnauthorized(res, realm, config.resourceMetadataUrl, {
26
- error: 'invalid_token',
27
- error_description: 'Invalid authorization header format. Expected: Bearer <token>',
28
- });
29
- return;
30
- }
31
- const token = parts[1];
32
- // Verify token
33
- try {
34
- const verifiedToken = await config.verifier.verifyToken(token);
35
- req.auth = verifiedToken;
36
- next();
37
- }
38
- catch (error) {
39
- const errorMessage = getErrorMessage(error, 'Token verification failed');
40
- sendUnauthorized(res, realm, config.resourceMetadataUrl, {
41
- error: 'invalid_token',
42
- error_description: errorMessage,
43
- });
44
- }
45
- }
46
- catch (error) {
47
- console.error('OAuth middleware error:', error);
48
- res.status(500).json({
49
- error: 'server_error',
50
- error_description: 'Internal server error during authentication',
51
- });
52
- }
53
- };
54
- }
55
- /**
56
- * Send 401 Unauthorized response with RFC 6750 compliant WWW-Authenticate header
57
- */
58
- function sendUnauthorized(res, realm, resourceMetadataUrl, challenge) {
59
- // Build WWW-Authenticate header per RFC 6750
60
- let authenticateValue = `Bearer realm="${realm}", resource_metadata="${resourceMetadataUrl}"`;
61
- if (challenge.error) {
62
- authenticateValue += `, error="${challenge.error}"`;
63
- }
64
- if (challenge.error_description) {
65
- authenticateValue += `, error_description="${challenge.error_description}"`;
66
- }
67
- if (challenge.scope) {
68
- authenticateValue += `, scope="${challenge.scope}"`;
69
- }
70
- res.setHeader('WWW-Authenticate', authenticateValue);
71
- res.status(401).json({
72
- error: challenge.error || 'unauthorized',
73
- error_description: challenge.error_description || 'Authorization required',
74
- });
75
- }
76
- /**
77
- * Optional middleware to check specific scopes
78
- */
79
- export function requireScopes(requiredScopes) {
80
- return (req, res, next) => {
81
- if (!req.auth) {
82
- res.status(401).json({
83
- error: 'unauthorized',
84
- error_description: 'No authentication information found',
85
- });
86
- return;
87
- }
88
- const hasRequiredScopes = requiredScopes.every((scope) => req.auth.scopes.includes(scope));
89
- if (!hasRequiredScopes) {
90
- res.status(403).json({
91
- error: 'insufficient_scope',
92
- error_description: `Missing required scopes: ${requiredScopes.join(', ')}`,
93
- required_scopes: requiredScopes,
94
- provided_scopes: req.auth.scopes,
95
- });
96
- return;
97
- }
98
- next();
99
- };
100
- }
@@ -1,186 +0,0 @@
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 { getErrorMessage } from '../utils/errors.js';
7
- import { describeHttpError, httpRequest, isHttpError } from '../utils/http.js';
8
- /**
9
- * Verifies MCP Bearer tokens using OAuth introspection or JWT validation.
10
- */
11
- export class TokenVerifier {
12
- config;
13
- metadata = null;
14
- constructor(config) {
15
- this.config = config;
16
- }
17
- /**
18
- * Initialize the verifier by loading OAuth server metadata
19
- */
20
- async initialize() {
21
- if (typeof this.config.authServerMetadata === 'string') {
22
- try {
23
- const response = await httpRequest({
24
- url: this.config.authServerMetadata,
25
- });
26
- this.metadata = response.data;
27
- }
28
- catch (error) {
29
- throw new Error(`Failed to load OAuth server metadata: ${getErrorMessage(error)}`);
30
- }
31
- }
32
- else {
33
- this.metadata = this.config.authServerMetadata;
34
- }
35
- }
36
- /**
37
- * Verify an access token
38
- */
39
- async verifyToken(token) {
40
- if (!this.metadata) {
41
- throw new Error('Token verifier not initialized');
42
- }
43
- if (this.config.useIntrospection !== false) {
44
- return await this.verifyViaIntrospection(token);
45
- }
46
- else {
47
- return await this.verifyViaJWT(token);
48
- }
49
- }
50
- /**
51
- * Verify token using OAuth 2.0 Token Introspection (RFC 7662)
52
- */
53
- async verifyViaIntrospection(token) {
54
- if (!this.metadata) {
55
- throw new Error('Token verifier not initialized');
56
- }
57
- // Check if introspection endpoint is available
58
- const introspectionEndpoint = this.metadata.introspection_endpoint;
59
- if (!introspectionEndpoint) {
60
- throw new Error('Introspection endpoint not available in OAuth server metadata');
61
- }
62
- // Prepare introspection request
63
- const requestData = {
64
- token,
65
- token_type_hint: 'access_token',
66
- };
67
- // Add client credentials if provided
68
- const headers = {
69
- 'Content-Type': 'application/x-www-form-urlencoded',
70
- };
71
- const params = new URLSearchParams({
72
- token: requestData.token,
73
- });
74
- if (this.config.clientId) {
75
- params.set('client_id', this.config.clientId);
76
- }
77
- if (this.config.clientSecret) {
78
- params.set('client_secret', this.config.clientSecret);
79
- }
80
- // Make introspection request
81
- try {
82
- const response = await httpRequest({
83
- method: 'POST',
84
- url: introspectionEndpoint,
85
- body: params,
86
- headers,
87
- });
88
- const data = response.data;
89
- // Check if token is active
90
- if (!data.active) {
91
- throw new Error('Token is not active');
92
- }
93
- // Validate audience
94
- if (!this.validateAudience(data.aud)) {
95
- throw new Error(`Invalid audience. Expected: ${this.config.expectedAudience}, Got: ${data.aud}`);
96
- }
97
- // Validate scopes
98
- const scopes = data.scope ? data.scope.split(' ') : [];
99
- if (this.config.requiredScopes) {
100
- const hasRequiredScopes = this.config.requiredScopes.every((scope) => scopes.includes(scope));
101
- if (!hasRequiredScopes) {
102
- throw new Error(`Missing required scopes. Required: ${this.config.requiredScopes.join(', ')}, Got: ${scopes.join(', ')}`);
103
- }
104
- }
105
- return {
106
- token,
107
- clientId: data.client_id || 'unknown',
108
- scopes,
109
- expiresAt: data.exp,
110
- audience: data.aud,
111
- subject: data.sub,
112
- };
113
- }
114
- catch (error) {
115
- if (isHttpError(error)) {
116
- throw new Error(`Token introspection failed: ${describeHttpError(error)}`);
117
- }
118
- throw error;
119
- }
120
- }
121
- /**
122
- * Verify token using JWT validation
123
- */
124
- async verifyViaJWT(token) {
125
- if (!this.metadata) {
126
- throw new Error('Token verifier not initialized');
127
- }
128
- if (!this.metadata.jwks_uri) {
129
- throw new Error('JWKS URI not available in OAuth server metadata');
130
- }
131
- try {
132
- // Get JWKS from authorization server
133
- const JWKS = createRemoteJWKSet(new URL(this.metadata.jwks_uri));
134
- // Verify JWT
135
- const { payload } = await jwtVerify(token, JWKS, {
136
- issuer: this.metadata.issuer,
137
- audience: this.config.expectedAudience,
138
- });
139
- // Extract scopes
140
- const scopes = typeof payload.scope === 'string'
141
- ? payload.scope.split(' ')
142
- : Array.isArray(payload.scope)
143
- ? payload.scope
144
- : [];
145
- // Validate required scopes
146
- if (this.config.requiredScopes) {
147
- const hasRequiredScopes = this.config.requiredScopes.every((scope) => scopes.includes(scope));
148
- if (!hasRequiredScopes) {
149
- throw new Error(`Missing required scopes. Required: ${this.config.requiredScopes.join(', ')}, Got: ${scopes.join(', ')}`);
150
- }
151
- }
152
- const clientId = typeof payload.client_id === 'string'
153
- ? payload.client_id
154
- : typeof payload.azp === 'string'
155
- ? payload.azp
156
- : 'unknown';
157
- return {
158
- token,
159
- clientId,
160
- scopes,
161
- expiresAt: payload.exp,
162
- audience: payload.aud,
163
- subject: payload.sub,
164
- };
165
- }
166
- catch (error) {
167
- throw new Error(`JWT verification failed: ${getErrorMessage(error)}`);
168
- }
169
- }
170
- /**
171
- * Validate audience claim
172
- */
173
- validateAudience(audience) {
174
- if (!audience) {
175
- return false;
176
- }
177
- const audiences = Array.isArray(audience) ? audience : [audience];
178
- const normalizedExpected = this.config.expectedAudience.replace(/\/$/, '');
179
- return audiences.some((aud) => {
180
- const normalizedAud = aud.replace(/\/$/, '');
181
- return (normalizedAud === normalizedExpected ||
182
- normalizedAud === normalizedExpected + '/' ||
183
- normalizedExpected === normalizedAud + '/');
184
- });
185
- }
186
- }