@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/store.js CHANGED
@@ -3,6 +3,12 @@ import { constants } from 'node:fs';
3
3
  import { lstat, mkdir, open, rename, rm } from 'node:fs/promises';
4
4
  import { homedir } from 'node:os';
5
5
  import { dirname, join } from 'node:path';
6
+ import { DatabaseSync } from 'node:sqlite';
7
+ import { setTimeout as delay } from 'node:timers/promises';
8
+ /** Compare the bearer and refresh credentials, not object identity across reloads. */
9
+ export function sameTokens(left, right) {
10
+ return left === right || !!left && !!right && left.access_token === right.access_token && left.refresh_token === right.refresh_token;
11
+ }
6
12
  /** Keep credentials separate for each DSH profile and server. */
7
13
  export function sessionFileFor(serverName, url, patchPath) {
8
14
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(serverName)) {
@@ -60,45 +66,213 @@ async function secureExistingFile(file) {
60
66
  export class SessionStore {
61
67
  #file;
62
68
  #value = { version: 1 };
63
- #tail = Promise.resolve();
64
69
  constructor(file) { this.#file = file; }
65
70
  get file() { return this.#file; }
66
71
  get current() { return this.#value; }
67
- async load() {
68
- return this.#serialize(async () => {
69
- const handle = await secureExistingFile(this.#file);
70
- if (!handle)
71
- return this.#value = { version: 1 };
72
- let raw;
73
- try {
74
- raw = await handle.readFile('utf8');
75
- }
76
- finally {
77
- await handle.close();
78
- }
79
- let parsed;
80
- try {
81
- parsed = JSON.parse(raw.replace(/^\uFEFF/, ''));
82
- }
83
- catch (error) {
84
- throw new Error(`atlassian: invalid credential file: ${this.#file}`, { cause: error });
72
+ /** Hold an OS-backed lock across the complete OAuth refresh exchange. */
73
+ async acquire(signal) {
74
+ const lockFile = `${this.#file}.lock.sqlite`;
75
+ await mkdir(dirname(lockFile), { recursive: true, mode: 0o700 });
76
+ try {
77
+ await (await open(lockFile, 'wx', 0o600)).close();
78
+ }
79
+ catch (error) {
80
+ if (error.code !== 'EEXIST')
81
+ throw error;
82
+ }
83
+ // Opening and closing the lock database outside SQLite can drop every
84
+ // POSIX advisory lock that this process holds on the same inode.
85
+ const info = await lstat(lockFile);
86
+ if (!info.isFile())
87
+ throw new Error(`atlassian: session lock must be a regular file: ${lockFile}`);
88
+ if (process.platform !== 'win32') {
89
+ if (typeof process.geteuid === 'function' && info.uid !== process.geteuid())
90
+ throw new Error(`atlassian: session lock must be owned by the service user: ${lockFile}`);
91
+ if ((info.mode & 0o077) !== 0)
92
+ throw new Error(`atlassian: session lock must not be accessible to other users: ${lockFile}`);
93
+ }
94
+ const db = new DatabaseSync(lockFile);
95
+ let locked = false;
96
+ try {
97
+ for (;;) {
98
+ if (signal?.aborted)
99
+ throw new Error('atlassian: connection cancelled');
100
+ try {
101
+ db.exec('BEGIN IMMEDIATE');
102
+ locked = true;
103
+ break;
104
+ }
105
+ catch (error) {
106
+ const code = error.errcode;
107
+ if (code === undefined || (code & 0xff) !== 5)
108
+ throw error;
109
+ try {
110
+ await delay(25, undefined, { signal });
111
+ }
112
+ catch {
113
+ throw new Error('atlassian: connection cancelled');
114
+ }
115
+ }
85
116
  }
86
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || parsed.version !== 1) {
87
- throw new Error(`atlassian: invalid credential file: ${this.#file}`);
117
+ await this.#read();
118
+ let active = true;
119
+ let running = 0;
120
+ let closed = false;
121
+ const close = () => {
122
+ if (closed || active || running)
123
+ return;
124
+ closed = true;
125
+ try {
126
+ db.exec('ROLLBACK');
127
+ }
128
+ finally {
129
+ db.close();
130
+ }
131
+ };
132
+ return {
133
+ owner: this,
134
+ get active() { return active; },
135
+ async run(work) {
136
+ if (!active)
137
+ throw new Error('atlassian: invalid session lock');
138
+ running++;
139
+ try {
140
+ return await work();
141
+ }
142
+ finally {
143
+ running--;
144
+ close();
145
+ }
146
+ },
147
+ release() {
148
+ if (!active)
149
+ return;
150
+ active = false;
151
+ close();
152
+ },
153
+ };
154
+ }
155
+ catch (error) {
156
+ if (locked) {
157
+ try {
158
+ db.exec('ROLLBACK');
159
+ }
160
+ catch { /* closing also releases the lock */ }
88
161
  }
89
- this.#value = parsed;
90
- return this.#value;
91
- });
162
+ db.close();
163
+ throw error;
164
+ }
165
+ }
166
+ async #withLease(work, lease, signal) {
167
+ if (lease) {
168
+ if (lease.owner !== this || !lease.active)
169
+ throw new Error('atlassian: invalid session lock');
170
+ return lease.run(work);
171
+ }
172
+ const acquired = await this.acquire(signal);
173
+ try {
174
+ return await work();
175
+ }
176
+ finally {
177
+ acquired.release();
178
+ }
179
+ }
180
+ async load(signal) {
181
+ return this.#withLease(async () => this.#value, undefined, signal);
182
+ }
183
+ async #read() {
184
+ const handle = await secureExistingFile(this.#file);
185
+ if (!handle)
186
+ return this.#value = { version: 1 };
187
+ let raw;
188
+ try {
189
+ raw = await handle.readFile('utf8');
190
+ }
191
+ finally {
192
+ await handle.close();
193
+ }
194
+ let parsed;
195
+ try {
196
+ parsed = JSON.parse(raw.replace(/^\uFEFF/, ''));
197
+ }
198
+ catch (error) {
199
+ throw new Error(`atlassian: invalid credential file: ${this.#file}`, { cause: error });
200
+ }
201
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || parsed.version !== 1) {
202
+ throw new Error(`atlassian: invalid credential file: ${this.#file}`);
203
+ }
204
+ this.#value = parsed;
205
+ return this.#value;
92
206
  }
93
- async patch(patch) {
94
- await this.#serialize(async () => {
207
+ async patch(patch, active, lease, expected, signal, guard = false) {
208
+ await this.#withLease(async () => {
209
+ if (active && !active())
210
+ throw new Error('atlassian: connection cancelled');
211
+ if ((expected || guard) && !sameTokens(this.#value.tokens, expected))
212
+ throw new Error('atlassian: credentials changed; reconnect to continue');
95
213
  const next = { ...this.#value, ...patch, version: 1 };
96
214
  await this.#flush(next);
97
215
  this.#value = next;
98
- });
216
+ }, lease, signal);
217
+ }
218
+ /** A secondary process must not discard credentials merely because its callback port is busy. */
219
+ async prepareRedirect(actual, signal) {
220
+ await this.#withLease(async () => {
221
+ const previous = this.#value.redirectUri;
222
+ if (previous && previous !== actual && this.#value.tokens)
223
+ return;
224
+ const next = { ...this.#value, redirectUri: actual, version: 1 };
225
+ if (previous && previous !== actual) {
226
+ delete next.clientInformation;
227
+ delete next.tokens;
228
+ delete next.codeVerifier;
229
+ }
230
+ await this.#flush(next);
231
+ this.#value = next;
232
+ }, undefined, signal);
233
+ }
234
+ /** Re-register only when a new interactive flow needs a different callback. */
235
+ async rebindRedirect(actual, expected, active, lease, signal) {
236
+ await this.#withLease(async () => {
237
+ if (!active())
238
+ throw new Error('atlassian: connection cancelled');
239
+ if (this.#value.tokens && !sameTokens(this.#value.tokens, expected))
240
+ return;
241
+ const next = { ...this.#value, redirectUri: actual, version: 1 };
242
+ delete next.clientInformation;
243
+ delete next.tokens;
244
+ delete next.codeVerifier;
245
+ await this.#flush(next);
246
+ this.#value = next;
247
+ }, lease, signal);
248
+ }
249
+ async saveTokens(tokens, active, expected, lease, signal, guard = false) {
250
+ await this.#withLease(async () => {
251
+ if (!active())
252
+ throw new Error('atlassian: connection cancelled');
253
+ if ((expected || guard) && !sameTokens(this.#value.tokens, expected) && !sameTokens(this.#value.tokens, tokens))
254
+ return;
255
+ const next = { ...this.#value, tokens, version: 1 };
256
+ await this.#flush(next);
257
+ this.#value = next;
258
+ }, lease, signal);
259
+ }
260
+ async clearCredentialsIf(active, expected, lease, signal, guard, ...fields) {
261
+ await this.#withLease(async () => {
262
+ if (!active())
263
+ throw new Error('atlassian: connection cancelled');
264
+ if ((expected || guard) && !sameTokens(this.#value.tokens, expected))
265
+ return;
266
+ const next = { ...this.#value, version: 1 };
267
+ for (const field of fields)
268
+ if (field !== 'version')
269
+ delete next[field];
270
+ await this.#flush(next);
271
+ this.#value = next;
272
+ }, lease, signal);
99
273
  }
100
274
  async clear(...fields) {
101
- await this.#serialize(async () => {
275
+ await this.#withLease(async () => {
102
276
  const next = { ...this.#value, version: 1 };
103
277
  for (const field of fields)
104
278
  if (field !== 'version')
@@ -108,7 +282,7 @@ export class SessionStore {
108
282
  });
109
283
  }
110
284
  async destroy() {
111
- await this.#serialize(async () => {
285
+ await this.#withLease(async () => {
112
286
  await (await secureExistingFile(this.#file))?.close();
113
287
  await rm(this.#file, { force: true });
114
288
  this.#value = { version: 1 };
@@ -133,9 +307,4 @@ export class SessionStore {
133
307
  await rm(temporary, { force: true });
134
308
  }
135
309
  }
136
- #serialize(work) {
137
- const run = this.#tail.then(work, work);
138
- this.#tail = run.then(() => undefined, () => undefined);
139
- return run;
140
- }
141
310
  }
@@ -1,6 +1,6 @@
1
1
  import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
2
2
  import { type Logger } from './oauth.js';
3
- import type { SessionStore } from './store.js';
3
+ import { type SessionStore } from './store.js';
4
4
  export interface BridgeHost {
5
5
  register(definition: ToolDefinition): () => void;
6
6
  logger: Logger;
@@ -1,7 +1,7 @@
1
1
  import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
2
2
  import type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
3
3
  import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
4
- import type { SessionStore } from './store.js';
4
+ import type { SessionLease, SessionStore } from './store.js';
5
5
  export interface Logger {
6
6
  info(message: string): void;
7
7
  warn(message: string): void;
@@ -11,6 +11,9 @@ export interface AuthorizationCallback {
11
11
  code: string;
12
12
  state: string | undefined;
13
13
  }
14
+ export declare class RedirectRegistrationChanged extends Error {
15
+ }
16
+ export declare function secureUrl(url: URL, allowLoopbackHttp: boolean): void;
14
17
  /** Restrict every discovered OAuth and MCP endpoint, including redirect targets. */
15
18
  export declare function createCloudFetch(serverUrl: URL): {
16
19
  fetch: FetchLike;
@@ -32,6 +35,13 @@ export declare class AtlassianOAuthProvider implements OAuthClientProvider {
32
35
  onAuthorizationUrl: (url: string) => void;
33
36
  allowLoopbackHttp: boolean;
34
37
  logger: Logger;
38
+ active?: () => boolean;
39
+ tokenRead?: (tokens: OAuthTokens | undefined) => void;
40
+ refreshExpected?: () => OAuthTokens | undefined;
41
+ authFinished?: () => void;
42
+ lease?: () => SessionLease | undefined;
43
+ observedTokens?: () => OAuthTokens | undefined;
44
+ signal?: () => AbortSignal | undefined;
35
45
  });
36
46
  get redirectUrl(): string;
37
47
  get clientMetadata(): OAuthClientMetadata;
@@ -16,6 +16,14 @@ export interface ServerCredentials {
16
16
  jira?: ServerCredential;
17
17
  confluence?: ServerCredential;
18
18
  }
19
+ /** Compare the bearer and refresh credentials, not object identity across reloads. */
20
+ export declare function sameTokens(left: OAuthTokens | undefined, right: OAuthTokens | undefined): boolean;
21
+ export interface SessionLease {
22
+ readonly owner: SessionStore;
23
+ readonly active: boolean;
24
+ run<T>(work: () => Promise<T>): Promise<T>;
25
+ release(): void;
26
+ }
19
27
  /** Keep credentials separate for each DSH profile and server. */
20
28
  export declare function sessionFileFor(serverName: string, url: string, patchPath?: string): string;
21
29
  /** Serialize state changes and replace the file only after a complete write. */
@@ -24,8 +32,16 @@ export declare class SessionStore {
24
32
  constructor(file: string);
25
33
  get file(): string;
26
34
  get current(): StoredSession;
27
- load(): Promise<StoredSession>;
28
- patch(patch: Partial<StoredSession>): Promise<void>;
35
+ /** Hold an OS-backed lock across the complete OAuth refresh exchange. */
36
+ acquire(signal?: AbortSignal): Promise<SessionLease>;
37
+ load(signal?: AbortSignal): Promise<StoredSession>;
38
+ patch(patch: Partial<StoredSession>, active?: () => boolean, lease?: SessionLease, expected?: OAuthTokens, signal?: AbortSignal, guard?: boolean): Promise<void>;
39
+ /** A secondary process must not discard credentials merely because its callback port is busy. */
40
+ prepareRedirect(actual: string, signal?: AbortSignal): Promise<void>;
41
+ /** Re-register only when a new interactive flow needs a different callback. */
42
+ rebindRedirect(actual: string, expected: OAuthTokens | undefined, active: () => boolean, lease?: SessionLease, signal?: AbortSignal): Promise<void>;
43
+ saveTokens(tokens: OAuthTokens, active: () => boolean, expected?: OAuthTokens, lease?: SessionLease, signal?: AbortSignal, guard?: boolean): Promise<void>;
44
+ clearCredentialsIf(active: () => boolean, expected: OAuthTokens | undefined, lease: SessionLease | undefined, signal: AbortSignal | undefined, guard: boolean, ...fields: readonly (keyof StoredSession)[]): Promise<void>;
29
45
  clear(...fields: readonly (keyof StoredSession)[]): Promise<void>;
30
46
  destroy(): Promise<void>;
31
47
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lornatang/dsh-atlassian",
3
- "version": "0.1.6",
3
+ "version": "0.1.10",
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",
@@ -31,12 +31,14 @@
31
31
  "types": "./lib/types/client/index.d.ts",
32
32
  "default": "./lib/client.js"
33
33
  },
34
+ "./cordis.patch.yml": "./cordis.patch.yml",
34
35
  "./package.json": "./package.json"
35
36
  },
36
37
  "files": [
37
38
  "lib",
38
39
  "cordis.patch.yml",
39
40
  "README.md",
41
+ "README.zh.md",
40
42
  "CHANGELOG.md",
41
43
  "LICENSE",
42
44
  "NOTICE"