strands-darwin 0.0.44 → 0.0.47

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 (110) hide show
  1. package/README.md +7 -2
  2. package/README.zh-CN.md +7 -2
  3. package/dist/patches/ink+7.1.1.patch +15 -0
  4. package/dist/src/agent/context-breakdown.d.ts +26 -3
  5. package/dist/src/agent/context-breakdown.js +27 -1
  6. package/dist/src/agent/context-breakdown.js.map +1 -1
  7. package/dist/src/agent/goal-check.d.ts +35 -0
  8. package/dist/src/agent/goal-check.js +132 -0
  9. package/dist/src/agent/goal-check.js.map +1 -0
  10. package/dist/src/agent/model-retry.d.ts +6 -1
  11. package/dist/src/agent/model-retry.js +45 -9
  12. package/dist/src/agent/model-retry.js.map +1 -1
  13. package/dist/src/agent/permission-rules.d.ts +31 -13
  14. package/dist/src/agent/permission-rules.js +180 -20
  15. package/dist/src/agent/permission-rules.js.map +1 -1
  16. package/dist/src/agent/permission.d.ts +0 -6
  17. package/dist/src/agent/permission.js +23 -5
  18. package/dist/src/agent/permission.js.map +1 -1
  19. package/dist/src/agent/runtime.d.ts +44 -1
  20. package/dist/src/agent/runtime.js +91 -6
  21. package/dist/src/agent/runtime.js.map +1 -1
  22. package/dist/src/agent/safety-classifier.d.ts +3 -1
  23. package/dist/src/agent/safety-classifier.js +0 -0
  24. package/dist/src/agent/safety-classifier.js.map +1 -1
  25. package/dist/src/agent/working-context.d.ts +16 -0
  26. package/dist/src/agent/working-context.js +20 -0
  27. package/dist/src/agent/working-context.js.map +1 -1
  28. package/dist/src/cli-completion.d.ts +13 -0
  29. package/dist/src/cli-completion.js +161 -0
  30. package/dist/src/cli-completion.js.map +1 -0
  31. package/dist/src/cli-main.js +3 -1
  32. package/dist/src/cli-main.js.map +1 -1
  33. package/dist/src/cli-mcp.d.ts +12 -0
  34. package/dist/src/cli-mcp.js +111 -0
  35. package/dist/src/cli-mcp.js.map +1 -0
  36. package/dist/src/cli-usage.d.ts +1 -1
  37. package/dist/src/cli-usage.js +3 -0
  38. package/dist/src/cli-usage.js.map +1 -1
  39. package/dist/src/cli.js +9 -1
  40. package/dist/src/cli.js.map +1 -1
  41. package/dist/src/collaboration/command.js +1 -1
  42. package/dist/src/collaboration/command.js.map +1 -1
  43. package/dist/src/collaboration/local.d.ts +137 -6
  44. package/dist/src/collaboration/local.js +76 -19
  45. package/dist/src/collaboration/local.js.map +1 -1
  46. package/dist/src/collaboration/tools.js +1 -1
  47. package/dist/src/collaboration/tools.js.map +1 -1
  48. package/dist/src/commands/custom-commands.d.ts +8 -1
  49. package/dist/src/commands/custom-commands.js +23 -1
  50. package/dist/src/commands/custom-commands.js.map +1 -1
  51. package/dist/src/commands/goal-command.d.ts +26 -0
  52. package/dist/src/commands/goal-command.js +32 -0
  53. package/dist/src/commands/goal-command.js.map +1 -0
  54. package/dist/src/config.d.ts +3 -5
  55. package/dist/src/config.js.map +1 -1
  56. package/dist/src/dev-repl.js +4 -1
  57. package/dist/src/dev-repl.js.map +1 -1
  58. package/dist/src/headless-protocol.d.ts +1 -1
  59. package/dist/src/headless-protocol.js +5 -0
  60. package/dist/src/headless-protocol.js.map +1 -1
  61. package/dist/src/headless-runner.js +5 -0
  62. package/dist/src/headless-runner.js.map +1 -1
  63. package/dist/src/headless.js +5 -0
  64. package/dist/src/headless.js.map +1 -1
  65. package/dist/src/mcp/oauth-login.d.ts +37 -0
  66. package/dist/src/mcp/oauth-login.js +263 -0
  67. package/dist/src/mcp/oauth-login.js.map +1 -0
  68. package/dist/src/mcp/oauth-net.d.ts +50 -0
  69. package/dist/src/mcp/oauth-net.js +321 -0
  70. package/dist/src/mcp/oauth-net.js.map +1 -0
  71. package/dist/src/mcp/oauth-provider.d.ts +89 -0
  72. package/dist/src/mcp/oauth-provider.js +398 -0
  73. package/dist/src/mcp/oauth-provider.js.map +1 -0
  74. package/dist/src/mcp/oauth-store.d.ts +49 -0
  75. package/dist/src/mcp/oauth-store.js +176 -0
  76. package/dist/src/mcp/oauth-store.js.map +1 -0
  77. package/dist/src/mcp/prompts.d.ts +179 -0
  78. package/dist/src/mcp/prompts.js +349 -0
  79. package/dist/src/mcp/prompts.js.map +1 -0
  80. package/dist/src/mcp/registry.d.ts +14 -1
  81. package/dist/src/mcp/registry.js +86 -5
  82. package/dist/src/mcp/registry.js.map +1 -1
  83. package/dist/src/tools/shell-env.d.ts +27 -1
  84. package/dist/src/tools/shell-env.js +34 -5
  85. package/dist/src/tools/shell-env.js.map +1 -1
  86. package/dist/src/tui/App.d.ts +4 -1
  87. package/dist/src/tui/App.js +394 -20
  88. package/dist/src/tui/App.js.map +1 -1
  89. package/dist/src/tui/InputBox.d.ts +8 -2
  90. package/dist/src/tui/InputBox.js +6 -4
  91. package/dist/src/tui/InputBox.js.map +1 -1
  92. package/dist/src/tui/context-format.d.ts +7 -3
  93. package/dist/src/tui/context-format.js +28 -3
  94. package/dist/src/tui/context-format.js.map +1 -1
  95. package/dist/src/tui/external-editor.d.ts +143 -0
  96. package/dist/src/tui/external-editor.js +482 -0
  97. package/dist/src/tui/external-editor.js.map +1 -0
  98. package/dist/src/tui/goal.d.ts +123 -0
  99. package/dist/src/tui/goal.js +187 -0
  100. package/dist/src/tui/goal.js.map +1 -0
  101. package/dist/src/tui/help-format.d.ts +1 -1
  102. package/dist/src/tui/help-format.js +3 -3
  103. package/dist/src/tui/help-format.js.map +1 -1
  104. package/dist/src/tui/mcp-format.d.ts +2 -0
  105. package/dist/src/tui/mcp-format.js +27 -1
  106. package/dist/src/tui/mcp-format.js.map +1 -1
  107. package/dist/src/tui/prompt-editor.d.ts +10 -3
  108. package/dist/src/tui/prompt-editor.js +18 -3
  109. package/dist/src/tui/prompt-editor.js.map +1 -1
  110. package/package.json +1 -1
@@ -0,0 +1,398 @@
1
+ /**
2
+ * MCP OAuth for remote servers (SER-107): the SDK `OAuthClientProvider` darwin hands to
3
+ * `McpClientConfig.authProvider`, and the per-server settings that opt a server into it.
4
+ *
5
+ * The flow itself — discovery, dynamic registration, PKCE, code exchange, refresh — is the MCP
6
+ * SDK's own `auth()`; this file only supplies what the SDK asks a provider for, and draws the
7
+ * boundary around it. The provider runs in two modes that share one class so they cannot drift:
8
+ *
9
+ * - `login` (`darwin mcp login`): interactive, in memory until the login completes, every request
10
+ * through the guarded fetch, the authorization URL handed to a callback (the browser).
11
+ * - `runtime` (a normal session): non-interactive, backed by the stored record. It has no way to
12
+ * open a browser or register a client; when a 401 needs a fresh login it raises
13
+ * {@link McpLoginRequiredError} (or no-ops the redirect, which the transport turns into an
14
+ * `UnauthorizedError`), records `loginRequired`, and the `/mcp` report says which command to run.
15
+ * With no stored login it does not even start discovery — a session that has never logged in
16
+ * makes no request to any authorization server.
17
+ *
18
+ * Endpoints are checked where they enter (`saveDiscoveryState`, `redirectToAuthorization`) and
19
+ * where they are used (`addClientAuthentication`, before every token request), so a discovery
20
+ * document cannot steer darwin to a private address or a different origin. Tokens flow only
21
+ * between the SDK, this class and the store; nothing here logs them.
22
+ */
23
+ import { randomBytes } from 'node:crypto';
24
+ import { ConfigError } from '../config.js';
25
+ import { OAuthPolicyError, assertHostResolvesPublic, isPrivateLiteralHost, validateOAuthUrl, } from './oauth-net.js';
26
+ import { deleteOAuthRecord, newLoginId, readOAuthRecord, writeOAuthRecord, } from './oauth-store.js';
27
+ /** Longest access/refresh token darwin will hold or store. */
28
+ const MAX_TOKEN_LENGTH = 16 * 1024;
29
+ /** Raised inside a session when a server needs `darwin mcp login`; the message is the guidance. */
30
+ export class McpLoginRequiredError extends Error {
31
+ constructor(server, detail) {
32
+ super(`MCP server "${server}" requires authentication${detail === undefined ? '' : ` (${detail})`}: run \`darwin mcp login ${server}\``);
33
+ this.name = 'McpLoginRequiredError';
34
+ }
35
+ }
36
+ const OAUTH_KEYS = new Set(['scope', 'clientId', 'callbackPort', 'allowPrivateNetwork']);
37
+ function interpolateEnv(value) {
38
+ return value.replace(/\$\{(?:env:)?([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, key) => {
39
+ const resolved = process.env[key];
40
+ if (resolved === undefined)
41
+ throw new Error(`environment variable "${key}" is not set`);
42
+ return resolved;
43
+ });
44
+ }
45
+ /**
46
+ * Reads the `oauth` key of a server entry: `undefined` when the server has none (or `false`), the
47
+ * settings when it has a valid one, {@link ConfigError} when the entry asks for OAuth but cannot
48
+ * have it. A typo in a credential setting should stop startup rather than hide a server.
49
+ */
50
+ export function resolveOAuthSettings(name, entry) {
51
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry))
52
+ return undefined;
53
+ const record = entry;
54
+ const option = record['oauth'];
55
+ if (option === undefined || option === false)
56
+ return undefined;
57
+ const fail = (message) => {
58
+ throw new ConfigError(`MCP server "${name}": oauth ${message}`);
59
+ };
60
+ if (option !== true && (typeof option !== 'object' || option === null || Array.isArray(option))) {
61
+ return fail('must be true or an object such as { "scope": "…" }');
62
+ }
63
+ const options = option === true ? {} : option;
64
+ for (const key of Object.keys(options))
65
+ if (!OAUTH_KEYS.has(key))
66
+ fail(`has an unknown key "${key}" (allowed: ${[...OAUTH_KEYS].join(', ')})`);
67
+ if (typeof record['url'] !== 'string' || record['url'] === '')
68
+ return fail('needs a "url" (remote streamable-http servers only)');
69
+ if (record['command'] !== undefined)
70
+ fail('cannot be combined with "command" (stdio servers have no OAuth)');
71
+ if (record['transport'] !== undefined && record['transport'] !== 'streamable-http')
72
+ fail('supports only the streamable-http transport');
73
+ if (record['auth'] !== undefined)
74
+ fail('cannot be combined with "auth" (static client credentials); pick one');
75
+ const headers = record['headers'];
76
+ if (typeof headers === 'object' && headers !== null && Object.keys(headers).some((key) => key.toLowerCase() === 'authorization')) {
77
+ fail('cannot be combined with an Authorization header; pick one');
78
+ }
79
+ const scope = options['scope'];
80
+ if (scope !== undefined && (typeof scope !== 'string' || scope.length > 256 || /[\u0000-\u001f\u007f"\\]/.test(scope))) {
81
+ fail('"scope" must be a short plain string');
82
+ }
83
+ const clientId = options['clientId'];
84
+ if (clientId !== undefined && (typeof clientId !== 'string' || clientId === '' || clientId.length > 256 || /[\u0000-\u001f\u007f]/.test(clientId))) {
85
+ fail('"clientId" must be a short plain string');
86
+ }
87
+ const callbackPort = options['callbackPort'];
88
+ if (callbackPort !== undefined && (!Number.isInteger(callbackPort) || callbackPort < 1024 || callbackPort > 65535)) {
89
+ fail('"callbackPort" must be an integer from 1024 to 65535');
90
+ }
91
+ const allowPrivateNetwork = options['allowPrivateNetwork'];
92
+ if (allowPrivateNetwork !== undefined && typeof allowPrivateNetwork !== 'boolean')
93
+ fail('"allowPrivateNetwork" must be true or false');
94
+ let serverUrl;
95
+ try {
96
+ serverUrl = new URL(interpolateEnv(record['url']));
97
+ }
98
+ catch (error) {
99
+ return fail(`server URL is unusable: ${error instanceof Error ? error.message : String(error)}`);
100
+ }
101
+ const allowPrivate = allowPrivateNetwork === true || isPrivateLiteralHost(serverUrl.hostname);
102
+ try {
103
+ validateOAuthUrl(serverUrl, 'MCP server URL', { allowPrivate });
104
+ }
105
+ catch (error) {
106
+ return fail(error instanceof Error ? error.message : String(error));
107
+ }
108
+ return {
109
+ name,
110
+ serverUrl,
111
+ allowPrivate,
112
+ ...(scope === undefined ? {} : { scope: scope }),
113
+ ...(clientId === undefined ? {} : { clientId: clientId }),
114
+ ...(callbackPort === undefined ? {} : { callbackPort: callbackPort }),
115
+ };
116
+ }
117
+ /**
118
+ * Vets a discovery document: the authorization server and each endpoint it names must pass the
119
+ * URL policy and share the authorization server's origin, its `issuer` must be that origin, and
120
+ * any protected-resource metadata must describe this MCP server's origin. Throws
121
+ * {@link OAuthPolicyError}.
122
+ */
123
+ export function validateDiscoveryState(state, settings) {
124
+ const context = { allowPrivate: settings.allowPrivate };
125
+ const server = validateOAuthUrl(state.authorizationServerUrl, 'authorization server', context);
126
+ const metadata = state.authorizationServerMetadata;
127
+ if (metadata !== undefined) {
128
+ if (typeof metadata.issuer === 'string' && new URL(metadata.issuer).origin !== server.origin) {
129
+ throw new OAuthPolicyError('authorization server metadata: issuer does not match the authorization server origin');
130
+ }
131
+ const endpoints = {
132
+ authorization_endpoint: metadata.authorization_endpoint,
133
+ token_endpoint: metadata.token_endpoint,
134
+ registration_endpoint: metadata.registration_endpoint,
135
+ };
136
+ for (const [key, value] of Object.entries(endpoints)) {
137
+ if (value === undefined)
138
+ continue;
139
+ if (typeof value !== 'string')
140
+ throw new OAuthPolicyError(`authorization server metadata: ${key} is not a URL`);
141
+ if (validateOAuthUrl(value, key, context).origin !== server.origin) {
142
+ throw new OAuthPolicyError(`authorization server metadata: ${key} is on a different origin than the authorization server`);
143
+ }
144
+ }
145
+ }
146
+ const resource = state.resourceMetadata?.resource;
147
+ if (resource !== undefined && validateOAuthUrl(resource, 'protected resource', context).origin !== settings.serverUrl.origin) {
148
+ throw new OAuthPolicyError('protected resource metadata describes a different origin than the MCP server');
149
+ }
150
+ if (state.resourceMetadataUrl !== undefined && validateOAuthUrl(state.resourceMetadataUrl, 'resource metadata URL', context).origin !== settings.serverUrl.origin) {
151
+ throw new OAuthPolicyError('resource metadata URL is on a different origin than the MCP server');
152
+ }
153
+ }
154
+ function assertUsableTokens(tokens) {
155
+ if (tokens.token_type.toLowerCase() !== 'bearer')
156
+ throw new OAuthPolicyError('token response: only Bearer tokens are supported');
157
+ if (tokens.access_token.length > MAX_TOKEN_LENGTH || (tokens.refresh_token?.length ?? 0) > MAX_TOKEN_LENGTH) {
158
+ throw new OAuthPolicyError('token response: token is unreasonably long');
159
+ }
160
+ }
161
+ export class DarwinOAuthProvider {
162
+ settings;
163
+ mode;
164
+ /** Set when a session request needed a login this process cannot perform. */
165
+ loginRequired = false;
166
+ redirect;
167
+ onAuthorizationUrl;
168
+ record;
169
+ recordProblem;
170
+ client;
171
+ tokenState;
172
+ discovery;
173
+ verifier;
174
+ stateValue;
175
+ constructor(options) {
176
+ this.settings = options.settings;
177
+ this.mode = options.mode;
178
+ this.redirect = options.redirectUrl;
179
+ this.onAuthorizationUrl = options.onAuthorizationUrl;
180
+ this.record = options.record;
181
+ this.recordProblem = options.recordProblem;
182
+ if (options.record !== undefined) {
183
+ this.client = options.record.clientInformation;
184
+ this.tokenState = options.record.tokens;
185
+ }
186
+ }
187
+ /** What `/mcp` may say: never a token, never a timestamp of one. */
188
+ authStatus() {
189
+ if (this.loginRequired)
190
+ return 'login-required';
191
+ return this.tokenState === undefined ? 'not-logged-in' : 'logged-in';
192
+ }
193
+ get redirectUrl() {
194
+ return this.redirect ?? this.record?.redirectUrl ?? 'http://127.0.0.1/callback';
195
+ }
196
+ get clientMetadata() {
197
+ return {
198
+ client_name: 'darwin',
199
+ redirect_uris: [this.redirectUrl],
200
+ grant_types: ['authorization_code', 'refresh_token'],
201
+ response_types: ['code'],
202
+ token_endpoint_auth_method: 'none',
203
+ ...(this.settings.scope === undefined ? {} : { scope: this.settings.scope }),
204
+ };
205
+ }
206
+ /** The `state` value of the authorization request this provider issued (login mode). */
207
+ get expectedState() {
208
+ return this.stateValue;
209
+ }
210
+ state() {
211
+ this.stateValue = randomBytes(32).toString('base64url');
212
+ return this.stateValue;
213
+ }
214
+ clientInformation() {
215
+ const known = this.client ?? (this.settings.clientId === undefined ? undefined : { client_id: this.settings.clientId });
216
+ if (known === undefined && this.mode === 'runtime') {
217
+ // Registering a client is part of logging in, never something a session does on its own.
218
+ this.loginRequired = true;
219
+ throw new McpLoginRequiredError(this.settings.name);
220
+ }
221
+ return known;
222
+ }
223
+ saveClientInformation(info) {
224
+ if (this.mode === 'runtime')
225
+ return;
226
+ this.client = info;
227
+ }
228
+ tokens() {
229
+ return this.tokenState;
230
+ }
231
+ async saveTokens(tokens) {
232
+ assertUsableTokens(tokens);
233
+ const merged = {
234
+ ...tokens,
235
+ ...(tokens.refresh_token === undefined && this.tokenState?.refresh_token !== undefined
236
+ ? { refresh_token: this.tokenState.refresh_token }
237
+ : {}),
238
+ };
239
+ this.tokenState = merged;
240
+ this.loginRequired = false;
241
+ if (this.mode === 'login' || this.record === undefined)
242
+ return;
243
+ // A session refresh must never clobber a login someone completed in another terminal since.
244
+ const current = await readOAuthRecord(this.settings.name, this.settings.serverUrl.href);
245
+ // Only the login that produced the record may rewrite it: a logout (absent), a newer login, a
246
+ // record for another URL or a damaged file are all someone else's state.
247
+ if (current.status !== 'ok' || current.record.loginId !== this.record.loginId)
248
+ return;
249
+ this.record = { ...this.record, tokens: merged, savedAt: new Date().toISOString() };
250
+ await writeOAuthRecord(this.record);
251
+ }
252
+ async redirectToAuthorization(url) {
253
+ if (this.mode === 'runtime') {
254
+ // The transport turns "auth() returned REDIRECT" into an UnauthorizedError. Nothing opens.
255
+ this.loginRequired = true;
256
+ return;
257
+ }
258
+ const context = { allowPrivate: this.settings.allowPrivate };
259
+ const target = validateOAuthUrl(url, 'authorization URL', context);
260
+ const expected = this.discovery?.authorizationServerMetadata?.authorization_endpoint ?? this.discovery?.authorizationServerUrl;
261
+ if (expected !== undefined && new URL(expected).origin !== target.origin) {
262
+ throw new OAuthPolicyError('authorization URL is on a different origin than the authorization server');
263
+ }
264
+ if (target.searchParams.get('redirect_uri') !== this.redirectUrl || !target.searchParams.has('client_id')) {
265
+ throw new OAuthPolicyError('authorization URL does not carry darwin\'s client id and loopback redirect URI');
266
+ }
267
+ await this.onAuthorizationUrl?.(target);
268
+ }
269
+ saveCodeVerifier(codeVerifier) {
270
+ if (this.mode === 'login')
271
+ this.verifier = codeVerifier;
272
+ }
273
+ codeVerifier() {
274
+ if (this.verifier === undefined)
275
+ throw new Error('no PKCE code verifier is saved for this login');
276
+ return this.verifier;
277
+ }
278
+ saveDiscoveryState(state) {
279
+ validateDiscoveryState(state, this.settings);
280
+ // A session already holds the stored (and re-validated) state; only a login keeps a new one.
281
+ if (this.mode === 'login')
282
+ this.discovery = state;
283
+ }
284
+ discoveryState() {
285
+ if (this.mode === 'login')
286
+ return this.discovery;
287
+ if (this.record === undefined) {
288
+ this.loginRequired = true;
289
+ throw new McpLoginRequiredError(this.settings.name, this.recordProblem === 'mismatch' ? 'the stored login is for a different server URL' : this.recordProblem === 'invalid' ? 'the stored login is unreadable' : undefined);
290
+ }
291
+ const stored = this.record.discovery;
292
+ if (stored.resourceMetadata !== undefined || stored.resourceIndicator)
293
+ return stored;
294
+ // No protected-resource metadata at login: a stub keeps the SDK from fetching any at request time.
295
+ const stub = { resource: this.settings.serverUrl.href };
296
+ return { ...stored, resourceMetadata: stub };
297
+ }
298
+ async validateResourceURL(_defaultResource, resource) {
299
+ if (resource === undefined)
300
+ return undefined;
301
+ if (this.mode === 'runtime' && this.record?.discovery.resourceIndicator === false)
302
+ return undefined;
303
+ const url = validateOAuthUrl(resource, 'protected resource', { allowPrivate: this.settings.allowPrivate });
304
+ if (url.origin !== this.settings.serverUrl.origin) {
305
+ throw new OAuthPolicyError('protected resource is on a different origin than the MCP server');
306
+ }
307
+ return url;
308
+ }
309
+ /** Before every token request: re-vet the endpoint (and its DNS), then authenticate as the client. */
310
+ addClientAuthentication = async (headers, params, url, metadata) => {
311
+ const context = { allowPrivate: this.settings.allowPrivate };
312
+ const target = validateOAuthUrl(url, 'token endpoint', context);
313
+ const base = this.discovery?.authorizationServerUrl ?? this.record?.discovery.authorizationServerUrl;
314
+ if (base !== undefined && new URL(base).origin !== target.origin) {
315
+ throw new OAuthPolicyError('token endpoint is on a different origin than the authorization server');
316
+ }
317
+ await assertHostResolvesPublic(target.hostname, context);
318
+ const client = this.clientInformation();
319
+ if (client === undefined)
320
+ throw new Error('no OAuth client information for the token request');
321
+ const secret = client.client_secret;
322
+ if (secret === undefined) {
323
+ params.set('client_id', client.client_id);
324
+ return;
325
+ }
326
+ const methods = metadata?.token_endpoint_auth_methods_supported ?? [];
327
+ if (methods.includes('client_secret_post') && !methods.includes('client_secret_basic')) {
328
+ params.set('client_id', client.client_id);
329
+ params.set('client_secret', secret);
330
+ }
331
+ else {
332
+ headers.set('Authorization', `Basic ${Buffer.from(`${encodeURIComponent(client.client_id)}:${encodeURIComponent(secret)}`).toString('base64')}`);
333
+ }
334
+ };
335
+ async invalidateCredentials(scope) {
336
+ if (scope === 'verifier') {
337
+ this.verifier = undefined;
338
+ return;
339
+ }
340
+ if (scope === 'tokens' || scope === 'all') {
341
+ this.tokenState = undefined;
342
+ this.loginRequired = this.mode === 'runtime';
343
+ }
344
+ if (scope === 'client' || scope === 'all')
345
+ this.client = undefined;
346
+ if (this.mode !== 'runtime' || this.record === undefined)
347
+ return;
348
+ const current = await readOAuthRecord(this.settings.name, this.settings.serverUrl.href);
349
+ if (current.status !== 'ok' || current.record.loginId !== this.record.loginId)
350
+ return;
351
+ if (scope === 'all') {
352
+ await deleteOAuthRecord(this.settings.name);
353
+ return;
354
+ }
355
+ const { tokens: _dropped, clientInformation: _client, ...rest } = this.record;
356
+ this.record = {
357
+ ...rest,
358
+ ...(this.client === undefined ? {} : { clientInformation: this.client }),
359
+ ...(this.tokenState === undefined ? {} : { tokens: this.tokenState }),
360
+ };
361
+ await writeOAuthRecord(this.record);
362
+ }
363
+ /** Login mode: the record the finished login stores. Throws if the login has no tokens yet. */
364
+ buildRecord() {
365
+ if (this.tokenState === undefined || this.discovery === undefined)
366
+ throw new Error('login is not complete');
367
+ const stored = { ...this.discovery, resourceIndicator: this.discovery.resourceMetadata !== undefined };
368
+ return {
369
+ version: 1,
370
+ server: this.settings.name,
371
+ serverUrl: this.settings.serverUrl.href,
372
+ loginId: newLoginId(),
373
+ savedAt: new Date().toISOString(),
374
+ redirectUrl: this.redirectUrl,
375
+ ...(this.client === undefined ? {} : { clientInformation: this.client }),
376
+ tokens: this.tokenState,
377
+ discovery: stored,
378
+ };
379
+ }
380
+ }
381
+ /**
382
+ * The provider a session attaches to an OAuth-configured server: reads the stored login once (the
383
+ * only token-store read a session makes, and only for servers that are armed and opted in).
384
+ */
385
+ export async function createRuntimeOAuthProvider(settings) {
386
+ const read = await readOAuthRecord(settings.name, settings.serverUrl.href);
387
+ if (read.status === 'ok') {
388
+ try {
389
+ validateDiscoveryState(read.record.discovery, settings);
390
+ return new DarwinOAuthProvider({ settings, mode: 'runtime', record: read.record });
391
+ }
392
+ catch {
393
+ return new DarwinOAuthProvider({ settings, mode: 'runtime', recordProblem: 'invalid' });
394
+ }
395
+ }
396
+ return new DarwinOAuthProvider({ settings, mode: 'runtime', recordProblem: read.status });
397
+ }
398
+ //# sourceMappingURL=oauth-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-provider.js","sourceRoot":"","sources":["../../../src/mcp/oauth-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAU1C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,oBAAoB,EACpB,gBAAgB,GACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,iBAAiB,EACjB,UAAU,EACV,eAAe,EACf,gBAAgB,GAGjB,MAAM,kBAAkB,CAAC;AAE1B,8DAA8D;AAC9D,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,CAAC;AAEnC,mGAAmG;AACnG,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAC9C,YAAY,MAAc,EAAE,MAAe;QACzC,KAAK,CAAC,eAAe,MAAM,4BAA4B,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,MAAM,GAAG,4BAA4B,MAAM,IAAI,CAAC,CAAC;QACzI,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAC;IACtC,CAAC;CACF;AAgBD,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,qBAAqB,CAAC,CAAC,CAAC;AAEzF,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,OAAO,CAAC,0CAA0C,EAAE,CAAC,CAAC,EAAE,GAAW,EAAE,EAAE;QAClF,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI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C,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,iBAAiB,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;YACxE,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,SAAS,EAAE,MAAM;SAClB,CAAC;IACJ,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAAC,QAA6B;IAC5E,MAAM,IAAI,GAAG,MAAM,eAAe,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAC3E,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QACzB,IAAI,CAAC;YACH,sBAAsB,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;YACxD,OAAO,IAAI,mBAAmB,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;QACrF,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,IAAI,mBAAmB,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,aAAa,EAAE,SAAS,EAAE,CAAC,CAAC;QAC1F,CAAC;IACH,CAAC;IACD,OAAO,IAAI,mBAAmB,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,aAAa,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;AAC5F,CAAC"}
@@ -0,0 +1,49 @@
1
+ import type { OAuthDiscoveryState } from '@modelcontextprotocol/sdk/client/auth.js';
2
+ import type { OAuthClientInformationMixed, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
3
+ export declare const OAUTH_STORE_DIRNAME = "mcp-auth";
4
+ /** Largest record read or written. Real records are a few KiB. */
5
+ export declare const MAX_OAUTH_RECORD_BYTES: number;
6
+ export interface OAuthStoredDiscovery extends OAuthDiscoveryState {
7
+ /**
8
+ * Whether token requests carry the RFC 8707 `resource` parameter: true only when the server
9
+ * published protected-resource metadata. Kept so a runtime refresh repeats the login exactly.
10
+ */
11
+ resourceIndicator: boolean;
12
+ }
13
+ export interface OAuthRecord {
14
+ version: 1;
15
+ /** The config server name this record belongs to. */
16
+ server: string;
17
+ /** The exact (interpolated) MCP server URL the token was issued for. */
18
+ serverUrl: string;
19
+ /** Random id of the login that produced the record; a runtime refresh never overwrites a newer login. */
20
+ loginId: string;
21
+ savedAt: string;
22
+ /** The loopback redirect URI registered at login. */
23
+ redirectUrl: string;
24
+ clientInformation?: OAuthClientInformationMixed;
25
+ tokens?: OAuthTokens;
26
+ discovery: OAuthStoredDiscovery;
27
+ }
28
+ export type OAuthRecordRead = {
29
+ status: 'ok';
30
+ record: OAuthRecord;
31
+ } | {
32
+ status: 'absent';
33
+ }
34
+ /** A record exists for this server name but was issued for a different URL. */
35
+ | {
36
+ status: 'mismatch';
37
+ } | {
38
+ status: 'invalid';
39
+ problem: string;
40
+ };
41
+ export declare function oauthStoreDir(): string;
42
+ export declare function oauthRecordPath(server: string): string;
43
+ export declare function newLoginId(): string;
44
+ /** Reads one server's record, bound to `serverUrl`. Never throws; a bad file is `invalid`. */
45
+ export declare function readOAuthRecord(server: string, serverUrl: string): Promise<OAuthRecordRead>;
46
+ /** Atomically replaces the server's record with `0600` permissions inside a `0700` directory. */
47
+ export declare function writeOAuthRecord(record: OAuthRecord): Promise<void>;
48
+ /** Removes the server's record. Returns whether a file was removed. */
49
+ export declare function deleteOAuthRecord(server: string): Promise<boolean>;
@@ -0,0 +1,176 @@
1
+ /**
2
+ * The per-server OAuth token store (SER-107): `~/.darwin/mcp-auth/<server>-<hash>.json`, one
3
+ * private file per MCP server name.
4
+ *
5
+ * This is darwin-owned credential state, so its rules are strict and few. The directory is
6
+ * `0700` and each file `0600`, written by exclusive-create of a temp file plus rename so a crash
7
+ * never leaves half a token; reads refuse symlinks and non-regular files and are size-capped. A
8
+ * record is bound to the exact MCP server URL it was issued for: a same-named server that now
9
+ * points elsewhere (a project config that changed, an override) reads as "not logged in" — never
10
+ * as the old server's token — so a token cannot follow a name to a different origin. Nothing in
11
+ * this module logs, and no caller is given a path to print next to a value: the only strings that
12
+ * leave it are file paths and fixed problem descriptions.
13
+ */
14
+ import { createHash, randomBytes } from 'node:crypto';
15
+ import { constants as fsConstants } from 'node:fs';
16
+ import { lstat, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
17
+ import path from 'node:path';
18
+ import { OAuthClientInformationSchema, OAuthTokensSchema } from '@modelcontextprotocol/sdk/shared/auth.js';
19
+ import { userDarwinDir } from '../paths.js';
20
+ export const OAUTH_STORE_DIRNAME = 'mcp-auth';
21
+ /** Largest record read or written. Real records are a few KiB. */
22
+ export const MAX_OAUTH_RECORD_BYTES = 64 * 1024;
23
+ export function oauthStoreDir() {
24
+ return path.join(userDarwinDir(), OAUTH_STORE_DIRNAME);
25
+ }
26
+ export function oauthRecordPath(server) {
27
+ const slug = server.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 48) || 'server';
28
+ const hash = createHash('sha256').update(server).digest('hex').slice(0, 10);
29
+ return path.join(oauthStoreDir(), `${slug}-${hash}.json`);
30
+ }
31
+ export function newLoginId() {
32
+ return randomBytes(12).toString('base64url');
33
+ }
34
+ function isObject(value) {
35
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
36
+ }
37
+ function parseRecord(value) {
38
+ if (!isObject(value) || value['version'] !== 1)
39
+ return 'not a version 1 OAuth record';
40
+ const discovery = value['discovery'];
41
+ if (typeof value['server'] !== 'string' || typeof value['serverUrl'] !== 'string' ||
42
+ typeof value['loginId'] !== 'string' || typeof value['savedAt'] !== 'string' ||
43
+ typeof value['redirectUrl'] !== 'string' || !isObject(discovery) ||
44
+ typeof discovery['authorizationServerUrl'] !== 'string' || typeof discovery['resourceIndicator'] !== 'boolean') {
45
+ return 'record fields are missing or of the wrong type';
46
+ }
47
+ let tokens;
48
+ if (value['tokens'] !== undefined) {
49
+ const parsed = OAuthTokensSchema.safeParse(value['tokens']);
50
+ if (!parsed.success)
51
+ return 'stored tokens are malformed';
52
+ tokens = parsed.data;
53
+ }
54
+ let clientInformation;
55
+ if (value['clientInformation'] !== undefined) {
56
+ const parsed = OAuthClientInformationSchema.safeParse(value['clientInformation']);
57
+ if (!parsed.success)
58
+ return 'stored client information is malformed';
59
+ clientInformation = parsed.data;
60
+ }
61
+ return {
62
+ version: 1,
63
+ server: value['server'],
64
+ serverUrl: value['serverUrl'],
65
+ loginId: value['loginId'],
66
+ savedAt: value['savedAt'],
67
+ redirectUrl: value['redirectUrl'],
68
+ ...(clientInformation === undefined ? {} : { clientInformation }),
69
+ ...(tokens === undefined ? {} : { tokens }),
70
+ discovery: discovery,
71
+ };
72
+ }
73
+ const NOFOLLOW = fsConstants.O_NOFOLLOW ?? 0;
74
+ /**
75
+ * Why the store directory cannot be trusted, or undefined when it is absent or a real directory.
76
+ * A symlinked `mcp-auth` would send every token file (and its chmod) into whatever it points at,
77
+ * so reads, writes and deletes all refuse it before touching the target.
78
+ */
79
+ async function storeDirProblem(dir) {
80
+ try {
81
+ const info = await lstat(dir);
82
+ return info.isDirectory() ? undefined : `${dir} is not a real directory (a symlink or file); nothing was read or written`;
83
+ }
84
+ catch (error) {
85
+ const code = error?.code;
86
+ return code === 'ENOENT' ? undefined : `${dir} could not be inspected (${code ?? 'error'})`;
87
+ }
88
+ }
89
+ /** Reads one server's record, bound to `serverUrl`. Never throws; a bad file is `invalid`. */
90
+ export async function readOAuthRecord(server, serverUrl) {
91
+ const file = oauthRecordPath(server);
92
+ const dirProblem = await storeDirProblem(oauthStoreDir());
93
+ if (dirProblem !== undefined)
94
+ return { status: 'invalid', problem: dirProblem };
95
+ let text;
96
+ try {
97
+ const info = await lstat(file);
98
+ if (!info.isFile())
99
+ return { status: 'invalid', problem: `${file} is not a regular file` };
100
+ if (info.size > MAX_OAUTH_RECORD_BYTES)
101
+ return { status: 'invalid', problem: `${file} is larger than ${MAX_OAUTH_RECORD_BYTES} bytes` };
102
+ const handle = await open(file, fsConstants.O_RDONLY | NOFOLLOW);
103
+ try {
104
+ text = await handle.readFile('utf8');
105
+ }
106
+ finally {
107
+ await handle.close();
108
+ }
109
+ }
110
+ catch (error) {
111
+ if (error?.code === 'ENOENT')
112
+ return { status: 'absent' };
113
+ return { status: 'invalid', problem: `${file} could not be read (${error?.code ?? 'error'})` };
114
+ }
115
+ let parsed;
116
+ try {
117
+ parsed = JSON.parse(text);
118
+ }
119
+ catch {
120
+ return { status: 'invalid', problem: `${file} is not valid JSON` };
121
+ }
122
+ const record = parseRecord(parsed);
123
+ if (typeof record === 'string')
124
+ return { status: 'invalid', problem: `${file}: ${record}` };
125
+ if (record.server !== server || record.serverUrl !== serverUrl)
126
+ return { status: 'mismatch' };
127
+ return { status: 'ok', record };
128
+ }
129
+ /** Atomically replaces the server's record with `0600` permissions inside a `0700` directory. */
130
+ export async function writeOAuthRecord(record) {
131
+ const text = `${JSON.stringify(record)}\n`;
132
+ if (Buffer.byteLength(text) > MAX_OAUTH_RECORD_BYTES)
133
+ throw new Error(`OAuth record exceeds ${MAX_OAUTH_RECORD_BYTES} bytes`);
134
+ const dir = oauthStoreDir();
135
+ const dirProblem = await storeDirProblem(dir);
136
+ if (dirProblem !== undefined)
137
+ throw new Error(dirProblem);
138
+ await mkdir(dir, { recursive: true, mode: 0o700 });
139
+ // Tighten through a no-follow directory handle, so a symlink swapped in after the check above
140
+ // is refused (ELOOP) instead of having its target chmod-ed.
141
+ const dirHandle = await open(dir, fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | NOFOLLOW);
142
+ try {
143
+ if (!(await dirHandle.stat()).isDirectory())
144
+ throw new Error(`${dir} is not a real directory`);
145
+ await dirHandle.chmod(0o700);
146
+ }
147
+ finally {
148
+ await dirHandle.close();
149
+ }
150
+ const file = oauthRecordPath(record.server);
151
+ const temp = `${file}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
152
+ try {
153
+ await writeFile(temp, text, { flag: 'wx', mode: 0o600 });
154
+ await rename(temp, file);
155
+ }
156
+ catch (error) {
157
+ await rm(temp, { force: true });
158
+ throw error;
159
+ }
160
+ }
161
+ /** Removes the server's record. Returns whether a file was removed. */
162
+ export async function deleteOAuthRecord(server) {
163
+ const dirProblem = await storeDirProblem(oauthStoreDir());
164
+ if (dirProblem !== undefined)
165
+ throw new Error(dirProblem);
166
+ try {
167
+ await rm(oauthRecordPath(server));
168
+ return true;
169
+ }
170
+ catch (error) {
171
+ if (error?.code === 'ENOENT')
172
+ return false;
173
+ throw error;
174
+ }
175
+ }
176
+ //# sourceMappingURL=oauth-store.js.map