-
Notifications
You must be signed in to change notification settings - Fork 14.2k
Expand file tree
/
Copy pathoauth-token-storage.ts
More file actions
255 lines (230 loc) · 7.13 KB
/
Copy pathoauth-token-storage.ts
File metadata and controls
255 lines (230 loc) · 7.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { coreEvents } from '../utils/events.js';
import { promises as fs } from 'node:fs';
import * as path from 'node:path';
import { Storage } from '../config/storage.js';
import { getErrorMessage } from '../utils/errors.js';
import type {
OAuthToken,
OAuthCredentials,
TokenStorage,
} from './token-storage/types.js';
import { HybridTokenStorage } from './token-storage/hybrid-token-storage.js';
import {
DEFAULT_SERVICE_NAME,
FORCE_ENCRYPTED_FILE_ENV_VAR,
} from './token-storage/index.js';
/**
* Class for managing OAuth token storage and retrieval.
* Used by both MCP and A2A OAuth providers. Pass a custom `tokenFilePath`
* to store tokens in a protocol-specific file.
*/
export class MCPOAuthTokenStorage implements TokenStorage {
private readonly hybridTokenStorage: HybridTokenStorage;
private readonly useEncryptedFile =
process.env[FORCE_ENCRYPTED_FILE_ENV_VAR] === 'true';
private readonly customTokenFilePath?: string;
constructor(
tokenFilePath?: string,
serviceName: string = DEFAULT_SERVICE_NAME,
) {
this.customTokenFilePath = tokenFilePath;
this.hybridTokenStorage = new HybridTokenStorage(serviceName);
}
/**
* Get the path to the token storage file.
*
* @returns The full path to the token storage file
*/
private getTokenFilePath(): string {
return this.customTokenFilePath ?? Storage.getMcpOAuthTokensPath();
}
/**
* Ensure the config directory exists.
*/
private async ensureConfigDir(): Promise<void> {
const configDir = path.dirname(this.getTokenFilePath());
await fs.mkdir(configDir, { recursive: true });
}
/**
* Load all stored MCP OAuth tokens.
*
* @returns A map of server names to credentials
*/
async getAllCredentials(): Promise<Map<string, OAuthCredentials>> {
if (this.useEncryptedFile) {
return this.hybridTokenStorage.getAllCredentials();
}
const tokenMap = new Map<string, OAuthCredentials>();
try {
const tokenFile = this.getTokenFilePath();
const data = await fs.readFile(tokenFile, 'utf-8');
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const tokens = JSON.parse(data) as OAuthCredentials[];
for (const credential of tokens) {
tokenMap.set(credential.serverName, credential);
}
} catch (error) {
// File doesn't exist or is invalid, return empty map
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
coreEvents.emitFeedback(
'error',
`Failed to load MCP OAuth tokens: ${getErrorMessage(error)}`,
error,
);
}
}
return tokenMap;
}
async listServers(): Promise<string[]> {
if (this.useEncryptedFile) {
return this.hybridTokenStorage.listServers();
}
const tokens = await this.getAllCredentials();
return Array.from(tokens.keys());
}
async setCredentials(credentials: OAuthCredentials): Promise<void> {
if (this.useEncryptedFile) {
return this.hybridTokenStorage.setCredentials(credentials);
}
const tokens = await this.getAllCredentials();
tokens.set(credentials.serverName, credentials);
const tokenArray = Array.from(tokens.values());
const tokenFile = this.getTokenFilePath();
try {
await fs.writeFile(
tokenFile,
JSON.stringify(tokenArray, null, 2),
{ mode: 0o600 }, // Restrict file permissions
);
} catch (error) {
coreEvents.emitFeedback(
'error',
`Failed to save MCP OAuth token: ${getErrorMessage(error)}`,
error,
);
throw error;
}
}
/**
* Save a token for a specific MCP server.
*
* @param serverName The name of the MCP server
* @param token The OAuth token to save
* @param clientId Optional client ID used for this token
* @param tokenUrl Optional token URL used for this token
* @param mcpServerUrl Optional MCP server URL
*/
async saveToken(
serverName: string,
token: OAuthToken,
clientId?: string,
tokenUrl?: string,
mcpServerUrl?: string,
): Promise<void> {
await this.ensureConfigDir();
const existing = await this.getCredentials(serverName);
const mergedRefreshToken =
token.refreshToken || existing?.token.refreshToken;
const mergedToken = {
...token,
refreshToken: mergedRefreshToken,
};
const credential: OAuthCredentials = {
serverName,
token: mergedToken,
clientId,
tokenUrl,
mcpServerUrl,
updatedAt: Date.now(),
};
if (this.useEncryptedFile) {
return this.hybridTokenStorage.setCredentials(credential);
}
await this.setCredentials(credential);
}
/**
* Get a token for a specific MCP server.
*
* @param serverName The name of the MCP server
* @returns The stored credentials or null if not found
*/
async getCredentials(serverName: string): Promise<OAuthCredentials | null> {
if (this.useEncryptedFile) {
return this.hybridTokenStorage.getCredentials(serverName);
}
const tokens = await this.getAllCredentials();
return tokens.get(serverName) || null;
}
/**
* Remove a token for a specific MCP server.
*
* @param serverName The name of the MCP server
*/
async deleteCredentials(serverName: string): Promise<void> {
if (this.useEncryptedFile) {
return this.hybridTokenStorage.deleteCredentials(serverName);
}
const tokens = await this.getAllCredentials();
if (tokens.delete(serverName)) {
const tokenArray = Array.from(tokens.values());
const tokenFile = this.getTokenFilePath();
try {
if (tokenArray.length === 0) {
// Remove file if no tokens left
await fs.unlink(tokenFile);
} else {
await fs.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), {
mode: 0o600,
});
}
} catch (error) {
coreEvents.emitFeedback(
'error',
`Failed to remove MCP OAuth token: ${getErrorMessage(error)}`,
error,
);
}
}
}
/**
* Check if a token is expired.
*
* @param token The token to check
* @returns True if the token is expired
*/
isTokenExpired(token: OAuthToken): boolean {
if (!token.expiresAt) {
return false; // No expiry, assume valid
}
// Add a 5-minute buffer to account for clock skew
const bufferMs = 5 * 60 * 1000;
return Date.now() + bufferMs >= token.expiresAt;
}
/**
* Clear all stored MCP OAuth tokens.
*/
async clearAll(): Promise<void> {
if (this.useEncryptedFile) {
return this.hybridTokenStorage.clearAll();
}
try {
const tokenFile = this.getTokenFilePath();
await fs.unlink(tokenFile);
} catch (error) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
coreEvents.emitFeedback(
'error',
`Failed to clear MCP OAuth tokens: ${getErrorMessage(error)}`,
error,
);
}
}
}
}