@lornatang/dsh-atlassian 0.1.10 → 0.1.11

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.11 - 2026-11-17
4
+
5
+ - Invalidate the cached Jira site whenever the connection is replaced and deduplicate concurrent site lookups, so a reconnect can never serve data from the previous site.
6
+ - Reuse keep-alive connections for self-hosted REST requests and close the socket pool on reconnect, disconnect, and disposal.
7
+ - Scan Cloud SSE size limits with native buffer searches instead of a per-byte loop, and wake connection waiters on state changes instead of polling.
8
+ - Share one status poller between the settings and board client panels and skip re-renders when the snapshot is unchanged.
9
+ - Show a clear empty state on the Jira board for Confluence-only profiles instead of a missing-tool error.
10
+ - Expand issue keys and summaries literally in board handoff prompts.
11
+ - Destroy stored credentials when a configuration change points the profile at a different endpoint identity.
12
+ - Reject malformed request URLs and issue-key encodings with 400 responses, and bound request-body reads with a deadline.
13
+ - Bound the cross-process refresh lock even when toolCallTimeoutMs is configured very large.
14
+ - Include a GitHub release archive; this release is also published to npm.
15
+
3
16
  ## 0.1.10 - 2026-11-15
4
17
 
5
18
  - Coordinate OAuth token rotation across processes sharing a profile, including delayed responses, shutdown, callback-port changes, and concurrent session updates.
package/README.md CHANGED
@@ -34,7 +34,7 @@ dsh plugin --profile <name> add @lornatang/dsh-atlassian
34
34
  dsh plugin --profile <name> remove @lornatang/dsh-atlassian
35
35
  ```
36
36
 
37
- For the GitHub-only 0.1.10 release, use `dsh plugin --profile <name> add https://github.com/Lornatang/dsh-atlassian/releases/download/v0.1.10/lornatang-dsh-atlassian-0.1.10.tgz`. The npm registry version may be older.
37
+ The same release is also attached as an archive on GitHub: `dsh plugin --profile <name> add https://github.com/Lornatang/dsh-atlassian/releases/download/v0.1.11/lornatang-dsh-atlassian-0.1.11.tgz`.
38
38
 
39
39
  `add` composes the layer into the profile: the profile's `cordis.patch.yml` gains an insert entry with row id `atlassian`, package `@lornatang/dsh-atlassian`, and the five values the shipped patch carries — `mode: cloud`, `serverName: atlassian`, `url: https://mcp.atlassian.com/v1/mcp`, `redirectPort: 3334` and `autoOpenBrowser: true`. The manifest declares `dsh.bundle.patch: ./cordis.patch.yml`, which is the declaration the reconcile step reads; `remove` deletes the entry again. Restart DSH after either command, because the profile composes its rows and its client half only at startup, then open Settings → Atlassian. Releases before 0.1.5 published this package as `@lornatang/dsh-atlassian-bridge`; add the scoped name, remove the old package from the same profile and restart once — the row, its settings and the stored credentials survive.
40
40
 
package/README.zh.md CHANGED
@@ -34,7 +34,7 @@ dsh plugin --profile <name> add @lornatang/dsh-atlassian
34
34
  dsh plugin --profile <name> remove @lornatang/dsh-atlassian
35
35
  ```
36
36
 
37
- 安装仅发布到 GitHub 的 0.1.10 版本,请运行 `dsh plugin --profile <name> add https://github.com/Lornatang/dsh-atlassian/releases/download/v0.1.10/lornatang-dsh-atlassian-0.1.10.tgz`。npm 仓库中的版本可能较旧。
37
+ 也可以从 GitHub release 附带的压缩包安装同一版本:`dsh plugin --profile <name> add https://github.com/Lornatang/dsh-atlassian/releases/download/v0.1.11/lornatang-dsh-atlassian-0.1.11.tgz`。
38
38
 
39
39
  `add` 会把本层组合进 profile:profile 的 `cordis.patch.yml` 会增加一条 insert 记录,行 id 为 `atlassian`,包名为 `@lornatang/dsh-atlassian`,并带上随包提供的补丁中的五个值——`mode: cloud`、`serverName: atlassian`、`url: https://mcp.atlassian.com/v1/mcp`、`redirectPort: 3334` 与 `autoOpenBrowser: true`。包的 manifest 声明了 `dsh.bundle.patch: ./cordis.patch.yml`,reconcile 步骤读取的正是这条声明;`remove` 会再次删除该记录。两条命令执行后都要重启 DSH,因为 profile 只在启动时组合自己的行与客户端部分,随后打开 Settings → Atlassian。0.1.5 之前的版本以 `@lornatang/dsh-atlassian-bridge` 发布;添加带作用域的新名称、从同一 profile 删除旧包、重启一次即可——行、其设置与已保存的凭据都会保留。
40
40
 
package/lib/board.js CHANGED
@@ -29,15 +29,16 @@ function issue(value, base) {
29
29
  export class JiraBoard {
30
30
  #bridge;
31
31
  #resource;
32
+ #pending;
32
33
  constructor(bridge) { this.#bridge = bridge; }
33
34
  available() { return !!this.#bridge.rawNameMatching(/searchJiraIssuesUsingJql/i); }
34
- get site() { return this.#resource?.site; }
35
+ get site() { return this.#resource?.epoch === (this.#bridge.epoch?.() ?? 0) ? this.#resource.site : undefined; }
35
36
  async #call(pattern, args, timeoutMs) {
36
37
  const name = this.#bridge.rawNameMatching(pattern);
37
38
  if (!name) {
38
39
  const state = this.#bridge.snapshot?.();
39
40
  if (state && state.status !== 'ready')
40
- throw new BoardError('not-connected', state.error || `Atlassian is not connected(${state.status})`);
41
+ throw new BoardError('not-connected', state.error || `Atlassian is not connected (${state.status})`);
41
42
  throw new BoardError('missing-tool', `Missing Jira tool: ${pattern.source}`);
42
43
  }
43
44
  let blocks;
@@ -56,8 +57,22 @@ export class JiraBoard {
56
57
  }
57
58
  }
58
59
  async cloudId() {
59
- if (this.#resource)
60
+ const epoch = this.#bridge.epoch?.() ?? 0;
61
+ if (this.#resource?.epoch === epoch)
60
62
  return this.#resource.id;
63
+ if (this.#pending?.epoch === epoch)
64
+ return this.#pending.promise;
65
+ const promise = this.#resolveSite(epoch);
66
+ this.#pending = { epoch, promise };
67
+ try {
68
+ return await promise;
69
+ }
70
+ finally {
71
+ if (this.#pending?.promise === promise)
72
+ this.#pending = undefined;
73
+ }
74
+ }
75
+ async #resolveSite(epoch) {
61
76
  const data = await this.#call(/accessibleatlassianresources/i, {}, 20000);
62
77
  const list = Array.isArray(data) ? data : [data];
63
78
  for (const item of list) {
@@ -70,7 +85,9 @@ export class JiraBoard {
70
85
  const parsed = new URL(url);
71
86
  if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password)
72
87
  continue;
73
- this.#resource = { id, base: `${parsed.origin}${parsed.pathname.replace(/\/$/, '')}`, site: parsed.host };
88
+ // A reconnect may have invalidated this resolution while it was in flight.
89
+ if ((this.#bridge.epoch?.() ?? 0) === epoch)
90
+ this.#resource = { epoch, id, base: `${parsed.origin}${parsed.pathname.replace(/\/$/, '')}`, site: parsed.host };
74
91
  return id;
75
92
  }
76
93
  catch {
package/lib/bridge.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
- import { setTimeout as delay } from 'node:timers/promises';
4
3
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
5
4
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
6
5
  import { UnauthorizedError, auth } from '@modelcontextprotocol/sdk/client/auth.js';
@@ -56,6 +55,7 @@ export class AtlassianBridge {
56
55
  #controller = new AbortController();
57
56
  #flight;
58
57
  #refreshes = new Set();
58
+ #waiters = new Set();
59
59
  constructor(host, options) {
60
60
  this.#host = host;
61
61
  this.#options = options;
@@ -141,7 +141,8 @@ export class AtlassianBridge {
141
141
  try {
142
142
  // A cancelled local request may still rotate its token remotely. Finish
143
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)) });
144
+ // Bound the cross-process refresh lock even when toolCallTimeoutMs is huge.
145
+ const response = await network.fetch(value, { ...init, signal: AbortSignal.timeout(Math.min(120000, Math.max(30000, this.#options.toolCallTimeoutMs))) });
145
146
  if (response.ok) {
146
147
  const parsed = OAuthTokensSchema.omit({ issuer: true }).safeParse(await response.clone().json());
147
148
  if (!parsed.success)
@@ -181,9 +182,9 @@ export class AtlassianBridge {
181
182
  onAuthorizationUrl: (url) => {
182
183
  if (!active())
183
184
  return;
184
- this.#url = url;
185
+ this.#setUrl(url);
185
186
  if (this.#status === 'ready') {
186
- this.#status = 'error';
187
+ this.#setStatus('error');
187
188
  this.#error = 'Atlassian authorization expired; reconnect to authorize again';
188
189
  }
189
190
  },
@@ -199,6 +200,28 @@ export class AtlassianBridge {
199
200
  });
200
201
  }
201
202
  #newOperation() { return { generation: this.#generation, signal: this.#controller.signal }; }
203
+ epoch() { return this.#generation; }
204
+ #setStatus(status) { this.#status = status; this.#wake(); }
205
+ #setUrl(url) { this.#url = url; this.#wake(); }
206
+ #wake() { const waiters = [...this.#waiters]; this.#waiters.clear(); for (const wake of waiters)
207
+ wake(); }
208
+ /** Resolve as soon as the predicate holds, or at the deadline like the previous polling loop. */
209
+ #waitFor(timeoutMs, done) {
210
+ return new Promise((resolve) => {
211
+ if (done()) {
212
+ resolve();
213
+ return;
214
+ }
215
+ const finish = () => { clearTimeout(timer); this.#waiters.delete(wake); resolve(); };
216
+ const wake = () => { if (done())
217
+ finish();
218
+ else
219
+ this.#waiters.add(wake); };
220
+ const timer = setTimeout(finish, timeoutMs);
221
+ timer.unref();
222
+ this.#waiters.add(wake);
223
+ });
224
+ }
202
225
  snapshot() {
203
226
  const site = this.#options.store.current.site;
204
227
  let mismatch = false;
@@ -220,7 +243,7 @@ export class AtlassianBridge {
220
243
  return this.#boot;
221
244
  const generation = this.#generation;
222
245
  const boot = (async () => {
223
- this.#status = 'connecting';
246
+ this.#setStatus('connecting');
224
247
  await this.#options.store.load(this.#controller.signal);
225
248
  if (this.#disposed || generation !== this.#generation)
226
249
  return;
@@ -231,8 +254,7 @@ export class AtlassianBridge {
231
254
  if (this.#disposed || generation !== this.#generation)
232
255
  return;
233
256
  this.#launch(false, generation);
234
- for (let i = 0; i < 600 && this.#status === 'connecting'; i++)
235
- await delay(25);
257
+ await this.#waitFor(15000, () => this.#status !== 'connecting');
236
258
  })();
237
259
  this.#boot = boot;
238
260
  try {
@@ -240,7 +262,7 @@ export class AtlassianBridge {
240
262
  }
241
263
  catch (error) {
242
264
  if (!this.#disposed && generation === this.#generation) {
243
- this.#status = 'error';
265
+ this.#setStatus('error');
244
266
  this.#error = error instanceof Error ? error.message : String(error);
245
267
  }
246
268
  throw error;
@@ -262,17 +284,18 @@ export class AtlassianBridge {
262
284
  if (!this.#work) {
263
285
  await this.#closeClient();
264
286
  this.#clearTools();
265
- this.#url = undefined;
287
+ this.#setUrl(undefined);
266
288
  this.#launch(true, this.#generation);
267
289
  }
268
- for (let i = 0; i < 800 && this.#status === 'connecting' && !this.#url; i++)
269
- await delay(25);
290
+ // Wait for a settled state: the authorization URL is published just before
291
+ // the status leaves 'connecting', and callers act on the returned status.
292
+ await this.#waitFor(20000, () => this.#status !== 'connecting');
270
293
  return this.snapshot();
271
294
  }
272
295
  #launch(open, generation) {
273
296
  const work = this.#connect(open, generation).catch((error) => {
274
297
  if (!this.#disposed && generation === this.#generation) {
275
- this.#status = 'error';
298
+ this.#setStatus('error');
276
299
  this.#error = error instanceof Error ? error.message : String(error);
277
300
  this.#host.logger.error(`atlassian: ${this.#error}`);
278
301
  }
@@ -286,9 +309,9 @@ export class AtlassianBridge {
286
309
  throw new Error('connection cancelled'); };
287
310
  for (let attempt = 0; attempt < 2; attempt++) {
288
311
  check();
289
- this.#status = 'connecting';
312
+ this.#setStatus('connecting');
290
313
  this.#error = undefined;
291
- const client = new Client({ name: 'dsh-atlassian', version: '0.1.10' });
314
+ const client = new Client({ name: 'dsh-atlassian', version: '0.1.11' });
292
315
  client.onerror = () => { this.#operation.getStore()?.releaseRefresh?.(); };
293
316
  const transport = new StreamableHTTPClientTransport(new URL(this.#options.url), { authProvider: this.#provider, fetch: this.#fetch });
294
317
  const send = transport.send.bind(transport);
@@ -301,7 +324,7 @@ export class AtlassianBridge {
301
324
  catch (error) {
302
325
  operation.releaseRefresh?.();
303
326
  if (!this.#disposed && operation.generation === this.#generation && this.#status === 'ready' && operation.observedTokens && !this.#options.store.current.tokens) {
304
- this.#status = 'error';
327
+ this.#setStatus('error');
305
328
  this.#error = 'Atlassian authorization expired; reconnect to authorize again';
306
329
  }
307
330
  if (!(error instanceof RedirectRegistrationChanged))
@@ -323,7 +346,7 @@ export class AtlassianBridge {
323
346
  throw error;
324
347
  const state = this.#url ? new URL(this.#url).searchParams.get('state') ?? undefined : undefined;
325
348
  const waiting = this.#callback.waitForCode(this.#options.authorizationTimeoutMs, state);
326
- this.#status = 'authorizing';
349
+ this.#setStatus('authorizing');
327
350
  if (open && this.#url && this.#options.autoOpenBrowser)
328
351
  void openInBrowser(this.#url);
329
352
  const callback = await waiting;
@@ -338,8 +361,8 @@ export class AtlassianBridge {
338
361
  check();
339
362
  await this.#readSite(client, generation, this.#controller.signal);
340
363
  check();
341
- this.#url = undefined;
342
- this.#status = 'ready';
364
+ this.#setUrl(undefined);
365
+ this.#setStatus('ready');
343
366
  return;
344
367
  }
345
368
  throw new Error('Atlassian authorization did not establish a connection');
@@ -419,7 +442,7 @@ export class AtlassianBridge {
419
442
  this.#generation++;
420
443
  this.#controller.abort();
421
444
  this.#controller = new AbortController();
422
- this.#status = 'idle';
445
+ this.#setStatus('idle');
423
446
  this.#callback.cancelWait();
424
447
  await this.#boot?.catch(() => undefined);
425
448
  this.#callback.cancelWait();
@@ -428,7 +451,7 @@ export class AtlassianBridge {
428
451
  await this.#closeClient();
429
452
  this.#clearTools();
430
453
  await this.#options.store.destroy();
431
- this.#url = undefined;
454
+ this.#setUrl(undefined);
432
455
  this.#error = undefined;
433
456
  return this.snapshot();
434
457
  }
@@ -438,7 +461,7 @@ export class AtlassianBridge {
438
461
  this.#disposed = true;
439
462
  this.#generation++;
440
463
  this.#controller.abort();
441
- this.#status = 'idle';
464
+ this.#setStatus('idle');
442
465
  this.#callback.cancelWait();
443
466
  await this.#boot?.catch(() => undefined);
444
467
  this.#callback.cancelWait();
package/lib/client.js CHANGED
@@ -77,20 +77,57 @@ async function api(path, method = 'GET', body) {
77
77
  throw new Error(typeof value['error'] === 'string' ? value['error'] : `HTTP ${String(response.status)}`);
78
78
  return value;
79
79
  }
80
- function useSnapshot() {
81
- const [value, setValue] = React.useState();
82
- const [error, setError] = React.useState('');
83
- const refresh = React.useCallback(async () => {
80
+ // Settings and the board panel share one poller and one snapshot, so an idle
81
+ // workspace neither doubles the /status traffic nor re-renders unchanged data.
82
+ const snapshotState = { value: undefined, error: '' };
83
+ const snapshotListeners = new Set();
84
+ let snapshotTimer;
85
+ let snapshotInflight;
86
+ let snapshotSerialized = '';
87
+ async function refreshSnapshot() {
88
+ if (snapshotInflight)
89
+ return snapshotInflight;
90
+ snapshotInflight = (async () => {
91
+ let next;
84
92
  try {
85
- setValue(await api('/status'));
86
- setError('');
93
+ next = { value: await api('/status'), error: '' };
87
94
  }
88
95
  catch (err) {
89
- setError(err instanceof Error ? err.message : String(err));
96
+ next = { value: snapshotState.value, error: err instanceof Error ? err.message : String(err) };
90
97
  }
98
+ const serialized = JSON.stringify(next);
99
+ if (serialized === snapshotSerialized)
100
+ return;
101
+ snapshotSerialized = serialized;
102
+ snapshotState.value = next.value;
103
+ snapshotState.error = next.error;
104
+ for (const listener of [...snapshotListeners])
105
+ listener();
106
+ })().finally(() => { snapshotInflight = undefined; });
107
+ return snapshotInflight;
108
+ }
109
+ function subscribeSnapshot(listener) {
110
+ snapshotListeners.add(listener);
111
+ if (snapshotTimer === undefined) {
112
+ snapshotTimer = window.setInterval(() => { void refreshSnapshot(); }, 5000);
113
+ void refreshSnapshot();
114
+ }
115
+ return () => {
116
+ snapshotListeners.delete(listener);
117
+ if (!snapshotListeners.size && snapshotTimer !== undefined) {
118
+ window.clearInterval(snapshotTimer);
119
+ snapshotTimer = undefined;
120
+ }
121
+ };
122
+ }
123
+ function useSnapshot() {
124
+ const [state, setState] = React.useState({ value: snapshotState.value, error: snapshotState.error });
125
+ React.useEffect(() => {
126
+ const update = () => setState({ value: snapshotState.value, error: snapshotState.error });
127
+ update();
128
+ return subscribeSnapshot(update);
91
129
  }, []);
92
- React.useEffect(() => { void refresh(); const timer = window.setInterval(() => { void refresh(); }, 5000); return () => window.clearInterval(timer); }, [refresh]);
93
- return { value, error, refresh };
130
+ return { value: state.value, error: state.error, refresh: refreshSnapshot };
94
131
  }
95
132
  function icon(name) {
96
133
  const paths = {
@@ -169,7 +206,7 @@ function AtlassianSettings() {
169
206
  }
170
207
  function promptFor(issues, template) {
171
208
  return issues.map((item) => template
172
- ? template.replaceAll('{{key}}', item.key).replaceAll('{{summary}}', item.summary)
209
+ ? template.replaceAll('{{key}}', () => item.key).replaceAll('{{summary}}', () => item.summary)
173
210
  : `Work on Jira issue ${item.key}: ${item.summary}. Check the requirements and relevant code first, then report changes and verification. Do not change the Jira status automatically.`).join('\n\n');
174
211
  }
175
212
  function JiraBoardPanel() {
@@ -183,7 +220,15 @@ function JiraBoardPanel() {
183
220
  const [detail, setDetail] = React.useState();
184
221
  const [message, setMessage] = React.useState('');
185
222
  const [loading, setLoading] = React.useState(false);
223
+ // A Confluence-only profile has no Jira tools; the board shows an empty state
224
+ // instead of reporting a missing tool as an error on every refresh.
225
+ const jiraConfigured = snapshot?.mode !== 'server' || !!snapshot?.server?.jiraUrl;
186
226
  const refresh = React.useCallback(async (value) => {
227
+ if (!jiraConfigured) {
228
+ setBoard(undefined);
229
+ setMessage('');
230
+ return;
231
+ }
187
232
  setLoading(true);
188
233
  try {
189
234
  const result = await api(`/board?jql=${encodeURIComponent(value)}`);
@@ -197,7 +242,7 @@ function JiraBoardPanel() {
197
242
  finally {
198
243
  setLoading(false);
199
244
  }
200
- }, []);
245
+ }, [jiraConfigured]);
201
246
  React.useEffect(() => { if (snapshot?.status === 'ready')
202
247
  void refresh(snapshot.board.jql); }, [snapshot?.status, refresh]);
203
248
  const issues = (board?.issues ?? []).filter((item) => (!project || item.projectKey === project) && `${item.key} ${item.summary} ${item.projectName ?? ''}`.toLowerCase().includes(query.toLowerCase()));
@@ -243,7 +288,7 @@ function JiraBoardPanel() {
243
288
  event.preventDefault();
244
289
  void inspect(item.key);
245
290
  } } }, h('label', { className: 'dab-issue-key', onClick: (event) => event.stopPropagation() }, h('input', { type: 'checkbox', 'aria-label': `Select ${item.key}`, checked: selected.includes(item.key), onChange: (event) => setSelected(event.target.checked ? [...selected, item.key] : selected.filter((key) => key !== item.key)) }), item.key), h('div', { className: 'dab-issue-summary' }, item.summary), h('small', { className: 'dab-issue-meta' }, item.projectName ?? item.projectKey ?? ''))));
246
- })) : h('div', { className: 'dab-empty' }, snapshot?.status === 'ready' ? 'No issues match this view.' : 'Connect Atlassian in Settings to see your Jira issues.'), board?.truncated ? h('p', { className: 'dab-message' }, `Showing up to ${String(board.limit)} issues. Narrow the query for more.`) : null, detail ? h('aside', { className: 'dab-detail', 'aria-label': 'Issue details' }, h('div', { className: 'dab-detail-head' }, h('span', { className: 'dab-eyebrow' }, 'Issue details'), h('button', { className: 'dab-button', onClick: () => setDetail(undefined) }, icon('close'), 'Close')), h('h3', { className: 'dab-title', style: { fontSize: 19, marginTop: 16 } }, detail.issue.key, ' ', detail.issue.summary), detail.issue.url ? h('p', { style: { marginTop: 8 } }, h('a', { className: 'dab-link', href: detail.issue.url, target: '_blank', rel: 'noreferrer' }, 'Open in Jira')) : null, h('pre', null, detail.description), h('div', { className: 'dab-row' }, ...detail.transitions.map((transition) => h('button', { key: transition.id, className: 'dab-button', onClick: () => { void api('/transition', 'POST', { key: detail.issue.key, transitionId: transition.id }).then(() => { setDetail(undefined); return refresh(jql); }).catch((error) => setMessage(error instanceof Error ? error.message : String(error))); } }, transition.toName || transition.name)))) : null);
291
+ })) : h('div', { className: 'dab-empty' }, snapshot?.status !== 'ready' ? 'Connect Atlassian in Settings to see your Jira issues.' : jiraConfigured ? 'No issues match this view.' : 'No Jira service is configured. Add a Jira URL in Settings.'), board?.truncated ? h('p', { className: 'dab-message' }, `Showing up to ${String(board.limit)} issues. Narrow the query for more.`) : null, detail ? h('aside', { className: 'dab-detail', 'aria-label': 'Issue details' }, h('div', { className: 'dab-detail-head' }, h('span', { className: 'dab-eyebrow' }, 'Issue details'), h('button', { className: 'dab-button', onClick: () => setDetail(undefined) }, icon('close'), 'Close')), h('h3', { className: 'dab-title', style: { fontSize: 19, marginTop: 16 } }, detail.issue.key, ' ', detail.issue.summary), detail.issue.url ? h('p', { style: { marginTop: 8 } }, h('a', { className: 'dab-link', href: detail.issue.url, target: '_blank', rel: 'noreferrer' }, 'Open in Jira')) : null, h('pre', null, detail.description), h('div', { className: 'dab-row' }, ...detail.transitions.map((transition) => h('button', { key: transition.id, className: 'dab-button', onClick: () => { void api('/transition', 'POST', { key: detail.issue.key, transitionId: transition.id }).then(() => { setDetail(undefined); return refresh(jql); }).catch((error) => setMessage(error instanceof Error ? error.message : String(error))); } }, transition.toName || transition.name)))) : null);
247
292
  }
248
293
  function BoardPanelIcon() {
249
294
  return h('svg', { viewBox: '0 0 24 24', width: 19, height: 19, fill: 'none', stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, h('rect', { x: 3, y: 4, width: 18, height: 16, rx: 3 }), h('path', { d: 'M9 4v16M15 4v16M5.8 8h.4M11.8 8h.4M17.8 8h.4' }));
package/lib/index.js CHANGED
@@ -7,9 +7,12 @@ import { SessionStore, sessionFileFor } from './store.js';
7
7
  export const name = 'atlassian';
8
8
  export const inject = ['tools'];
9
9
  export { Config };
10
+ function identityFor(settings) {
11
+ return settings.mode === 'server' ? `server:${settings.server.jiraUrl}\0${settings.server.confluenceUrl}` : settings.url;
12
+ }
10
13
  export function apply(ctx, config) {
11
14
  const scope = ctx;
12
- const identity = config.mode === 'server' ? `server:${config.server.jiraUrl}\0${config.server.confluenceUrl}` : config.url;
15
+ const identity = identityFor(config);
13
16
  const store = new SessionStore(sessionFileFor(config.serverName, identity, scope.profileContext?.patchPath));
14
17
  const host = { register: (definition) => ctx.tools.register(definition), logger: ctx.logger };
15
18
  const bridge = config.mode === 'server'
@@ -19,12 +22,16 @@ export function apply(ctx, config) {
19
22
  const connection = {
20
23
  snapshot: () => ({ ...config.server }),
21
24
  update: async (input) => {
22
- configureEndpoints(config, input);
25
+ const next = configureEndpoints(config, input);
23
26
  const editor = scope.get('configEditor');
24
27
  const entry = editor?.entries().find((candidate) => candidate.options.id === 'atlassian');
25
28
  if (!editor || !entry)
26
29
  throw new Error('DSH configuration editor is unavailable');
27
30
  await editor.edit(entry, (current) => configureEndpoints(Config(current), input));
31
+ if (identityFor(next) !== identity) {
32
+ // The profile now points at a different endpoint; leave no credentials behind for the old one.
33
+ void store.destroy().catch((error) => ctx.logger.warn(`atlassian: ${String(error)}`));
34
+ }
28
35
  },
29
36
  };
30
37
  ctx.effect(() => () => bridge.dispose(), 'atlassian:connection');
package/lib/oauth.js CHANGED
@@ -20,24 +20,46 @@ function limitCloudResponse(response, allowEvents) {
20
20
  }
21
21
  else {
22
22
  // SSE events end at an empty line. Track CR, LF and CRLF separately,
23
- // including separators split across network chunks.
24
- for (const byte of chunk) {
23
+ // including separators split across network chunks. Scan with native
24
+ // indexOf instead of a per-byte loop: this is the hot path for every
25
+ // Cloud MCP response.
26
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
27
+ let pos = 0;
28
+ if (afterCarriageReturn && buf.length > 0 && buf[0] === 10) {
25
29
  size++;
26
30
  if (size > MAX_CLOUD_RESPONSE_BYTES)
27
31
  throw new Error('Atlassian Cloud event exceeded the size limit');
28
- if (byte === 10 && afterCarriageReturn) {
32
+ afterCarriageReturn = false;
33
+ pos = 1;
34
+ }
35
+ while (pos < buf.length) {
36
+ const cr = buf.indexOf(13, pos);
37
+ const lf = buf.indexOf(10, pos);
38
+ if (cr === -1 && lf === -1) {
39
+ size += buf.length - pos;
40
+ if (size > MAX_CLOUD_RESPONSE_BYTES)
41
+ throw new Error('Atlassian Cloud event exceeded the size limit');
42
+ lineHasContent = true;
29
43
  afterCarriageReturn = false;
30
- continue;
31
- }
32
- if (byte === 10 || byte === 13) {
33
- if (!lineHasContent)
34
- size = 0;
35
- lineHasContent = false;
36
- afterCarriageReturn = byte === 13;
44
+ break;
37
45
  }
38
- else {
46
+ const term = cr !== -1 && (lf === -1 || cr < lf) ? cr : lf;
47
+ size += term - pos + 1;
48
+ if (size > MAX_CLOUD_RESPONSE_BYTES)
49
+ throw new Error('Atlassian Cloud event exceeded the size limit');
50
+ if (term > pos)
39
51
  lineHasContent = true;
52
+ if (!lineHasContent)
53
+ size = 0;
54
+ lineHasContent = false;
55
+ afterCarriageReturn = buf[term] === 13;
56
+ pos = term + 1;
57
+ if (afterCarriageReturn && pos < buf.length && buf[pos] === 10) {
58
+ size++;
59
+ if (size > MAX_CLOUD_RESPONSE_BYTES)
60
+ throw new Error('Atlassian Cloud event exceeded the size limit');
40
61
  afterCarriageReturn = false;
62
+ pos++;
41
63
  }
42
64
  }
43
65
  }
package/lib/routes.js CHANGED
@@ -4,15 +4,30 @@ function respond(res, status, value) {
4
4
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
5
5
  res.end(JSON.stringify(value));
6
6
  }
7
+ const BODY_TIMEOUT_MS = 30000;
7
8
  async function readBody(req) {
8
9
  const chunks = [];
9
10
  let size = 0;
10
- for await (const chunk of req) {
11
- const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
12
- size += data.length;
13
- if (size > 65536)
14
- throw new BoardError('too-large', 'Request body is too large');
15
- chunks.push(data);
11
+ let timedOut = false;
12
+ // A slow-drip body must not hold the handler open indefinitely.
13
+ const timer = setTimeout(() => { timedOut = true; req.destroy(); }, BODY_TIMEOUT_MS);
14
+ timer.unref();
15
+ try {
16
+ for await (const chunk of req) {
17
+ const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
18
+ size += data.length;
19
+ if (size > 65536)
20
+ throw new BoardError('too-large', 'Request body is too large');
21
+ chunks.push(data);
22
+ }
23
+ }
24
+ catch (error) {
25
+ if (timedOut)
26
+ throw new BoardError('request-timeout', 'Request body timed out');
27
+ throw error;
28
+ }
29
+ finally {
30
+ clearTimeout(timer);
16
31
  }
17
32
  if (!size)
18
33
  return {};
@@ -44,7 +59,14 @@ export function registerRoutes(web, bridge, board, options, fence, connection) {
44
59
  res.writeHead(rejection).end();
45
60
  return;
46
61
  }
47
- const url = new URL(req.url ?? '/', 'http://localhost');
62
+ let url;
63
+ try {
64
+ url = new URL(req.url ?? '/', 'http://localhost');
65
+ }
66
+ catch {
67
+ respond(res, 400, { ok: false, code: 'bad-request', error: 'Invalid request URL' });
68
+ return;
69
+ }
48
70
  const action = url.pathname.slice(ROUTE_PREFIX.length).replace(/^\//, '');
49
71
  const method = req.method ?? 'GET';
50
72
  try {
@@ -91,7 +113,13 @@ export function registerRoutes(web, bridge, board, options, fence, connection) {
91
113
  }
92
114
  const match = /^issue\/([^/]+)(\/transitions)?$/.exec(action);
93
115
  if (method === 'GET' && match) {
94
- const key = decodeURIComponent(match[1] ?? '');
116
+ let key;
117
+ try {
118
+ key = decodeURIComponent(match[1] ?? '');
119
+ }
120
+ catch {
121
+ throw new BoardError('bad-request', 'Invalid issue key encoding');
122
+ }
95
123
  if (match[2])
96
124
  respond(res, 200, { ok: true, transitions: await board.transitions(key, options.timeoutMs) });
97
125
  else
@@ -51,6 +51,7 @@ export class ServerBridge {
51
51
  #operations = new Map();
52
52
  #disposers = [];
53
53
  #controllers = new Set();
54
+ #http = new Set();
54
55
  #status = 'idle';
55
56
  #error;
56
57
  #disposed = false;
@@ -78,6 +79,7 @@ export class ServerBridge {
78
79
  }
79
80
  rawNames() { return [...this.#operations.keys()]; }
80
81
  rawNameMatching(pattern) { return this.rawNames().find((name) => pattern.test(name)); }
82
+ epoch() { return this.#generation; }
81
83
  async start() {
82
84
  if (this.#starting)
83
85
  return this.#starting;
@@ -142,36 +144,48 @@ export class ServerBridge {
142
144
  throw new Error('Enter Confluence credentials');
143
145
  const jira = jiraUrl && next.jira ? new ServerHttp(jiraUrl, next.jira, jiraCaFile, allowInsecureHttp) : undefined;
144
146
  const confluence = confluenceUrl && next.confluence ? new ServerHttp(confluenceUrl, next.confluence, confluenceCaFile, allowInsecureHttp) : undefined;
145
- if (jira) {
146
- const me = record(await this.#request(jira, 'GET', '/rest/api/2/myself'), 'Jira login response');
147
- if (typeof me['name'] !== 'string' && typeof me['key'] !== 'string')
148
- throw new Error('Jira did not return an authenticated user');
149
- current();
150
- }
151
- if (confluence) {
152
- const me = record(await this.#request(confluence, 'GET', '/rest/api/user/current'), 'Confluence login response');
153
- if (typeof me['username'] !== 'string' && typeof me['userKey'] !== 'string')
154
- throw new Error('Confluence did not return an authenticated user');
155
- current();
156
- }
157
- await this.#store.patch({ serverCredentials: next });
158
- current();
159
- const operations = this.#makeOperations(jira, confluence);
160
- this.#clearTools();
161
- const disposers = [];
147
+ const clients = [jira, confluence].filter((client) => !!client);
162
148
  try {
163
- for (const [rawName, op] of operations)
164
- disposers.push(this.#host.register(this.#definition(rawName, op)));
149
+ if (jira) {
150
+ const me = record(await this.#request(jira, 'GET', '/rest/api/2/myself'), 'Jira login response');
151
+ if (typeof me['name'] !== 'string' && typeof me['key'] !== 'string')
152
+ throw new Error('Jira did not return an authenticated user');
153
+ current();
154
+ }
155
+ if (confluence) {
156
+ const me = record(await this.#request(confluence, 'GET', '/rest/api/user/current'), 'Confluence login response');
157
+ if (typeof me['username'] !== 'string' && typeof me['userKey'] !== 'string')
158
+ throw new Error('Confluence did not return an authenticated user');
159
+ current();
160
+ }
161
+ await this.#store.patch({ serverCredentials: next });
162
+ current();
163
+ const operations = this.#makeOperations(jira, confluence);
164
+ this.#clearTools();
165
+ const disposers = [];
166
+ try {
167
+ for (const [rawName, op] of operations)
168
+ disposers.push(this.#host.register(this.#definition(rawName, op)));
169
+ }
170
+ catch (error) {
171
+ for (const dispose of disposers)
172
+ dispose();
173
+ throw error;
174
+ }
175
+ this.#credentials = next;
176
+ this.#operations = operations;
177
+ this.#disposers = disposers;
178
+ this.#status = 'ready';
165
179
  }
166
180
  catch (error) {
167
- for (const dispose of disposers)
168
- dispose();
181
+ for (const client of clients)
182
+ client.close();
169
183
  throw error;
170
184
  }
171
- this.#credentials = next;
172
- this.#operations = operations;
173
- this.#disposers = disposers;
174
- this.#status = 'ready';
185
+ // The replacement connection is live; release the previous pooled sockets.
186
+ for (const client of this.#http)
187
+ client.close();
188
+ this.#http = new Set(clients);
175
189
  }
176
190
  async disconnect() {
177
191
  this.#generation++;
@@ -181,6 +195,7 @@ export class ServerBridge {
181
195
  await this.#starting?.catch(() => undefined);
182
196
  await this.#running;
183
197
  this.#clearTools();
198
+ this.#closeHttp();
184
199
  await this.#store.destroy();
185
200
  this.#credentials = {};
186
201
  this.#status = 'idle';
@@ -198,6 +213,7 @@ export class ServerBridge {
198
213
  await this.#starting?.catch(() => undefined);
199
214
  await this.#running;
200
215
  this.#clearTools();
216
+ this.#closeHttp();
201
217
  }
202
218
  async callTool(rawName, args, timeoutMs) {
203
219
  const op = this.#operations.get(rawName);
@@ -211,6 +227,8 @@ export class ServerBridge {
211
227
  this.#disposers = [];
212
228
  this.#operations = new Map();
213
229
  }
230
+ #closeHttp() { for (const client of this.#http)
231
+ client.close(); this.#http.clear(); }
214
232
  #definition(rawName, op) {
215
233
  const definition = {
216
234
  name: publicToolName(this.#name, rawName),
@@ -8,6 +8,7 @@ export class ServerHttp {
8
8
  #base;
9
9
  #credential;
10
10
  #ca;
11
+ #agent;
11
12
  constructor(base, credential, caFile, allowInsecureHttp) {
12
13
  let url;
13
14
  try {
@@ -28,7 +29,15 @@ export class ServerHttp {
28
29
  this.#base = url;
29
30
  this.#credential = credential;
30
31
  this.#ca = caFile ? [...rootCertificates, readFileSync(caFile, 'utf8')] : undefined;
32
+ // Reuse connections across REST calls instead of a TCP/TLS handshake per request.
33
+ // Explicitly supplied trust anchors may be intermediates or a pinned
34
+ // self-signed server certificate. Keep hostname and TLS checks enabled.
35
+ this.#agent = url.protocol === 'https:'
36
+ ? new https.Agent({ keepAlive: true, maxSockets: 8, ...(this.#ca ? { ca: [...this.#ca], allowPartialTrustChain: true } : {}) })
37
+ : new http.Agent({ keepAlive: true, maxSockets: 8 });
31
38
  }
39
+ /** Release pooled sockets when the connection is replaced or torn down. */
40
+ close() { this.#agent.destroy(); }
32
41
  get baseUrl() { return this.#base.href.replace(/\/$/, ''); }
33
42
  async request(method, path, query = {}, body, timeoutMs = 60000, signal) {
34
43
  const target = new URL(this.#base.href);
@@ -56,10 +65,7 @@ export class ServerHttp {
56
65
  const transport = target.protocol === 'https:' ? https : http;
57
66
  const req = transport.request(target, {
58
67
  method,
59
- agent: false,
60
- // Explicitly supplied trust anchors may be intermediates or a pinned
61
- // self-signed server certificate. Keep hostname and TLS checks enabled.
62
- ...(target.protocol === 'https:' && this.#ca ? { ca: [...this.#ca], allowPartialTrustChain: true } : {}),
68
+ agent: this.#agent,
63
69
  headers: {
64
70
  accept: 'application/json',
65
71
  authorization,
@@ -5,6 +5,8 @@ export interface ToolBridge {
5
5
  status: string;
6
6
  error?: string | undefined;
7
7
  };
8
+ /** Changes whenever the connection is replaced, so cached site data can be invalidated. */
9
+ epoch?(): number;
8
10
  }
9
11
  export interface BoardStatus {
10
12
  name: string;
@@ -36,6 +36,7 @@ export declare function publicToolName(server: string, tool: string): string;
36
36
  export declare class AtlassianBridge {
37
37
  #private;
38
38
  constructor(host: BridgeHost, options: BridgeOptions);
39
+ epoch(): number;
39
40
  snapshot(): BridgeSnapshot;
40
41
  rawNames(): readonly string[];
41
42
  rawNameMatching(pattern: RegExp): string | undefined;
@@ -14,6 +14,7 @@ export declare class ServerBridge {
14
14
  snapshot(): BridgeSnapshot;
15
15
  rawNames(): readonly string[];
16
16
  rawNameMatching(pattern: RegExp): string | undefined;
17
+ epoch(): number;
17
18
  start(): Promise<void>;
18
19
  authorize(input?: Args): Promise<BridgeSnapshot>;
19
20
  disconnect(): Promise<BridgeSnapshot>;
@@ -3,6 +3,8 @@ import type { ServerCredential } from './store.js';
3
3
  export declare class ServerHttp {
4
4
  #private;
5
5
  constructor(base: string, credential: ServerCredential, caFile: string, allowInsecureHttp: boolean);
6
+ /** Release pooled sockets when the connection is replaced or torn down. */
7
+ close(): void;
6
8
  get baseUrl(): string;
7
9
  request(method: 'GET' | 'POST' | 'PUT', path: string, query?: Record<string, string | number | undefined>, body?: unknown, timeoutMs?: number, signal?: AbortSignal): Promise<unknown>;
8
10
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lornatang/dsh-atlassian",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "Connect Atlassian Cloud or self-hosted Jira and Confluence to DeepSeek Harness with tools and a Jira board.",
5
5
  "keywords": [
6
6
  "deepseek-harness",