@lornatang/dsh-atlassian 0.1.6 → 0.1.10

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.
package/lib/bridge.js CHANGED
@@ -1,10 +1,24 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
3
  import { setTimeout as delay } from 'node:timers/promises';
3
4
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
5
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
5
6
  import { UnauthorizedError, auth } from '@modelcontextprotocol/sdk/client/auth.js';
6
- import { AtlassianOAuthProvider, CallbackServer, createCloudFetch } from './oauth.js';
7
+ import { AtlassianOAuthProvider, CallbackServer, RedirectRegistrationChanged, createCloudFetch, secureUrl } from './oauth.js';
8
+ import { OAuthTokensSchema } from '@modelcontextprotocol/sdk/shared/auth.js';
7
9
  import { openInBrowser } from './open-url.js';
10
+ import { sameTokens } from './store.js';
11
+ async function waitForFlight(flight, signal) {
12
+ if (signal.aborted)
13
+ throw new Error('atlassian: connection cancelled');
14
+ await new Promise((resolve, reject) => {
15
+ const abort = () => { signal.removeEventListener('abort', abort); reject(new Error('atlassian: connection cancelled')); };
16
+ signal.addEventListener('abort', abort, { once: true });
17
+ void flight.then(() => { signal.removeEventListener('abort', abort); resolve(); }, reject);
18
+ if (signal.aborted)
19
+ abort();
20
+ });
21
+ }
8
22
  export function publicToolName(server, tool) {
9
23
  const raw = `mcp__${server}__${tool}`;
10
24
  const clean = raw.replace(/[^A-Za-z0-9_-]/g, '_');
@@ -27,6 +41,7 @@ export class AtlassianBridge {
27
41
  #host;
28
42
  #options;
29
43
  #callback = new CallbackServer();
44
+ #operation = new AsyncLocalStorage();
30
45
  #provider;
31
46
  #fetch;
32
47
  #client;
@@ -38,13 +53,152 @@ export class AtlassianBridge {
38
53
  #boot;
39
54
  #generation = 0;
40
55
  #disposed = false;
56
+ #controller = new AbortController();
57
+ #flight;
58
+ #refreshes = new Set();
41
59
  constructor(host, options) {
42
60
  this.#host = host;
43
61
  this.#options = options;
44
62
  const network = createCloudFetch(new URL(options.url));
45
- this.#fetch = network.fetch;
46
- this.#provider = new AtlassianOAuthProvider({ store: options.store, redirectUri: () => this.#callback.redirectUri, allowLoopbackHttp: network.allowLoopbackHttp, logger: host.logger, onAuthorizationUrl: (url) => { this.#url = url; } });
63
+ const active = () => {
64
+ const operation = this.#operation.getStore();
65
+ return !this.#disposed && (!operation || (operation.generation === this.#generation && !operation.signal.aborted));
66
+ };
67
+ this.#fetch = async (value, init) => {
68
+ const operation = this.#operation.getStore();
69
+ if (!operation) {
70
+ if (init?.body instanceof URLSearchParams && init.body.get('grant_type') === 'refresh_token') {
71
+ throw new Error('atlassian: refresh requires an active connection operation');
72
+ }
73
+ return network.fetch(value, init);
74
+ }
75
+ if (!active())
76
+ throw new Error('atlassian: connection cancelled');
77
+ const signals = [operation.signal];
78
+ if (init?.signal)
79
+ signals.push(init.signal);
80
+ const signal = AbortSignal.any(signals);
81
+ const authorization = new Headers(init?.headers).get('authorization');
82
+ if (authorization?.startsWith('Bearer ')) {
83
+ const current = this.#options.store.current.tokens;
84
+ const previous = operation.observedTokens;
85
+ operation.observedTokens = previous && authorization === `Bearer ${previous.access_token}` ? previous
86
+ : current && authorization === `Bearer ${current.access_token}` ? current : undefined;
87
+ }
88
+ const refresh = init?.body instanceof URLSearchParams && init.body.get('grant_type') === 'refresh_token';
89
+ if (!refresh)
90
+ return network.fetch(value, { ...init, signal });
91
+ // A synthetic response must obey the same URL policy as a network request.
92
+ secureUrl(new URL(value), network.allowLoopbackHttp);
93
+ const expected = operation.observedTokens;
94
+ while (this.#flight && this.#flight.owner !== operation)
95
+ await waitForFlight(this.#flight.done, signal);
96
+ if (!active() || signal.aborted)
97
+ throw new Error('atlassian: connection cancelled');
98
+ operation.refreshExpected = expected;
99
+ const lease = await this.#options.store.acquire(signal);
100
+ if (!active() || signal.aborted) {
101
+ lease.release();
102
+ throw new Error('atlassian: connection cancelled');
103
+ }
104
+ const current = this.#options.store.current.tokens;
105
+ if (expected && !sameTokens(current, expected)) {
106
+ lease.release();
107
+ return new Response(JSON.stringify(current ?? { error: 'invalid_grant' }), { status: current ? 200 : 400, headers: { 'content-type': 'application/json' } });
108
+ }
109
+ if (!this.#flight) {
110
+ let complete;
111
+ const done = new Promise((resolve) => { complete = resolve; });
112
+ let pending = true;
113
+ let requested = false;
114
+ const release = () => {
115
+ if (pending) {
116
+ requested = true;
117
+ return;
118
+ }
119
+ if (this.#flight?.owner === operation) {
120
+ this.#flight = undefined;
121
+ signal.removeEventListener('abort', release);
122
+ complete();
123
+ }
124
+ if (operation.lease === lease) {
125
+ operation.lease = undefined;
126
+ lease.release();
127
+ }
128
+ if (operation.releaseRefresh === release)
129
+ operation.releaseRefresh = undefined;
130
+ };
131
+ this.#flight = { owner: operation, done };
132
+ operation.lease = lease;
133
+ operation.releaseRefresh = release;
134
+ signal.addEventListener('abort', release, { once: true });
135
+ if (signal.aborted) {
136
+ pending = false;
137
+ release();
138
+ throw new Error('atlassian: connection cancelled');
139
+ }
140
+ const exchange = (async () => {
141
+ try {
142
+ // A cancelled local request may still rotate its token remotely. Finish
143
+ // and persist the response before allowing another process to refresh.
144
+ const response = await network.fetch(value, { ...init, signal: AbortSignal.timeout(Math.max(30000, this.#options.toolCallTimeoutMs)) });
145
+ if (response.ok) {
146
+ const parsed = OAuthTokensSchema.omit({ issuer: true }).safeParse(await response.clone().json());
147
+ if (!parsed.success)
148
+ throw new Error('atlassian: invalid refresh response');
149
+ const refreshToken = init?.body instanceof URLSearchParams ? init.body.get('refresh_token') ?? undefined : undefined;
150
+ const issuer = expected?.issuer ?? this.#options.store.current.clientInformation?.issuer;
151
+ const tokens = { refresh_token: refreshToken, ...parsed.data, ...(issuer ? { issuer } : {}) };
152
+ await this.#options.store.saveTokens(tokens, () => true, expected, lease);
153
+ }
154
+ return response;
155
+ }
156
+ catch (error) {
157
+ // If the response was lost, the server may already have rotated it.
158
+ // Do not let another process reuse the uncertain refresh token.
159
+ await this.#options.store.clearCredentialsIf(() => true, expected, lease, undefined, true, 'tokens');
160
+ throw error;
161
+ }
162
+ finally {
163
+ pending = false;
164
+ if (requested)
165
+ release();
166
+ }
167
+ })();
168
+ this.#refreshes.add(exchange);
169
+ try {
170
+ return await exchange;
171
+ }
172
+ finally {
173
+ this.#refreshes.delete(exchange);
174
+ }
175
+ }
176
+ lease.release();
177
+ throw new Error('atlassian: refresh is already in progress');
178
+ };
179
+ this.#provider = new AtlassianOAuthProvider({
180
+ store: options.store, redirectUri: () => this.#callback.redirectUri, allowLoopbackHttp: network.allowLoopbackHttp, logger: host.logger,
181
+ onAuthorizationUrl: (url) => {
182
+ if (!active())
183
+ return;
184
+ this.#url = url;
185
+ if (this.#status === 'ready') {
186
+ this.#status = 'error';
187
+ this.#error = 'Atlassian authorization expired; reconnect to authorize again';
188
+ }
189
+ },
190
+ active,
191
+ tokenRead: (tokens) => { const op = this.#operation.getStore(); if (op && !op.observedTokens)
192
+ op.observedTokens = tokens; },
193
+ refreshExpected: () => this.#operation.getStore()?.refreshExpected,
194
+ authFinished: () => { const op = this.#operation.getStore(); op?.releaseRefresh?.(); if (op)
195
+ op.refreshExpected = undefined; },
196
+ lease: () => this.#operation.getStore()?.lease,
197
+ observedTokens: () => this.#operation.getStore()?.observedTokens,
198
+ signal: () => this.#operation.getStore()?.signal,
199
+ });
47
200
  }
201
+ #newOperation() { return { generation: this.#generation, signal: this.#controller.signal }; }
48
202
  snapshot() {
49
203
  const site = this.#options.store.current.site;
50
204
  let mismatch = false;
@@ -67,17 +221,13 @@ export class AtlassianBridge {
67
221
  const generation = this.#generation;
68
222
  const boot = (async () => {
69
223
  this.#status = 'connecting';
70
- await this.#options.store.load();
224
+ await this.#options.store.load(this.#controller.signal);
71
225
  if (this.#disposed || generation !== this.#generation)
72
226
  return;
73
227
  await this.#callback.listen(this.#options.redirectPort);
74
228
  if (this.#disposed || generation !== this.#generation)
75
229
  return;
76
- const previous = this.#options.store.current.redirectUri;
77
- const actual = this.#callback.redirectUri;
78
- if (previous && previous !== actual)
79
- await this.#options.store.clear('clientInformation', 'tokens', 'codeVerifier');
80
- await this.#options.store.patch({ redirectUri: actual });
230
+ await this.#options.store.prepareRedirect(this.#callback.redirectUri, this.#controller.signal);
81
231
  if (this.#disposed || generation !== this.#generation)
82
232
  return;
83
233
  this.#launch(false, generation);
@@ -138,8 +288,30 @@ export class AtlassianBridge {
138
288
  check();
139
289
  this.#status = 'connecting';
140
290
  this.#error = undefined;
141
- const client = new Client({ name: 'dsh-atlassian', version: '0.1.6' });
291
+ const client = new Client({ name: 'dsh-atlassian', version: '0.1.10' });
292
+ client.onerror = () => { this.#operation.getStore()?.releaseRefresh?.(); };
142
293
  const transport = new StreamableHTTPClientTransport(new URL(this.#options.url), { authProvider: this.#provider, fetch: this.#fetch });
294
+ const send = transport.send.bind(transport);
295
+ transport.send = (message, options) => {
296
+ const operation = this.#newOperation();
297
+ return this.#operation.run(operation, async () => {
298
+ try {
299
+ return await send(message, options);
300
+ }
301
+ catch (error) {
302
+ operation.releaseRefresh?.();
303
+ if (!this.#disposed && operation.generation === this.#generation && this.#status === 'ready' && operation.observedTokens && !this.#options.store.current.tokens) {
304
+ this.#status = 'error';
305
+ this.#error = 'Atlassian authorization expired; reconnect to authorize again';
306
+ }
307
+ if (!(error instanceof RedirectRegistrationChanged))
308
+ throw error;
309
+ operation.observedTokens = undefined;
310
+ operation.refreshExpected = undefined;
311
+ return send(message, options);
312
+ }
313
+ });
314
+ };
143
315
  try {
144
316
  await client.connect(transport);
145
317
  check();
@@ -156,15 +328,15 @@ export class AtlassianBridge {
156
328
  void openInBrowser(this.#url);
157
329
  const callback = await waiting;
158
330
  check();
159
- await auth(this.#provider, { serverUrl: this.#options.url, authorizationCode: callback.code, fetchFn: this.#fetch });
331
+ await this.#operation.run(this.#newOperation(), () => auth(this.#provider, { serverUrl: this.#options.url, authorizationCode: callback.code, fetchFn: this.#fetch }));
160
332
  check();
161
- await this.#options.store.clear('codeVerifier');
333
+ await this.#options.store.clearCredentialsIf(() => !this.#disposed && generation === this.#generation, undefined, undefined, this.#controller.signal, false, 'codeVerifier');
162
334
  continue;
163
335
  }
164
336
  this.#client = client;
165
337
  await this.#registerTools(client);
166
338
  check();
167
- await this.#readSite(client);
339
+ await this.#readSite(client, generation, this.#controller.signal);
168
340
  check();
169
341
  this.#url = undefined;
170
342
  this.#status = 'ready';
@@ -221,16 +393,16 @@ export class AtlassianBridge {
221
393
  throw error;
222
394
  }
223
395
  }
224
- async #readSite(client) {
396
+ async #readSite(client, generation, signal) {
225
397
  const name = this.rawNameMatching(/accessibleatlassianresources/i);
226
398
  if (!name)
227
399
  return;
228
400
  try {
229
- const result = await client.callTool({ name, arguments: {} }, undefined, { timeout: 20000 });
401
+ const result = await client.callTool({ name, arguments: {} }, undefined, { timeout: 20000, signal });
230
402
  const items = JSON.parse(display(result.content));
231
403
  const first = Array.isArray(items) ? items[0] : items;
232
404
  if (first && typeof first === 'object' && typeof first['url'] === 'string') {
233
- await this.#options.store.patch({ site: new URL(first['url']).host });
405
+ await this.#options.store.patch({ site: new URL(first['url']).host }, () => !this.#disposed && generation === this.#generation && !signal.aborted, undefined, undefined, signal);
234
406
  }
235
407
  }
236
408
  catch { /* The connection can work without a site label. */ }
@@ -245,11 +417,14 @@ export class AtlassianBridge {
245
417
  }
246
418
  async disconnect() {
247
419
  this.#generation++;
420
+ this.#controller.abort();
421
+ this.#controller = new AbortController();
248
422
  this.#status = 'idle';
249
423
  this.#callback.cancelWait();
250
424
  await this.#boot?.catch(() => undefined);
251
425
  this.#callback.cancelWait();
252
426
  await this.#work;
427
+ await Promise.allSettled([...this.#refreshes]);
253
428
  await this.#closeClient();
254
429
  this.#clearTools();
255
430
  await this.#options.store.destroy();
@@ -262,11 +437,13 @@ export class AtlassianBridge {
262
437
  return;
263
438
  this.#disposed = true;
264
439
  this.#generation++;
440
+ this.#controller.abort();
265
441
  this.#status = 'idle';
266
442
  this.#callback.cancelWait();
267
443
  await this.#boot?.catch(() => undefined);
268
444
  this.#callback.cancelWait();
269
445
  await this.#work;
446
+ await Promise.allSettled([...this.#refreshes]);
270
447
  await this.#closeClient();
271
448
  this.#clearTools();
272
449
  await this.#callback.close();
package/lib/oauth.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { createServer } from 'node:http';
3
+ export class RedirectRegistrationChanged extends Error {
4
+ }
3
5
  const MAX_CLOUD_RESPONSE_BYTES = 10 * 1024 * 1024;
4
6
  /** Bound decoded response bytes, including error bodies and individual SSE events. */
5
7
  function limitCloudResponse(response, allowEvents) {
@@ -54,7 +56,7 @@ function limitCloudResponse(response, allowEvents) {
54
56
  function isLoopback(url) {
55
57
  return ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
56
58
  }
57
- function secureUrl(url, allowLoopbackHttp) {
59
+ export function secureUrl(url, allowLoopbackHttp) {
58
60
  if (url.username || url.password || (url.protocol !== 'https:' && !(allowLoopbackHttp && url.protocol === 'http:' && isLoopback(url)))) {
59
61
  throw new Error('Cloud and OAuth endpoints must use HTTPS without embedded credentials');
60
62
  }
@@ -184,40 +186,85 @@ export class AtlassianOAuthProvider {
184
186
  #redirect;
185
187
  #onUrl;
186
188
  #allowLoopbackHttp;
189
+ #active;
190
+ #tokenRead;
191
+ #refreshExpected;
192
+ #authFinished;
193
+ #lease;
194
+ #observedTokens;
195
+ #signal;
187
196
  constructor(options) {
188
197
  this.#store = options.store;
189
198
  this.#redirect = options.redirectUri;
190
199
  this.#onUrl = options.onAuthorizationUrl;
191
200
  this.#allowLoopbackHttp = options.allowLoopbackHttp;
201
+ this.#active = options.active ?? (() => true);
202
+ this.#tokenRead = options.tokenRead ?? (() => undefined);
203
+ this.#refreshExpected = options.refreshExpected ?? (() => undefined);
204
+ this.#authFinished = options.authFinished ?? (() => undefined);
205
+ this.#lease = options.lease ?? (() => undefined);
206
+ this.#observedTokens = options.observedTokens ?? (() => undefined);
207
+ this.#signal = options.signal ?? (() => undefined);
192
208
  }
193
- get redirectUrl() { return this.#redirect(); }
209
+ #check() { if (!this.#active())
210
+ throw new Error('atlassian: connection cancelled'); }
211
+ get redirectUrl() { this.#check(); return this.#redirect(); }
194
212
  get clientMetadata() {
195
213
  return { client_name: 'DSH Atlassian', redirect_uris: [this.redirectUrl], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none' };
196
214
  }
197
- state() { return randomBytes(16).toString('hex'); }
198
- clientInformation() { return this.#store.current.clientInformation; }
199
- async saveClientInformation(value) { await this.#store.patch({ clientInformation: value }); }
200
- tokens() { return this.#store.current.tokens; }
201
- async saveTokens(value) { await this.#store.patch({ tokens: value }); }
215
+ state() { this.#check(); return randomBytes(16).toString('hex'); }
216
+ clientInformation() { this.#check(); return this.#store.current.clientInformation; }
217
+ async saveClientInformation(value) { await this.#store.patch({ clientInformation: value }, this.#active, this.#lease(), this.#observedTokens(), this.#signal(), true); }
218
+ tokens() { this.#check(); const value = this.#store.current.tokens; this.#tokenRead(value); return value; }
219
+ async saveTokens(value) {
220
+ try {
221
+ await this.#store.saveTokens(value, this.#active, this.#refreshExpected() ?? this.#observedTokens(), this.#lease(), this.#signal(), true);
222
+ }
223
+ finally {
224
+ this.#authFinished();
225
+ }
226
+ }
202
227
  redirectToAuthorization(url) {
228
+ this.#check();
203
229
  secureUrl(url, this.#allowLoopbackHttp);
204
230
  this.#onUrl(url.href);
231
+ this.#authFinished();
232
+ }
233
+ async saveCodeVerifier(value) {
234
+ try {
235
+ const registered = this.#store.current.redirectUri;
236
+ const actual = this.#redirect();
237
+ if (registered && registered !== actual) {
238
+ await this.#store.rebindRedirect(actual, this.#observedTokens(), this.#active, this.#lease(), this.#signal());
239
+ throw new RedirectRegistrationChanged('atlassian: callback changed; restarting authorization');
240
+ }
241
+ await this.#store.patch({ codeVerifier: value }, this.#active, this.#lease(), this.#observedTokens(), this.#signal(), true);
242
+ }
243
+ finally {
244
+ this.#authFinished();
245
+ }
205
246
  }
206
- async saveCodeVerifier(value) { await this.#store.patch({ codeVerifier: value }); }
207
247
  codeVerifier() {
248
+ this.#check();
208
249
  const value = this.#store.current.codeVerifier;
209
250
  if (!value)
210
251
  throw new Error('missing PKCE verifier');
211
252
  return value;
212
253
  }
213
254
  async invalidateCredentials(scope) {
214
- if (scope === 'all')
215
- await this.#store.clear('tokens', 'clientInformation', 'codeVerifier');
216
- else if (scope === 'client')
217
- await this.#store.clear('clientInformation');
218
- else if (scope === 'tokens')
219
- await this.#store.clear('tokens');
220
- else if (scope === 'verifier')
221
- await this.#store.clear('codeVerifier');
255
+ try {
256
+ const expected = this.#refreshExpected() ?? this.#observedTokens();
257
+ if (scope === 'all')
258
+ await this.#store.clearCredentialsIf(this.#active, expected, this.#lease(), this.#signal(), true, 'tokens', 'clientInformation', 'codeVerifier');
259
+ else if (scope === 'client')
260
+ await this.#store.clearCredentialsIf(this.#active, expected, this.#lease(), this.#signal(), true, 'clientInformation');
261
+ else if (scope === 'tokens')
262
+ await this.#store.clearCredentialsIf(this.#active, expected, this.#lease(), this.#signal(), true, 'tokens');
263
+ else if (scope === 'verifier')
264
+ await this.#store.clearCredentialsIf(this.#active, expected, this.#lease(), this.#signal(), true, 'codeVerifier');
265
+ }
266
+ finally {
267
+ this.#authFinished();
268
+ }
222
269
  }
223
270
  }