@mcp-z/oauth-microsoft 1.0.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 (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -0
  3. package/dist/cjs/index.d.cts +16 -0
  4. package/dist/cjs/index.d.ts +16 -0
  5. package/dist/cjs/index.js +112 -0
  6. package/dist/cjs/index.js.map +1 -0
  7. package/dist/cjs/lib/dcr-router.d.cts +44 -0
  8. package/dist/cjs/lib/dcr-router.d.ts +44 -0
  9. package/dist/cjs/lib/dcr-router.js +1227 -0
  10. package/dist/cjs/lib/dcr-router.js.map +1 -0
  11. package/dist/cjs/lib/dcr-utils.d.cts +160 -0
  12. package/dist/cjs/lib/dcr-utils.d.ts +160 -0
  13. package/dist/cjs/lib/dcr-utils.js +860 -0
  14. package/dist/cjs/lib/dcr-utils.js.map +1 -0
  15. package/dist/cjs/lib/dcr-verify.d.cts +53 -0
  16. package/dist/cjs/lib/dcr-verify.d.ts +53 -0
  17. package/dist/cjs/lib/dcr-verify.js +193 -0
  18. package/dist/cjs/lib/dcr-verify.js.map +1 -0
  19. package/dist/cjs/lib/fetch-with-timeout.d.cts +14 -0
  20. package/dist/cjs/lib/fetch-with-timeout.d.ts +14 -0
  21. package/dist/cjs/lib/fetch-with-timeout.js +257 -0
  22. package/dist/cjs/lib/fetch-with-timeout.js.map +1 -0
  23. package/dist/cjs/lib/token-verifier.d.cts +44 -0
  24. package/dist/cjs/lib/token-verifier.d.ts +44 -0
  25. package/dist/cjs/lib/token-verifier.js +253 -0
  26. package/dist/cjs/lib/token-verifier.js.map +1 -0
  27. package/dist/cjs/package.json +1 -0
  28. package/dist/cjs/providers/dcr.d.cts +110 -0
  29. package/dist/cjs/providers/dcr.d.ts +110 -0
  30. package/dist/cjs/providers/dcr.js +600 -0
  31. package/dist/cjs/providers/dcr.js.map +1 -0
  32. package/dist/cjs/providers/device-code.d.cts +179 -0
  33. package/dist/cjs/providers/device-code.d.ts +179 -0
  34. package/dist/cjs/providers/device-code.js +896 -0
  35. package/dist/cjs/providers/device-code.js.map +1 -0
  36. package/dist/cjs/providers/loopback-oauth.d.cts +125 -0
  37. package/dist/cjs/providers/loopback-oauth.d.ts +125 -0
  38. package/dist/cjs/providers/loopback-oauth.js +1325 -0
  39. package/dist/cjs/providers/loopback-oauth.js.map +1 -0
  40. package/dist/cjs/schemas/index.d.cts +20 -0
  41. package/dist/cjs/schemas/index.d.ts +20 -0
  42. package/dist/cjs/schemas/index.js +37 -0
  43. package/dist/cjs/schemas/index.js.map +1 -0
  44. package/dist/cjs/setup/config.d.cts +113 -0
  45. package/dist/cjs/setup/config.d.ts +113 -0
  46. package/dist/cjs/setup/config.js +246 -0
  47. package/dist/cjs/setup/config.js.map +1 -0
  48. package/dist/cjs/types.d.cts +188 -0
  49. package/dist/cjs/types.d.ts +188 -0
  50. package/dist/cjs/types.js +18 -0
  51. package/dist/cjs/types.js.map +1 -0
  52. package/dist/esm/index.d.ts +16 -0
  53. package/dist/esm/index.js +16 -0
  54. package/dist/esm/index.js.map +1 -0
  55. package/dist/esm/lib/dcr-router.d.ts +44 -0
  56. package/dist/esm/lib/dcr-router.js +556 -0
  57. package/dist/esm/lib/dcr-router.js.map +1 -0
  58. package/dist/esm/lib/dcr-utils.d.ts +160 -0
  59. package/dist/esm/lib/dcr-utils.js +270 -0
  60. package/dist/esm/lib/dcr-utils.js.map +1 -0
  61. package/dist/esm/lib/dcr-verify.d.ts +53 -0
  62. package/dist/esm/lib/dcr-verify.js +53 -0
  63. package/dist/esm/lib/dcr-verify.js.map +1 -0
  64. package/dist/esm/lib/fetch-with-timeout.d.ts +14 -0
  65. package/dist/esm/lib/fetch-with-timeout.js +30 -0
  66. package/dist/esm/lib/fetch-with-timeout.js.map +1 -0
  67. package/dist/esm/lib/token-verifier.d.ts +44 -0
  68. package/dist/esm/lib/token-verifier.js +53 -0
  69. package/dist/esm/lib/token-verifier.js.map +1 -0
  70. package/dist/esm/package.json +1 -0
  71. package/dist/esm/providers/dcr.d.ts +110 -0
  72. package/dist/esm/providers/dcr.js +235 -0
  73. package/dist/esm/providers/dcr.js.map +1 -0
  74. package/dist/esm/providers/device-code.d.ts +179 -0
  75. package/dist/esm/providers/device-code.js +417 -0
  76. package/dist/esm/providers/device-code.js.map +1 -0
  77. package/dist/esm/providers/loopback-oauth.d.ts +125 -0
  78. package/dist/esm/providers/loopback-oauth.js +643 -0
  79. package/dist/esm/providers/loopback-oauth.js.map +1 -0
  80. package/dist/esm/schemas/index.d.ts +20 -0
  81. package/dist/esm/schemas/index.js +18 -0
  82. package/dist/esm/schemas/index.js.map +1 -0
  83. package/dist/esm/setup/config.d.ts +113 -0
  84. package/dist/esm/setup/config.js +268 -0
  85. package/dist/esm/setup/config.js.map +1 -0
  86. package/dist/esm/types.d.ts +188 -0
  87. package/dist/esm/types.js +8 -0
  88. package/dist/esm/types.js.map +1 -0
  89. package/package.json +87 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/oauth/oauth-microsoft/src/lib/dcr-utils.ts"],"sourcesContent":["/**\n * DCR Storage Utilities\n *\n * Keyv-based storage utilities for Dynamic Client Registration.\n * Follows @mcp-z/oauth pattern: single Keyv store with compound keys.\n *\n * Key Patterns:\n * - dcr:client:{clientId} -> RegisteredClient\n * - dcr:provider:{dcrToken} -> ProviderTokens\n * - dcr:authcode:{code} -> AuthorizationCode\n * - dcr:access:{token} -> AccessToken\n * - dcr:refresh:{token} -> AccessToken\n */\n\nimport type { DcrClientInformation, DcrClientMetadata, ProviderTokens } from '@mcp-z/oauth';\nimport { randomUUID } from 'crypto';\nimport type { Keyv } from 'keyv';\nimport type { AccessToken, AuthorizationCode, RegisteredClient } from '../types.ts';\n\n// ============================================================================\n// Client Operations\n// ============================================================================\n\n/**\n * Register a new OAuth client (RFC 7591 Section 3.1)\n *\n * @param store - Keyv store for all DCR data\n * @param metadata - Client registration metadata\n * @returns Registered client with credentials\n * @throws Error if validation fails\n */\nexport async function registerClient(store: Keyv, metadata: DcrClientMetadata): Promise<DcrClientInformation> {\n // Validate redirect URIs (required per RFC 7591)\n if (!metadata.redirect_uris || metadata.redirect_uris.length === 0) {\n throw new Error('redirect_uris is required');\n }\n\n // Generate client credentials\n const client_id = `dcr_${randomUUID()}`;\n const client_secret = randomUUID();\n\n // Default grant types and response types per RFC 7591 Section 2\n const grant_types = metadata.grant_types ?? ['authorization_code', 'refresh_token'];\n const response_types = metadata.response_types ?? ['code'];\n\n // Build registered client - only include optional fields if they have values\n const client: RegisteredClient = {\n client_id,\n client_secret,\n client_id_issued_at: Math.floor(Date.now() / 1000),\n client_secret_expires_at: 0, // Never expires\n redirect_uris: metadata.redirect_uris,\n token_endpoint_auth_method: metadata.token_endpoint_auth_method ?? 'client_secret_basic',\n grant_types,\n response_types,\n ...(metadata.client_name !== undefined && { client_name: metadata.client_name }),\n ...(metadata.client_uri !== undefined && { client_uri: metadata.client_uri }),\n ...(metadata.logo_uri !== undefined && { logo_uri: metadata.logo_uri }),\n ...(metadata.scope !== undefined && { scope: metadata.scope }),\n ...(metadata.contacts !== undefined && { contacts: metadata.contacts }),\n ...(metadata.tos_uri !== undefined && { tos_uri: metadata.tos_uri }),\n ...(metadata.policy_uri !== undefined && { policy_uri: metadata.policy_uri }),\n ...(metadata.jwks_uri !== undefined && { jwks_uri: metadata.jwks_uri }),\n ...(metadata.jwks !== undefined && { jwks: metadata.jwks }),\n ...(metadata.software_id !== undefined && { software_id: metadata.software_id }),\n ...(metadata.software_version !== undefined && { software_version: metadata.software_version }),\n created_at: Date.now(),\n };\n\n // Store client\n await store.set(`dcr:client:${client_id}`, client);\n\n // Return client information (excluding internal created_at)\n const { created_at, ...clientInfo } = client;\n return clientInfo;\n}\n\n/**\n * Get a registered client by ID\n *\n * @param store - Keyv store for all DCR data\n * @param clientId - Client identifier\n * @returns Registered client or undefined if not found\n */\nexport async function getClient(store: Keyv, clientId: string): Promise<RegisteredClient | undefined> {\n return await store.get(`dcr:client:${clientId}`);\n}\n\n/**\n * Validate client credentials\n *\n * @param store - Keyv store for all DCR data\n * @param clientId - Client identifier\n * @param clientSecret - Client secret\n * @returns True if credentials are valid\n */\nexport async function validateClient(store: Keyv, clientId: string, clientSecret: string): Promise<boolean> {\n const client = await getClient(store, clientId);\n if (!client) return false;\n return client.client_secret === clientSecret;\n}\n\n/**\n * Validate redirect URI for a client\n *\n * @param store - Keyv store for all DCR data\n * @param clientId - Client identifier\n * @param redirectUri - Redirect URI to validate\n * @returns True if redirect URI is registered\n */\nexport async function validateRedirectUri(store: Keyv, clientId: string, redirectUri: string): Promise<boolean> {\n const client = await getClient(store, clientId);\n if (!client || !client.redirect_uris) return false;\n return client.redirect_uris.includes(redirectUri);\n}\n\n/**\n * List all registered clients (for debugging)\n *\n * Note: This method uses Keyv's iterator which may not be available on all storage adapters.\n * For production use, consider maintaining a separate index of client IDs.\n *\n * @param store - Keyv store for all DCR data\n * @returns Array of all registered clients\n */\nexport async function listClients(store: Keyv): Promise<RegisteredClient[]> {\n const clients: RegisteredClient[] = [];\n\n // Check if iterator is available on the store\n if (store.iterator) {\n // Use iterator with namespace to iterate through dcr:client: keys\n const iterator = store.iterator('dcr:client:');\n for await (const [_key, value] of iterator) {\n if (value !== undefined) {\n clients.push(value as RegisteredClient);\n }\n }\n }\n\n return clients;\n}\n\n/**\n * Delete a registered client\n *\n * @param store - Keyv store for all DCR data\n * @param clientId - Client identifier\n */\nexport async function deleteClient(store: Keyv, clientId: string): Promise<void> {\n await store.delete(`dcr:client:${clientId}`);\n}\n\n// ============================================================================\n// Provider Token Operations\n// ============================================================================\n\n/**\n * Store provider tokens for a DCR access token\n *\n * @param store - Keyv store for all DCR data\n * @param dcrToken - DCR-issued access token (used as key)\n * @param tokens - Microsoft provider tokens (access, refresh, expiry)\n */\nexport async function setProviderTokens(store: Keyv, dcrToken: string, tokens: ProviderTokens): Promise<void> {\n await store.set(`dcr:provider:${dcrToken}`, tokens);\n}\n\n/**\n * Retrieve provider tokens for a DCR access token\n *\n * @param store - Keyv store for all DCR data\n * @param dcrToken - DCR-issued access token\n * @returns Provider tokens or undefined if not found\n */\nexport async function getProviderTokens(store: Keyv, dcrToken: string): Promise<ProviderTokens | undefined> {\n return await store.get(`dcr:provider:${dcrToken}`);\n}\n\n/**\n * Delete provider tokens for a DCR access token\n *\n * @param store - Keyv store for all DCR data\n * @param dcrToken - DCR-issued access token\n */\nexport async function deleteProviderTokens(store: Keyv, dcrToken: string): Promise<void> {\n await store.delete(`dcr:provider:${dcrToken}`);\n}\n\n// ============================================================================\n// Authorization Code Operations\n// ============================================================================\n\n/**\n * Store an authorization code\n *\n * @param store - Keyv store for all DCR data\n * @param code - Authorization code\n * @param authCode - Authorization code data\n */\nexport async function setAuthCode(store: Keyv, code: string, authCode: AuthorizationCode): Promise<void> {\n await store.set(`dcr:authcode:${code}`, authCode);\n}\n\n/**\n * Get an authorization code\n *\n * @param store - Keyv store for all DCR data\n * @param code - Authorization code\n * @returns Authorization code data or undefined if not found\n */\nexport async function getAuthCode(store: Keyv, code: string): Promise<AuthorizationCode | undefined> {\n return await store.get(`dcr:authcode:${code}`);\n}\n\n/**\n * Delete an authorization code\n *\n * @param store - Keyv store for all DCR data\n * @param code - Authorization code\n */\nexport async function deleteAuthCode(store: Keyv, code: string): Promise<void> {\n await store.delete(`dcr:authcode:${code}`);\n}\n\n// ============================================================================\n// Access Token Operations\n// ============================================================================\n\n/**\n * Store an access token\n *\n * @param store - Keyv store for all DCR data\n * @param token - Access token\n * @param tokenData - Access token data\n */\nexport async function setAccessToken(store: Keyv, token: string, tokenData: AccessToken): Promise<void> {\n await store.set(`dcr:access:${token}`, tokenData);\n}\n\n/**\n * Get an access token\n *\n * @param store - Keyv store for all DCR data\n * @param token - Access token\n * @returns Access token data or undefined if not found\n */\nexport async function getAccessToken(store: Keyv, token: string): Promise<AccessToken | undefined> {\n return await store.get(`dcr:access:${token}`);\n}\n\n/**\n * Delete an access token\n *\n * @param store - Keyv store for all DCR data\n * @param token - Access token\n */\nexport async function deleteAccessToken(store: Keyv, token: string): Promise<void> {\n await store.delete(`dcr:access:${token}`);\n}\n\n// ============================================================================\n// Refresh Token Operations\n// ============================================================================\n\n/**\n * Store a refresh token\n *\n * @param store - Keyv store for all DCR data\n * @param token - Refresh token\n * @param tokenData - Access token data (contains refresh token context)\n */\nexport async function setRefreshToken(store: Keyv, token: string, tokenData: AccessToken): Promise<void> {\n await store.set(`dcr:refresh:${token}`, tokenData);\n}\n\n/**\n * Get a refresh token\n *\n * @param store - Keyv store for all DCR data\n * @param token - Refresh token\n * @returns Access token data or undefined if not found\n */\nexport async function getRefreshToken(store: Keyv, token: string): Promise<AccessToken | undefined> {\n return await store.get(`dcr:refresh:${token}`);\n}\n\n/**\n * Delete a refresh token\n *\n * @param store - Keyv store for all DCR data\n * @param token - Refresh token\n */\nexport async function deleteRefreshToken(store: Keyv, token: string): Promise<void> {\n await store.delete(`dcr:refresh:${token}`);\n}\n"],"names":["deleteAccessToken","deleteAuthCode","deleteClient","deleteProviderTokens","deleteRefreshToken","getAccessToken","getAuthCode","getClient","getProviderTokens","getRefreshToken","listClients","registerClient","setAccessToken","setAuthCode","setProviderTokens","setRefreshToken","validateClient","validateRedirectUri","store","metadata","client_id","client_secret","grant_types","response_types","client","created_at","clientInfo","redirect_uris","length","Error","randomUUID","client_id_issued_at","Math","floor","Date","now","client_secret_expires_at","token_endpoint_auth_method","client_name","undefined","client_uri","logo_uri","scope","contacts","tos_uri","policy_uri","jwks_uri","jwks","software_id","software_version","set","clientId","get","clientSecret","redirectUri","includes","clients","iterator","_key","value","push","delete","dcrToken","tokens","code","authCode","token","tokenData"],"mappings":"AAAA;;;;;;;;;;;;CAYC;;;;;;;;;;;QAoPqBA;eAAAA;;QApCAC;eAAAA;;QAxEAC;eAAAA;;QAoCAC;eAAAA;;QA4GAC;eAAAA;;QA9CAC;eAAAA;;QApCAC;eAAAA;;QA9HAC;eAAAA;;QA0FAC;e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;;oBAAtC;;wBAAO;;;;IACT;;AAQO,SAAe9D,mBAAmBc,KAAW,EAAEgD,KAAa;;;;;oBACjE;;wBAAMhD,MAAM2C,MAAM,CAAC,AAAC,eAAoB,OAANK;;;oBAAlC;;;;;;IACF"}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * DCR Token Verification Utilities
3
+ *
4
+ * Provides token verification for both self-hosted and external DCR modes:
5
+ * - Self-hosted: Verifies tokens against local DCR router (/oauth/verify)
6
+ * - External: Verifies tokens against Auth0/Stitch verification endpoint
7
+ */
8
+ import type { ProviderTokens } from '@mcp-z/oauth';
9
+ /**
10
+ * Verification result from DCR authorization server
11
+ */
12
+ export interface VerificationResult {
13
+ /** Bearer token that was verified */
14
+ token: string;
15
+ /** Client ID associated with the token */
16
+ clientId: string;
17
+ /** OAuth scopes granted to the token */
18
+ scopes: string[];
19
+ /** Token expiration timestamp (milliseconds since epoch) */
20
+ expiresAt: number;
21
+ /** Provider tokens (Microsoft access/refresh tokens) */
22
+ providerTokens: ProviderTokens;
23
+ }
24
+ /**
25
+ * Verify bearer token against DCR authorization server
26
+ *
27
+ * Supports both self-hosted and external DCR modes by calling the
28
+ * /oauth/verify endpoint (or equivalent external URL).
29
+ *
30
+ * @param bearerToken - Bearer token to verify (without "Bearer " prefix)
31
+ * @param verifyUrl - Verification endpoint URL (self-hosted or external)
32
+ * @returns Verification result with provider tokens
33
+ * @throws Error if verification fails
34
+ *
35
+ * @example Self-hosted mode
36
+ * ```typescript
37
+ * const result = await verifyBearerToken(
38
+ * token,
39
+ * 'http://localhost:3456/oauth/verify'
40
+ * );
41
+ * const auth = provider.toAuthProvider(result.providerTokens);
42
+ * ```
43
+ *
44
+ * @example External mode (Auth0/Stitch)
45
+ * ```typescript
46
+ * const result = await verifyBearerToken(
47
+ * token,
48
+ * 'https://auth.example.com/oauth/verify'
49
+ * );
50
+ * const auth = provider.toAuthProvider(result.providerTokens);
51
+ * ```
52
+ */
53
+ export declare function verifyBearerToken(bearerToken: string, verifyUrl: string): Promise<VerificationResult>;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * DCR Token Verification Utilities
3
+ *
4
+ * Provides token verification for both self-hosted and external DCR modes:
5
+ * - Self-hosted: Verifies tokens against local DCR router (/oauth/verify)
6
+ * - External: Verifies tokens against Auth0/Stitch verification endpoint
7
+ */
8
+ import type { ProviderTokens } from '@mcp-z/oauth';
9
+ /**
10
+ * Verification result from DCR authorization server
11
+ */
12
+ export interface VerificationResult {
13
+ /** Bearer token that was verified */
14
+ token: string;
15
+ /** Client ID associated with the token */
16
+ clientId: string;
17
+ /** OAuth scopes granted to the token */
18
+ scopes: string[];
19
+ /** Token expiration timestamp (milliseconds since epoch) */
20
+ expiresAt: number;
21
+ /** Provider tokens (Microsoft access/refresh tokens) */
22
+ providerTokens: ProviderTokens;
23
+ }
24
+ /**
25
+ * Verify bearer token against DCR authorization server
26
+ *
27
+ * Supports both self-hosted and external DCR modes by calling the
28
+ * /oauth/verify endpoint (or equivalent external URL).
29
+ *
30
+ * @param bearerToken - Bearer token to verify (without "Bearer " prefix)
31
+ * @param verifyUrl - Verification endpoint URL (self-hosted or external)
32
+ * @returns Verification result with provider tokens
33
+ * @throws Error if verification fails
34
+ *
35
+ * @example Self-hosted mode
36
+ * ```typescript
37
+ * const result = await verifyBearerToken(
38
+ * token,
39
+ * 'http://localhost:3456/oauth/verify'
40
+ * );
41
+ * const auth = provider.toAuthProvider(result.providerTokens);
42
+ * ```
43
+ *
44
+ * @example External mode (Auth0/Stitch)
45
+ * ```typescript
46
+ * const result = await verifyBearerToken(
47
+ * token,
48
+ * 'https://auth.example.com/oauth/verify'
49
+ * );
50
+ * const auth = provider.toAuthProvider(result.providerTokens);
51
+ * ```
52
+ */
53
+ export declare function verifyBearerToken(bearerToken: string, verifyUrl: string): Promise<VerificationResult>;
@@ -0,0 +1,193 @@
1
+ /**
2
+ * DCR Token Verification Utilities
3
+ *
4
+ * Provides token verification for both self-hosted and external DCR modes:
5
+ * - Self-hosted: Verifies tokens against local DCR router (/oauth/verify)
6
+ * - External: Verifies tokens against Auth0/Stitch verification endpoint
7
+ */ "use strict";
8
+ Object.defineProperty(exports, "__esModule", {
9
+ value: true
10
+ });
11
+ Object.defineProperty(exports, "verifyBearerToken", {
12
+ enumerable: true,
13
+ get: function() {
14
+ return verifyBearerToken;
15
+ }
16
+ });
17
+ var _fetchwithtimeoutts = require("./fetch-with-timeout.js");
18
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
19
+ try {
20
+ var info = gen[key](arg);
21
+ var value = info.value;
22
+ } catch (error) {
23
+ reject(error);
24
+ return;
25
+ }
26
+ if (info.done) {
27
+ resolve(value);
28
+ } else {
29
+ Promise.resolve(value).then(_next, _throw);
30
+ }
31
+ }
32
+ function _async_to_generator(fn) {
33
+ return function() {
34
+ var self = this, args = arguments;
35
+ return new Promise(function(resolve, reject) {
36
+ var gen = fn.apply(self, args);
37
+ function _next(value) {
38
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
39
+ }
40
+ function _throw(err) {
41
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
42
+ }
43
+ _next(undefined);
44
+ });
45
+ };
46
+ }
47
+ function _ts_generator(thisArg, body) {
48
+ var f, y, t, _ = {
49
+ label: 0,
50
+ sent: function() {
51
+ if (t[0] & 1) throw t[1];
52
+ return t[1];
53
+ },
54
+ trys: [],
55
+ ops: []
56
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
57
+ return d(g, "next", {
58
+ value: verb(0)
59
+ }), d(g, "throw", {
60
+ value: verb(1)
61
+ }), d(g, "return", {
62
+ value: verb(2)
63
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
64
+ value: function() {
65
+ return this;
66
+ }
67
+ }), g;
68
+ function verb(n) {
69
+ return function(v) {
70
+ return step([
71
+ n,
72
+ v
73
+ ]);
74
+ };
75
+ }
76
+ function step(op) {
77
+ if (f) throw new TypeError("Generator is already executing.");
78
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
79
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
80
+ if (y = 0, t) op = [
81
+ op[0] & 2,
82
+ t.value
83
+ ];
84
+ switch(op[0]){
85
+ case 0:
86
+ case 1:
87
+ t = op;
88
+ break;
89
+ case 4:
90
+ _.label++;
91
+ return {
92
+ value: op[1],
93
+ done: false
94
+ };
95
+ case 5:
96
+ _.label++;
97
+ y = op[1];
98
+ op = [
99
+ 0
100
+ ];
101
+ continue;
102
+ case 7:
103
+ op = _.ops.pop();
104
+ _.trys.pop();
105
+ continue;
106
+ default:
107
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
108
+ _ = 0;
109
+ continue;
110
+ }
111
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
112
+ _.label = op[1];
113
+ break;
114
+ }
115
+ if (op[0] === 6 && _.label < t[1]) {
116
+ _.label = t[1];
117
+ t = op;
118
+ break;
119
+ }
120
+ if (t && _.label < t[2]) {
121
+ _.label = t[2];
122
+ _.ops.push(op);
123
+ break;
124
+ }
125
+ if (t[2]) _.ops.pop();
126
+ _.trys.pop();
127
+ continue;
128
+ }
129
+ op = body.call(thisArg, _);
130
+ } catch (e) {
131
+ op = [
132
+ 6,
133
+ e
134
+ ];
135
+ y = 0;
136
+ } finally{
137
+ f = t = 0;
138
+ }
139
+ if (op[0] & 5) throw op[1];
140
+ return {
141
+ value: op[0] ? op[1] : void 0,
142
+ done: true
143
+ };
144
+ }
145
+ }
146
+ function verifyBearerToken(bearerToken, verifyUrl) {
147
+ return _async_to_generator(function() {
148
+ var response, errorText, result;
149
+ return _ts_generator(this, function(_state) {
150
+ switch(_state.label){
151
+ case 0:
152
+ return [
153
+ 4,
154
+ (0, _fetchwithtimeoutts.fetchWithTimeout)(verifyUrl, {
155
+ method: 'GET',
156
+ headers: {
157
+ Authorization: "Bearer ".concat(bearerToken)
158
+ }
159
+ })
160
+ ];
161
+ case 1:
162
+ response = _state.sent();
163
+ if (!!response.ok) return [
164
+ 3,
165
+ 3
166
+ ];
167
+ return [
168
+ 4,
169
+ response.text()
170
+ ];
171
+ case 2:
172
+ errorText = _state.sent();
173
+ throw new Error("Token verification failed: ".concat(response.status, " ").concat(errorText));
174
+ case 3:
175
+ return [
176
+ 4,
177
+ response.json()
178
+ ];
179
+ case 4:
180
+ result = _state.sent();
181
+ // Validate required fields
182
+ if (!result.providerTokens || !result.providerTokens.accessToken) {
183
+ throw new Error('Verification response missing required provider tokens');
184
+ }
185
+ return [
186
+ 2,
187
+ result
188
+ ];
189
+ }
190
+ });
191
+ })();
192
+ }
193
+ /* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/oauth/oauth-microsoft/src/lib/dcr-verify.ts"],"sourcesContent":["/**\n * DCR Token Verification Utilities\n *\n * Provides token verification for both self-hosted and external DCR modes:\n * - Self-hosted: Verifies tokens against local DCR router (/oauth/verify)\n * - External: Verifies tokens against Auth0/Stitch verification endpoint\n */\n\nimport type { ProviderTokens } from '@mcp-z/oauth';\nimport { fetchWithTimeout } from './fetch-with-timeout.ts';\n\n/**\n * Verification result from DCR authorization server\n */\nexport interface VerificationResult {\n /** Bearer token that was verified */\n token: string;\n /** Client ID associated with the token */\n clientId: string;\n /** OAuth scopes granted to the token */\n scopes: string[];\n /** Token expiration timestamp (milliseconds since epoch) */\n expiresAt: number;\n /** Provider tokens (Microsoft access/refresh tokens) */\n providerTokens: ProviderTokens;\n}\n\n/**\n * Verify bearer token against DCR authorization server\n *\n * Supports both self-hosted and external DCR modes by calling the\n * /oauth/verify endpoint (or equivalent external URL).\n *\n * @param bearerToken - Bearer token to verify (without \"Bearer \" prefix)\n * @param verifyUrl - Verification endpoint URL (self-hosted or external)\n * @returns Verification result with provider tokens\n * @throws Error if verification fails\n *\n * @example Self-hosted mode\n * ```typescript\n * const result = await verifyBearerToken(\n * token,\n * 'http://localhost:3456/oauth/verify'\n * );\n * const auth = provider.toAuthProvider(result.providerTokens);\n * ```\n *\n * @example External mode (Auth0/Stitch)\n * ```typescript\n * const result = await verifyBearerToken(\n * token,\n * 'https://auth.example.com/oauth/verify'\n * );\n * const auth = provider.toAuthProvider(result.providerTokens);\n * ```\n */\nexport async function verifyBearerToken(bearerToken: string, verifyUrl: string): Promise<VerificationResult> {\n const response = await fetchWithTimeout(verifyUrl, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Token verification failed: ${response.status} ${errorText}`);\n }\n\n const result = (await response.json()) as VerificationResult;\n\n // Validate required fields\n if (!result.providerTokens || !result.providerTokens.accessToken) {\n throw new Error('Verification response missing required provider tokens');\n }\n\n return result;\n}\n"],"names":["verifyBearerToken","bearerToken","verifyUrl","response","errorText","result","fetchWithTimeout","method","headers","Authorization","ok","text","Error","status","json","providerTokens","accessToken"],"mappings":"AAAA;;;;;;CAMC;;;;+BAkDqBA;;;eAAAA;;;kCA/CW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+C1B,SAAeA,kBAAkBC,WAAmB,EAAEC,SAAiB;;YACtEC,UAQEC,WAIFC;;;;oBAZW;;wBAAMC,IAAAA,oCAAgB,EAACJ,WAAW;4BACjDK,QAAQ;4BACRC,SAAS;gCACPC,eAAe,AAAC,UAAqB,OAAZR;4BAC3B;wBACF;;;oBALME,WAAW;yBAOb,CAACA,SAASO,EAAE,EAAZ;;;;oBACgB;;wBAAMP,SAASQ,IAAI;;;oBAA/BP,YAAY;oBAClB,MAAM,IAAIQ,MAAM,AAAC,8BAAgDR,OAAnBD,SAASU,MAAM,EAAC,KAAa,OAAVT;;oBAGnD;;wBAAMD,SAASW,IAAI;;;oBAA7BT,SAAU;oBAEhB,2BAA2B;oBAC3B,IAAI,CAACA,OAAOU,cAAc,IAAI,CAACV,OAAOU,cAAc,CAACC,WAAW,EAAE;wBAChE,MAAM,IAAIJ,MAAM;oBAClB;oBAEA;;wBAAOP;;;;IACT"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Fetch with timeout to prevent hanging requests
3
+ *
4
+ * This utility wraps the native fetch API with an AbortController to ensure
5
+ * requests don't hang indefinitely. This is critical for OAuth token operations
6
+ * where expired tokens might cause Microsoft's servers to hang or respond slowly.
7
+ *
8
+ * @param url - URL to fetch
9
+ * @param options - Fetch options
10
+ * @param timeoutMs - Timeout in milliseconds (default: 30000)
11
+ * @returns Fetch response
12
+ * @throws Error if request times out
13
+ */
14
+ export declare function fetchWithTimeout(url: string, options?: RequestInit, timeoutMs?: number): Promise<Response>;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Fetch with timeout to prevent hanging requests
3
+ *
4
+ * This utility wraps the native fetch API with an AbortController to ensure
5
+ * requests don't hang indefinitely. This is critical for OAuth token operations
6
+ * where expired tokens might cause Microsoft's servers to hang or respond slowly.
7
+ *
8
+ * @param url - URL to fetch
9
+ * @param options - Fetch options
10
+ * @param timeoutMs - Timeout in milliseconds (default: 30000)
11
+ * @returns Fetch response
12
+ * @throws Error if request times out
13
+ */
14
+ export declare function fetchWithTimeout(url: string, options?: RequestInit, timeoutMs?: number): Promise<Response>;
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Fetch with timeout to prevent hanging requests
3
+ *
4
+ * This utility wraps the native fetch API with an AbortController to ensure
5
+ * requests don't hang indefinitely. This is critical for OAuth token operations
6
+ * where expired tokens might cause Microsoft's servers to hang or respond slowly.
7
+ *
8
+ * @param url - URL to fetch
9
+ * @param options - Fetch options
10
+ * @param timeoutMs - Timeout in milliseconds (default: 30000)
11
+ * @returns Fetch response
12
+ * @throws Error if request times out
13
+ */ "use strict";
14
+ Object.defineProperty(exports, "__esModule", {
15
+ value: true
16
+ });
17
+ Object.defineProperty(exports, "fetchWithTimeout", {
18
+ enumerable: true,
19
+ get: function() {
20
+ return fetchWithTimeout;
21
+ }
22
+ });
23
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
24
+ try {
25
+ var info = gen[key](arg);
26
+ var value = info.value;
27
+ } catch (error) {
28
+ reject(error);
29
+ return;
30
+ }
31
+ if (info.done) {
32
+ resolve(value);
33
+ } else {
34
+ Promise.resolve(value).then(_next, _throw);
35
+ }
36
+ }
37
+ function _async_to_generator(fn) {
38
+ return function() {
39
+ var self = this, args = arguments;
40
+ return new Promise(function(resolve, reject) {
41
+ var gen = fn.apply(self, args);
42
+ function _next(value) {
43
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
44
+ }
45
+ function _throw(err) {
46
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
47
+ }
48
+ _next(undefined);
49
+ });
50
+ };
51
+ }
52
+ function _define_property(obj, key, value) {
53
+ if (key in obj) {
54
+ Object.defineProperty(obj, key, {
55
+ value: value,
56
+ enumerable: true,
57
+ configurable: true,
58
+ writable: true
59
+ });
60
+ } else {
61
+ obj[key] = value;
62
+ }
63
+ return obj;
64
+ }
65
+ function _instanceof(left, right) {
66
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
67
+ return !!right[Symbol.hasInstance](left);
68
+ } else {
69
+ return left instanceof right;
70
+ }
71
+ }
72
+ function _object_spread(target) {
73
+ for(var i = 1; i < arguments.length; i++){
74
+ var source = arguments[i] != null ? arguments[i] : {};
75
+ var ownKeys = Object.keys(source);
76
+ if (typeof Object.getOwnPropertySymbols === "function") {
77
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
78
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
79
+ }));
80
+ }
81
+ ownKeys.forEach(function(key) {
82
+ _define_property(target, key, source[key]);
83
+ });
84
+ }
85
+ return target;
86
+ }
87
+ function ownKeys(object, enumerableOnly) {
88
+ var keys = Object.keys(object);
89
+ if (Object.getOwnPropertySymbols) {
90
+ var symbols = Object.getOwnPropertySymbols(object);
91
+ if (enumerableOnly) {
92
+ symbols = symbols.filter(function(sym) {
93
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
94
+ });
95
+ }
96
+ keys.push.apply(keys, symbols);
97
+ }
98
+ return keys;
99
+ }
100
+ function _object_spread_props(target, source) {
101
+ source = source != null ? source : {};
102
+ if (Object.getOwnPropertyDescriptors) {
103
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
104
+ } else {
105
+ ownKeys(Object(source)).forEach(function(key) {
106
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
107
+ });
108
+ }
109
+ return target;
110
+ }
111
+ function _ts_generator(thisArg, body) {
112
+ var f, y, t, _ = {
113
+ label: 0,
114
+ sent: function() {
115
+ if (t[0] & 1) throw t[1];
116
+ return t[1];
117
+ },
118
+ trys: [],
119
+ ops: []
120
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
121
+ return d(g, "next", {
122
+ value: verb(0)
123
+ }), d(g, "throw", {
124
+ value: verb(1)
125
+ }), d(g, "return", {
126
+ value: verb(2)
127
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
128
+ value: function() {
129
+ return this;
130
+ }
131
+ }), g;
132
+ function verb(n) {
133
+ return function(v) {
134
+ return step([
135
+ n,
136
+ v
137
+ ]);
138
+ };
139
+ }
140
+ function step(op) {
141
+ if (f) throw new TypeError("Generator is already executing.");
142
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
143
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
144
+ if (y = 0, t) op = [
145
+ op[0] & 2,
146
+ t.value
147
+ ];
148
+ switch(op[0]){
149
+ case 0:
150
+ case 1:
151
+ t = op;
152
+ break;
153
+ case 4:
154
+ _.label++;
155
+ return {
156
+ value: op[1],
157
+ done: false
158
+ };
159
+ case 5:
160
+ _.label++;
161
+ y = op[1];
162
+ op = [
163
+ 0
164
+ ];
165
+ continue;
166
+ case 7:
167
+ op = _.ops.pop();
168
+ _.trys.pop();
169
+ continue;
170
+ default:
171
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
172
+ _ = 0;
173
+ continue;
174
+ }
175
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
176
+ _.label = op[1];
177
+ break;
178
+ }
179
+ if (op[0] === 6 && _.label < t[1]) {
180
+ _.label = t[1];
181
+ t = op;
182
+ break;
183
+ }
184
+ if (t && _.label < t[2]) {
185
+ _.label = t[2];
186
+ _.ops.push(op);
187
+ break;
188
+ }
189
+ if (t[2]) _.ops.pop();
190
+ _.trys.pop();
191
+ continue;
192
+ }
193
+ op = body.call(thisArg, _);
194
+ } catch (e) {
195
+ op = [
196
+ 6,
197
+ e
198
+ ];
199
+ y = 0;
200
+ } finally{
201
+ f = t = 0;
202
+ }
203
+ if (op[0] & 5) throw op[1];
204
+ return {
205
+ value: op[0] ? op[1] : void 0,
206
+ done: true
207
+ };
208
+ }
209
+ }
210
+ function fetchWithTimeout(url, options) {
211
+ var timeoutMs = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 30000;
212
+ return _async_to_generator(function() {
213
+ var controller, timeoutId, response, error;
214
+ return _ts_generator(this, function(_state) {
215
+ switch(_state.label){
216
+ case 0:
217
+ controller = new AbortController();
218
+ timeoutId = setTimeout(function() {
219
+ return controller.abort();
220
+ }, timeoutMs);
221
+ _state.label = 1;
222
+ case 1:
223
+ _state.trys.push([
224
+ 1,
225
+ 3,
226
+ ,
227
+ 4
228
+ ]);
229
+ return [
230
+ 4,
231
+ fetch(url, _object_spread_props(_object_spread({}, options), {
232
+ signal: controller.signal
233
+ }))
234
+ ];
235
+ case 2:
236
+ response = _state.sent();
237
+ clearTimeout(timeoutId);
238
+ return [
239
+ 2,
240
+ response
241
+ ];
242
+ case 3:
243
+ error = _state.sent();
244
+ clearTimeout(timeoutId);
245
+ if (_instanceof(error, Error) && error.name === 'AbortError') {
246
+ throw new Error("Request timeout after ".concat(timeoutMs, "ms"));
247
+ }
248
+ throw error;
249
+ case 4:
250
+ return [
251
+ 2
252
+ ];
253
+ }
254
+ });
255
+ })();
256
+ }
257
+ /* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/oauth/oauth-microsoft/src/lib/fetch-with-timeout.ts"],"sourcesContent":["/**\n * Fetch with timeout to prevent hanging requests\n *\n * This utility wraps the native fetch API with an AbortController to ensure\n * requests don't hang indefinitely. This is critical for OAuth token operations\n * where expired tokens might cause Microsoft's servers to hang or respond slowly.\n *\n * @param url - URL to fetch\n * @param options - Fetch options\n * @param timeoutMs - Timeout in milliseconds (default: 30000)\n * @returns Fetch response\n * @throws Error if request times out\n */\nexport async function fetchWithTimeout(url: string, options?: RequestInit, timeoutMs = 30000): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`Request timeout after ${timeoutMs}ms`);\n }\n throw error;\n }\n}\n"],"names":["fetchWithTimeout","url","options","timeoutMs","controller","timeoutId","response","error","AbortController","setTimeout","abort","fetch","signal","clearTimeout","Error","name"],"mappings":"AAAA;;;;;;;;;;;;CAYC;;;;+BACqBA;;;eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAf,SAAeA,iBAAiBC,GAAW,EAAEC,OAAqB;QAAEC,YAAAA,iEAAY;;YAC/EC,YACAC,WAGEC,UAMCC;;;;oBAVHH,aAAa,IAAII;oBACjBH,YAAYI,WAAW;+BAAML,WAAWM,KAAK;uBAAIP;;;;;;;;;oBAGpC;;wBAAMQ,MAAMV,KAAK,wCAC7BC;4BACHU,QAAQR,WAAWQ,MAAM;;;;oBAFrBN,WAAW;oBAIjBO,aAAaR;oBACb;;wBAAOC;;;oBACAC;oBACPM,aAAaR;oBACb,IAAIE,AAAK,YAALA,OAAiBO,UAASP,MAAMQ,IAAI,KAAK,cAAc;wBACzD,MAAM,IAAID,MAAM,AAAC,yBAAkC,OAAVX,WAAU;oBACrD;oBACA,MAAMI;;;;;;;IAEV"}