@lornatang/dsh-atlassian 0.1.6 → 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 +31 -0
- package/README.md +153 -156
- package/README.zh.md +181 -0
- package/lib/board.js +21 -4
- package/lib/bridge.js +232 -32
- package/lib/client.js +57 -12
- package/lib/index.js +9 -2
- package/lib/oauth.js +96 -27
- package/lib/routes.js +36 -8
- package/lib/server-bridge.js +43 -25
- package/lib/server-http.js +10 -4
- package/lib/store.js +203 -34
- package/lib/types/board.d.ts +2 -0
- package/lib/types/bridge.d.ts +2 -1
- package/lib/types/oauth.d.ts +11 -1
- package/lib/types/server-bridge.d.ts +1 -0
- package/lib/types/server-http.d.ts +2 -0
- package/lib/types/store.d.ts +18 -2
- package/package.json +3 -1
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) {
|
|
@@ -18,24 +20,46 @@ function limitCloudResponse(response, allowEvents) {
|
|
|
18
20
|
}
|
|
19
21
|
else {
|
|
20
22
|
// SSE events end at an empty line. Track CR, LF and CRLF separately,
|
|
21
|
-
// including separators split across network chunks.
|
|
22
|
-
|
|
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) {
|
|
23
29
|
size++;
|
|
24
30
|
if (size > MAX_CLOUD_RESPONSE_BYTES)
|
|
25
31
|
throw new Error('Atlassian Cloud event exceeded the size limit');
|
|
26
|
-
|
|
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;
|
|
27
43
|
afterCarriageReturn = false;
|
|
28
|
-
|
|
44
|
+
break;
|
|
29
45
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
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)
|
|
37
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');
|
|
38
61
|
afterCarriageReturn = false;
|
|
62
|
+
pos++;
|
|
39
63
|
}
|
|
40
64
|
}
|
|
41
65
|
}
|
|
@@ -54,7 +78,7 @@ function limitCloudResponse(response, allowEvents) {
|
|
|
54
78
|
function isLoopback(url) {
|
|
55
79
|
return ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
56
80
|
}
|
|
57
|
-
function secureUrl(url, allowLoopbackHttp) {
|
|
81
|
+
export function secureUrl(url, allowLoopbackHttp) {
|
|
58
82
|
if (url.username || url.password || (url.protocol !== 'https:' && !(allowLoopbackHttp && url.protocol === 'http:' && isLoopback(url)))) {
|
|
59
83
|
throw new Error('Cloud and OAuth endpoints must use HTTPS without embedded credentials');
|
|
60
84
|
}
|
|
@@ -184,40 +208,85 @@ export class AtlassianOAuthProvider {
|
|
|
184
208
|
#redirect;
|
|
185
209
|
#onUrl;
|
|
186
210
|
#allowLoopbackHttp;
|
|
211
|
+
#active;
|
|
212
|
+
#tokenRead;
|
|
213
|
+
#refreshExpected;
|
|
214
|
+
#authFinished;
|
|
215
|
+
#lease;
|
|
216
|
+
#observedTokens;
|
|
217
|
+
#signal;
|
|
187
218
|
constructor(options) {
|
|
188
219
|
this.#store = options.store;
|
|
189
220
|
this.#redirect = options.redirectUri;
|
|
190
221
|
this.#onUrl = options.onAuthorizationUrl;
|
|
191
222
|
this.#allowLoopbackHttp = options.allowLoopbackHttp;
|
|
223
|
+
this.#active = options.active ?? (() => true);
|
|
224
|
+
this.#tokenRead = options.tokenRead ?? (() => undefined);
|
|
225
|
+
this.#refreshExpected = options.refreshExpected ?? (() => undefined);
|
|
226
|
+
this.#authFinished = options.authFinished ?? (() => undefined);
|
|
227
|
+
this.#lease = options.lease ?? (() => undefined);
|
|
228
|
+
this.#observedTokens = options.observedTokens ?? (() => undefined);
|
|
229
|
+
this.#signal = options.signal ?? (() => undefined);
|
|
192
230
|
}
|
|
193
|
-
|
|
231
|
+
#check() { if (!this.#active())
|
|
232
|
+
throw new Error('atlassian: connection cancelled'); }
|
|
233
|
+
get redirectUrl() { this.#check(); return this.#redirect(); }
|
|
194
234
|
get clientMetadata() {
|
|
195
235
|
return { client_name: 'DSH Atlassian', redirect_uris: [this.redirectUrl], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none' };
|
|
196
236
|
}
|
|
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() {
|
|
201
|
-
async saveTokens(value) {
|
|
237
|
+
state() { this.#check(); return randomBytes(16).toString('hex'); }
|
|
238
|
+
clientInformation() { this.#check(); return this.#store.current.clientInformation; }
|
|
239
|
+
async saveClientInformation(value) { await this.#store.patch({ clientInformation: value }, this.#active, this.#lease(), this.#observedTokens(), this.#signal(), true); }
|
|
240
|
+
tokens() { this.#check(); const value = this.#store.current.tokens; this.#tokenRead(value); return value; }
|
|
241
|
+
async saveTokens(value) {
|
|
242
|
+
try {
|
|
243
|
+
await this.#store.saveTokens(value, this.#active, this.#refreshExpected() ?? this.#observedTokens(), this.#lease(), this.#signal(), true);
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
this.#authFinished();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
202
249
|
redirectToAuthorization(url) {
|
|
250
|
+
this.#check();
|
|
203
251
|
secureUrl(url, this.#allowLoopbackHttp);
|
|
204
252
|
this.#onUrl(url.href);
|
|
253
|
+
this.#authFinished();
|
|
254
|
+
}
|
|
255
|
+
async saveCodeVerifier(value) {
|
|
256
|
+
try {
|
|
257
|
+
const registered = this.#store.current.redirectUri;
|
|
258
|
+
const actual = this.#redirect();
|
|
259
|
+
if (registered && registered !== actual) {
|
|
260
|
+
await this.#store.rebindRedirect(actual, this.#observedTokens(), this.#active, this.#lease(), this.#signal());
|
|
261
|
+
throw new RedirectRegistrationChanged('atlassian: callback changed; restarting authorization');
|
|
262
|
+
}
|
|
263
|
+
await this.#store.patch({ codeVerifier: value }, this.#active, this.#lease(), this.#observedTokens(), this.#signal(), true);
|
|
264
|
+
}
|
|
265
|
+
finally {
|
|
266
|
+
this.#authFinished();
|
|
267
|
+
}
|
|
205
268
|
}
|
|
206
|
-
async saveCodeVerifier(value) { await this.#store.patch({ codeVerifier: value }); }
|
|
207
269
|
codeVerifier() {
|
|
270
|
+
this.#check();
|
|
208
271
|
const value = this.#store.current.codeVerifier;
|
|
209
272
|
if (!value)
|
|
210
273
|
throw new Error('missing PKCE verifier');
|
|
211
274
|
return value;
|
|
212
275
|
}
|
|
213
276
|
async invalidateCredentials(scope) {
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
277
|
+
try {
|
|
278
|
+
const expected = this.#refreshExpected() ?? this.#observedTokens();
|
|
279
|
+
if (scope === 'all')
|
|
280
|
+
await this.#store.clearCredentialsIf(this.#active, expected, this.#lease(), this.#signal(), true, 'tokens', 'clientInformation', 'codeVerifier');
|
|
281
|
+
else if (scope === 'client')
|
|
282
|
+
await this.#store.clearCredentialsIf(this.#active, expected, this.#lease(), this.#signal(), true, 'clientInformation');
|
|
283
|
+
else if (scope === 'tokens')
|
|
284
|
+
await this.#store.clearCredentialsIf(this.#active, expected, this.#lease(), this.#signal(), true, 'tokens');
|
|
285
|
+
else if (scope === 'verifier')
|
|
286
|
+
await this.#store.clearCredentialsIf(this.#active, expected, this.#lease(), this.#signal(), true, 'codeVerifier');
|
|
287
|
+
}
|
|
288
|
+
finally {
|
|
289
|
+
this.#authFinished();
|
|
290
|
+
}
|
|
222
291
|
}
|
|
223
292
|
}
|
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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
package/lib/server-bridge.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
164
|
-
|
|
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
|
|
168
|
-
|
|
181
|
+
for (const client of clients)
|
|
182
|
+
client.close();
|
|
169
183
|
throw error;
|
|
170
184
|
}
|
|
171
|
-
|
|
172
|
-
this.#
|
|
173
|
-
|
|
174
|
-
this.#
|
|
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),
|
package/lib/server-http.js
CHANGED
|
@@ -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:
|
|
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,
|
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
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
|
|
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
|
-
|
|
87
|
-
|
|
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
|
-
|
|
90
|
-
|
|
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.#
|
|
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.#
|
|
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.#
|
|
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
|
}
|