@gitkraken/core-gitlens 0.52.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist/_types/provider-apis/types/exportedTypes/github.d.ts +75 -0
  3. package/dist/_types/provider-apis/types/exportedTypes/types.d.ts +7 -0
  4. package/dist/plus/git-github/api/issueWrites.js +1 -1
  5. package/dist/plus/git-github/api/issueWrites.js.map +1 -1
  6. package/dist/plus/integrations/authentication/cloudIntegrationAuthenticationProvider.d.ts +5 -1
  7. package/dist/plus/integrations/authentication/cloudIntegrationAuthenticationProvider.js +44 -20
  8. package/dist/plus/integrations/authentication/cloudIntegrationAuthenticationProvider.js.map +1 -1
  9. package/dist/plus/integrations/authentication/cloudIntegrationObservations.d.ts +49 -0
  10. package/dist/plus/integrations/authentication/cloudIntegrationObservations.js +118 -0
  11. package/dist/plus/integrations/authentication/cloudIntegrationObservations.js.map +1 -0
  12. package/dist/plus/integrations/authentication/configuredIntegrationService.d.ts +38 -25
  13. package/dist/plus/integrations/authentication/configuredIntegrationService.js +376 -141
  14. package/dist/plus/integrations/authentication/configuredIntegrationService.js.map +1 -1
  15. package/dist/plus/integrations/authentication/integrationAuthenticationService.d.ts +8 -2
  16. package/dist/plus/integrations/authentication/integrationAuthenticationService.js +34 -4
  17. package/dist/plus/integrations/authentication/integrationAuthenticationService.js.map +1 -1
  18. package/dist/plus/integrations/authentication/models.d.ts +6 -0
  19. package/dist/plus/integrations/authentication/models.js +9 -1
  20. package/dist/plus/integrations/authentication/models.js.map +1 -1
  21. package/dist/plus/integrations/authentication/observedAuthenticationProvider.d.ts +13 -2
  22. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js +68 -30
  23. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js.map +1 -1
  24. package/dist/plus/integrations/index.d.ts +2 -1
  25. package/dist/plus/integrations/index.js.map +1 -1
  26. package/dist/plus/integrations/integrationService.d.ts +8 -0
  27. package/dist/plus/integrations/integrationService.js +148 -36
  28. package/dist/plus/integrations/integrationService.js.map +1 -1
  29. package/dist/plus/integrations/manager.d.ts +3 -0
  30. package/dist/plus/integrations/models/integration.d.ts +4 -0
  31. package/dist/plus/integrations/models/integration.js +61 -16
  32. package/dist/plus/integrations/models/integration.js.map +1 -1
  33. package/dist/plus/integrations/models/issueRelationships.d.ts +31 -0
  34. package/dist/plus/integrations/models/issueRelationships.js +0 -0
  35. package/dist/plus/integrations/models/publicIntegration.d.ts +0 -1
  36. package/dist/plus/integrations/providers/github.d.ts +8 -0
  37. package/dist/plus/integrations/providers/github.js +162 -2
  38. package/dist/plus/integrations/providers/github.js.map +1 -1
  39. package/dist/plus/integrations/providers/issueSorts.d.ts +0 -1
  40. package/dist/plus/integrations/providers/providerApiClient.d.ts +1 -1
  41. package/dist/plus/integrations/providers/providerApiClient.js +33 -14
  42. package/dist/plus/integrations/providers/providerApiClient.js.map +1 -1
  43. package/dist/plus/integrations/providers/providerErrors.d.ts +1 -0
  44. package/dist/plus/integrations/providers/providerErrors.js +1 -2
  45. package/dist/plus/integrations/providers/providerErrors.js.map +1 -1
  46. package/dist/plus/integrations/providers/providersApi.d.ts +2 -1
  47. package/dist/plus/integrations/providers/providersApi.js +2 -0
  48. package/dist/plus/integrations/providers/providersApi.js.map +1 -1
  49. package/dist/plus/integrations/reads/drains.d.ts +0 -1
  50. package/docs/integrations.md +36 -0
  51. package/package.json +2 -2
@@ -5,31 +5,25 @@ import "../constants.js";
5
5
  import { providersMetadata } from "../providers/metadata.js";
6
6
  import { areDomainsOnSameHost, baseUrlFromDomain, hostFromDomain, sameConfiguredBaseUrl } from "../utils/domain.utils.js";
7
7
  import { isSelfManagedHostIntegrationId } from "../utils/integration.utils.js";
8
- import { getSessionIdentity } from "./models.js";
8
+ import { getSessionIdentity, getSupportedCloudIntegrationIds, isSameAuthenticationSession, sessionExpiry } from "./models.js";
9
+ import { CloudIntegrationObservations } from "./cloudIntegrationObservations.js";
9
10
  //#region ../plus/integrations/src/authentication/configuredIntegrationService.ts
10
- const storedWriteRetirements = /* @__PURE__ */ new WeakMap();
11
+ const cloudLogoutKey = "integrations:cloudLogout";
12
+ const configuredStorageState = /* @__PURE__ */ new WeakMap();
11
13
  var ConfiguredIntegrationService = class {
12
14
  ctx;
13
15
  _onDidChange = new Emitter();
14
16
  _onWillChangeSession = new Emitter();
15
17
  _onWillRemoveSessions = new Emitter();
16
- storeConfiguredQueue = Promise.resolve();
17
- /**
18
- * One provider's secret and descriptor mutations run one at a time, so a sign-out never interleaves with a
19
- * token being stored: storing writes the secret and then registers its descriptor, and a delete in between would
20
- * miss a connection it cannot see yet, or be undone by the pending write (#5948).
21
- */
22
- _locks = /* @__PURE__ */ new Map();
23
18
  _acquisitions = /* @__PURE__ */ new Map();
24
- /** Monotonic across providers; see {@link getSignOutMark}. */
25
- _signOutEpoch = 0;
26
- /** The latest retirement of pending stores per provider, self-managed host, or connection. */
27
- _signOuts = /* @__PURE__ */ new Map();
28
- _storedWriteRetirements;
19
+ state;
29
20
  _disposed = false;
30
21
  get onDidChange() {
31
22
  return this._onDidChange.event;
32
23
  }
24
+ get onCloudLogout() {
25
+ return this.state.onCloudLogout.event;
26
+ }
33
27
  get onWillChangeSession() {
34
28
  return this._onWillChangeSession.event;
35
29
  }
@@ -38,15 +32,23 @@ var ConfiguredIntegrationService = class {
38
32
  }
39
33
  constructor(ctx) {
40
34
  this.ctx = ctx;
41
- let retirements = storedWriteRetirements.get(ctx.storage);
42
- if (retirements == null) {
43
- retirements = {
35
+ let state = configuredStorageState.get(ctx.storage);
36
+ if (state == null) {
37
+ state = {
38
+ persistence: Promise.resolve(),
39
+ locks: /* @__PURE__ */ new Map(),
44
40
  epoch: 0,
45
- scopes: /* @__PURE__ */ new Map()
41
+ scopes: /* @__PURE__ */ new Map(),
42
+ signOuts: /* @__PURE__ */ new Map(),
43
+ publications: /* @__PURE__ */ new Map(),
44
+ removals: /* @__PURE__ */ new Map(),
45
+ cloud: new CloudIntegrationObservations(ctx.storage.get(cloudLogoutKey)),
46
+ onCloudLogout: new Emitter(),
47
+ expiries: /* @__PURE__ */ new Map()
46
48
  };
47
- storedWriteRetirements.set(ctx.storage, retirements);
49
+ configuredStorageState.set(ctx.storage, state);
48
50
  }
49
- this._storedWriteRetirements = retirements;
51
+ this.state = state;
50
52
  }
51
53
  dispose() {
52
54
  this._disposed = true;
@@ -54,10 +56,9 @@ var ConfiguredIntegrationService = class {
54
56
  this._onWillChangeSession.dispose();
55
57
  this._onWillRemoveSessions.dispose();
56
58
  }
57
- _configured;
58
59
  get configured() {
59
- if (this._configured == null) {
60
- this._configured = /* @__PURE__ */ new Map();
60
+ if (this.state.configured == null) {
61
+ this.state.configured = /* @__PURE__ */ new Map();
61
62
  const storedConfigured = this.ctx.storage.get("integrations:configured");
62
63
  for (const [id, configured] of Object.entries(storedConfigured ?? {})) {
63
64
  if (configured == null) continue;
@@ -68,10 +69,10 @@ var ConfiguredIntegrationService = class {
68
69
  id: d.id || d.domain || providersMetadata[id]?.domain || id,
69
70
  expiresAt: d.expiresAt ? new Date(d.expiresAt) : void 0
70
71
  }));
71
- this._configured.set(id, descriptors);
72
+ this.state.configured.set(id, descriptors);
72
73
  }
73
74
  }
74
- return this._configured;
75
+ return this.state.configured;
75
76
  }
76
77
  getConfigured(id, options) {
77
78
  const descriptors = [];
@@ -84,15 +85,21 @@ var ConfiguredIntegrationService = class {
84
85
  else descriptors.push(...configured);
85
86
  return descriptors;
86
87
  }
87
- async storeConfigured() {
88
- const configured = {};
89
- for (const [id, descriptors] of this.configured) configured[id] = descriptors.map((d) => ({
90
- ...d,
91
- expiresAt: d.expiresAt ? d.expiresAt instanceof Date ? d.expiresAt.toISOString() : d.expiresAt : void 0
92
- }));
93
- const pending = this.storeConfiguredQueue.then(() => this.ctx.storage.store("integrations:configured", configured));
94
- this.storeConfiguredQueue = pending.catch(() => {});
95
- await pending;
88
+ storeConfigured(id, descriptors) {
89
+ const pending = this.state.persistence.then(async () => {
90
+ const updated = new Map(this.configured);
91
+ if (descriptors == null) updated.delete(id);
92
+ else updated.set(id, descriptors);
93
+ const record = {};
94
+ for (const [providerId, connections] of updated) record[providerId] = connections.map((connection) => ({
95
+ ...connection,
96
+ expiresAt: connection.expiresAt instanceof Date ? connection.expiresAt.toISOString() : connection.expiresAt
97
+ }));
98
+ await this.ctx.storage.store("integrations:configured", record);
99
+ this.state.configured = updated;
100
+ });
101
+ this.state.persistence = pending.catch(() => {});
102
+ return pending;
96
103
  }
97
104
  async addOrUpdateConfigured(descriptor) {
98
105
  descriptor = {
@@ -100,7 +107,7 @@ var ConfiguredIntegrationService = class {
100
107
  baseUrl: isSelfManagedHostIntegrationId(descriptor.integrationId) ? getStoredBaseUrl(descriptor.baseUrl, descriptor.domain) : descriptor.baseUrl,
101
108
  domain: this.normalizeConfiguredDomain(descriptor.integrationId, descriptor.domain)
102
109
  };
103
- const descriptors = this.configured.get(descriptor.integrationId) ?? [];
110
+ const descriptors = [...this.configured.get(descriptor.integrationId) ?? []];
104
111
  const existing = descriptors.find((d) => d.id === descriptor.id && d.cloud === descriptor.cloud);
105
112
  const primaryScope = this.getPrimaryScope(descriptor.integrationId, descriptors, descriptor.domain);
106
113
  const primary = descriptor.primary ?? existing?.primary ?? !primaryScope.some((d) => d.primary);
@@ -122,9 +129,8 @@ var ConfiguredIntegrationService = class {
122
129
  descriptors.splice(descriptors.indexOf(existing), 1);
123
130
  } else changed = true;
124
131
  descriptors.push(normalized);
125
- this.configured.set(descriptor.integrationId, descriptors);
132
+ await this.storeConfigured(descriptor.integrationId, descriptors);
126
133
  if (changed) this.fireChange(descriptor.integrationId);
127
- await this.storeConfigured();
128
134
  }
129
135
  async removeConfigured(id, options) {
130
136
  const existing = this.configured.get(id);
@@ -147,16 +153,16 @@ var ConfiguredIntegrationService = class {
147
153
  primary: true
148
154
  };
149
155
  }
150
- this.configured.set(id, descriptors);
156
+ await this.storeConfigured(id, descriptors);
151
157
  this.fireChange(void 0, id);
152
- await this.storeConfigured();
153
158
  }
154
159
  withLock(id, fn) {
155
- const run = (this._locks.get(id) ?? Promise.resolve()).then(fn);
160
+ const locks = this.state.locks;
161
+ const run = (locks.get(id) ?? Promise.resolve()).then(fn);
156
162
  const settled = run.then(() => void 0, () => void 0);
157
- this._locks.set(id, settled);
163
+ locks.set(id, settled);
158
164
  settled.then(() => {
159
- if (this._locks.get(id) === settled) this._locks.delete(id);
165
+ if (locks.get(id) === settled) locks.delete(id);
160
166
  });
161
167
  return run;
162
168
  }
@@ -196,30 +202,180 @@ var ConfiguredIntegrationService = class {
196
202
  * that replaces the credential invalidates the pending store.
197
203
  */
198
204
  getSignOutMark() {
199
- return this._signOutEpoch;
205
+ return ++this.state.epoch;
206
+ }
207
+ retirePendingStores(scope, cloud) {
208
+ this.retireStoredWrites(scope, cloud);
209
+ this.state.signOuts.set(cloud == null ? scope : `${scope}|${cloud}`, this.getStoredWriteMark());
210
+ }
211
+ beginCloudSync() {
212
+ return ++this.state.epoch;
213
+ }
214
+ get lastCloudLogout() {
215
+ return this.state.cloud.lastLogout;
216
+ }
217
+ get hasCloudLogout() {
218
+ return this.state.cloud.hasLogout;
219
+ }
220
+ async retireCloudAccount(mark) {
221
+ if (this._disposed) return void 0;
222
+ const connections = this.getConfigured(void 0, { cloud: true });
223
+ const sync = this.state.cloud.acceptLogout(mark, ++this.state.epoch, connections);
224
+ if (sync == null) return void 0;
225
+ const persist = this.persistCloudLogout();
226
+ const departing = connections.map((c) => ({
227
+ ...c,
228
+ retained: this.state.cloud.acquiredAfter(`${c.integrationId}|connection:${c.id}`, mark)
229
+ }));
230
+ const cleanup = getSupportedCloudIntegrationIds().map((id) => this.withLock(id, () => this.clearDepartedCloudCredentials(id, mark, sync.mark)));
231
+ this.state.onCloudLogout.fire(departing);
232
+ const failure = (await Promise.allSettled([persist, ...cleanup])).find((result) => result.status === "rejected");
233
+ if (failure != null) throw failure.reason;
234
+ return this._disposed ? void 0 : sync;
235
+ }
236
+ persistCloudLogout() {
237
+ const pending = this.state.persistence.then(() => this.ctx.storage.store(cloudLogoutKey, this.state.cloud.snapshotLogout()));
238
+ this.state.persistence = pending.catch(() => {});
239
+ return pending;
240
+ }
241
+ async clearDepartedCloudCredentials(id, cutoff, logout) {
242
+ const connections = this.getConfigured(id);
243
+ const ids = new Set(connections.map((c) => c.id));
244
+ ids.add(providersMetadata[id]?.domain || id);
245
+ const failures = [];
246
+ for (const connectionId of ids) try {
247
+ const localKey = this.getLocalSecretKey(id, connectionId);
248
+ const raw = await this.ctx.storage.getSecret(localKey);
249
+ if (raw != null && isLegacyCloudSecret(raw)) {
250
+ await this.ctx.storage.deleteSecret(localKey);
251
+ await this.removeConfigured(id, {
252
+ connectionId,
253
+ cloud: false
254
+ });
255
+ }
256
+ const scope = `${id}|connection:${connectionId}`;
257
+ if (this.state.cloud.acquiredAfter(scope, cutoff)) continue;
258
+ const departed = connections.find((c) => c.id === connectionId && c.cloud);
259
+ if (departed != null && this.state.cloud.depart(id, departed.domain, connectionId, logout)) await this.persistCloudLogout();
260
+ try {
261
+ await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, connectionId));
262
+ } finally {
263
+ this.state.cloud.remove(scope);
264
+ await this.removeConfigured(id, {
265
+ connectionId,
266
+ cloud: true
267
+ });
268
+ }
269
+ } catch (ex) {
270
+ failures.push(ex);
271
+ }
272
+ if (failures.length) throw new AggregateError(failures, "Unable to clear retired cloud credentials.");
273
+ }
274
+ getCloudDeparture(id, session) {
275
+ return session.cloud ? this.state.cloud.departedAt(id, session.domain, session.id) : void 0;
200
276
  }
201
- retirePendingStores(scope) {
202
- this._signOuts.set(scope, ++this._signOutEpoch);
203
- this.retireStoredWrites(scope);
277
+ confirmHostCloudSession(id, session, logout) {
278
+ return this.withLock(id, async () => {
279
+ if (this._disposed) return false;
280
+ const departure = this.getCloudDeparture(id, session);
281
+ if (departure != null && logout < departure) return false;
282
+ const stored = await this.peekSecret(id, session.id, true, session.domain);
283
+ if (this._disposed || logout !== this.lastCloudLogout || stored === null) return false;
284
+ if (stored === void 0) return departure == null && !this.getConfigured(id, {
285
+ cloud: true,
286
+ domain: isSelfManagedHostIntegrationId(id) ? session.domain : void 0
287
+ }).some((c) => c.id === session.id);
288
+ return stored.id === session.id && stored.cloud && stored.accessToken === session.accessToken && (!stored.account.id || stored.account.id === session.account.id);
289
+ });
290
+ }
291
+ async acceptCloudSync(mark, connections) {
292
+ if (this._disposed) return void 0;
293
+ const sync = this.state.cloud.accept(mark, connections);
294
+ if (sync == null) return void 0;
295
+ await Promise.all(this.state.locks.values());
296
+ return !this._disposed && sync.isCurrent() ? sync : void 0;
297
+ }
298
+ supersedingPrimary(id, session, mark) {
299
+ return this.state.cloud.supersedingPrimary(id, session.domain, session.id, mark);
300
+ }
301
+ hasNewCloudConnection(id, domain, mark) {
302
+ const scopedDomain = isSelfManagedHostIntegrationId(id) ? domain : void 0;
303
+ return this.getConfigured(id, {
304
+ cloud: true,
305
+ domain: scopedDomain
306
+ }).some((c) => this.state.cloud.observedSince(`${id}|connection:${c.id}`, mark));
307
+ }
308
+ async dispatchHostListRetirement(id, domain, sync, retire) {
309
+ const dispatched = await this.withLock(id, () => {
310
+ if (this._disposed || !sync.isCurrent() || this.hasNewCloudConnection(id, domain, sync.mark)) return;
311
+ return { settled: retire() };
312
+ });
313
+ if (dispatched == null) return false;
314
+ await dispatched.settled;
315
+ return !this._disposed && sync.isCurrent() && !this.hasNewCloudConnection(id, domain, sync.mark);
204
316
  }
205
317
  getStoredWriteMark() {
206
- return this._storedWriteRetirements.epoch;
318
+ return this.state.epoch;
207
319
  }
208
320
  isStoredWriteRetiredSince(id, session, mark) {
209
- return this._disposed || this.hasRetirement(this._storedWriteRetirements.scopes, id, session, mark);
321
+ return this._disposed || session.cloud && this.state.cloud.loggedOutSince(mark) || this.hasRetirement(this.state.scopes, id, session, mark);
322
+ }
323
+ async captureConfiguredConnection(id, connectionId) {
324
+ const matches = this.getConfigured(id).filter((connection) => connection.id === connectionId);
325
+ const selected = matches.find((connection) => connection.cloud) ?? matches[0];
326
+ if (selected == null) return void 0;
327
+ const mark = this.state.epoch;
328
+ const scope = {
329
+ id: connectionId,
330
+ domain: selected.domain ?? "",
331
+ cloud: selected.cloud
332
+ };
333
+ const current = () => !this._disposed && !(selected.cloud && this.state.cloud.loggedOutSince(mark)) && !this.hasRetirement(this.state.removals, id, scope, mark) && this.configured.get(id)?.some((connection) => connection.id === connectionId && connection.cloud === selected.cloud) === true;
334
+ return this.withLock(id, async () => {
335
+ if (selected.cloud && this.hasCloudLogout && await this.peekSecret(id, connectionId, true, scope.domain) == null) return;
336
+ return current() ? current : void 0;
337
+ });
338
+ }
339
+ async duringRemoval(scope, cloud, remove) {
340
+ const key = cloud == null ? scope : `${scope}|${cloud}`;
341
+ this.retirePendingStores(scope, cloud);
342
+ this.state.removals.set(key, Infinity);
343
+ try {
344
+ await remove();
345
+ } finally {
346
+ const mark = ++this.state.epoch;
347
+ this.state.removals.set(key, mark);
348
+ this.state.signOuts.set(key, mark);
349
+ }
210
350
  }
211
- retireStoredWrites(scope) {
212
- const retirements = this._storedWriteRetirements;
213
- retirements.scopes.set(scope, ++retirements.epoch);
351
+ captureStoredRelationshipCurrency(id, session) {
352
+ return this.withLock(id, async () => {
353
+ const mark = this.getStoredWriteMark();
354
+ const stored = await this.peekSecret(id, session.id, session.cloud, session.domain);
355
+ if (this.isStoredWriteRetiredSince(id, session, mark) || stored == null || !isSameAuthenticationSession(stored, session)) return;
356
+ const scope = `${id}|connection:${session.id}|${session.cloud}`;
357
+ const expiries = this.state.expiries;
358
+ if (expiries.get(scope) === null) return void 0;
359
+ expiries.set(scope, sessionExpiry(stored.expiresAt));
360
+ return () => !this.isStoredWriteRetiredSince(id, session, mark) && (expiries.get(scope) ?? 0) > Date.now();
361
+ });
362
+ }
363
+ retireStoredWrites(scope, cloud) {
364
+ const retirements = this.state;
365
+ retirements.scopes.set(cloud == null ? scope : `${scope}|${cloud}`, ++retirements.epoch);
366
+ for (const variant of cloud == null ? [true, false] : [cloud]) {
367
+ const key = `${scope}|${variant}`;
368
+ if (retirements.expiries.get(key) !== null) retirements.expiries.delete(key);
369
+ }
214
370
  }
215
371
  getHostScope(id, domain) {
216
372
  return `${id}|host:${hostFromDomain(domain) ?? domain}`;
217
373
  }
218
- isSessionRetiredSince(id, session, mark) {
219
- return this.hasRetirement(this._signOuts, id, session, mark);
374
+ isSessionRetiredSince(id, session, mark, acquisitionMark = mark) {
375
+ return session.cloud !== false && !this.state.cloud.allows(this.state.cloud.origin(mark)) || this.hasRetirement(this.state.signOuts, id, session, mark) || this.hasRetirement(this.state.publications, id, session, acquisitionMark);
220
376
  }
221
377
  hasRetirement(scopes, id, session, mark) {
222
- const since = (scope) => (scopes.get(scope) ?? 0) > mark;
378
+ const since = (scope) => (scopes.get(scope) ?? 0) > mark || session.cloud !== false && (scopes.get(`${scope}|true`) ?? 0) > mark || session.cloud !== true && (scopes.get(`${scope}|false`) ?? 0) > mark;
223
379
  if (since(id)) return true;
224
380
  if (isSelfManagedHostIntegrationId(id) && session.domain && since(this.getHostScope(id, session.domain))) return true;
225
381
  return since(`${id}|connection:${session.id}`);
@@ -229,57 +385,105 @@ var ConfiguredIntegrationService = class {
229
385
  * credential recovery. A recovery must still own the stored credential when it publishes its replacement.
230
386
  */
231
387
  storeSession(id, session, options) {
388
+ const origin = session.cloud ? this.state.cloud.origin(options?.sync?.mark ?? options?.signOutMark ?? this.getSignOutMark()) : void 0;
232
389
  return this.withLock(id, async () => {
233
- if (options?.signOutMark != null && this.isSessionRetiredSince(id, session, options.signOutMark)) return false;
234
- const previous = await this.readSecret(id, session.id, session.cloud);
235
- if (options?.expectedStoredAccessToken != null && previous?.accessToken !== options.expectedStoredAccessToken) return false;
236
- if (getSessionIdentity(previous) !== getSessionIdentity(session)) {
237
- if (previous != null) this.retireStoredWrites(`${id}|connection:${session.id}`);
238
- this._onWillChangeSession.fire({
239
- integrationId: id,
240
- session,
241
- previousDomain: previous?.domain
242
- });
390
+ const canStore = () => !this._disposed && (origin == null || this.state.cloud.allows(origin)) && options?.sync?.isCurrent() !== false && (options?.signOutMark == null || !this.isSessionRetiredSince(id, session, options.signOutMark, options.acquisitionMark));
391
+ if (!canStore()) return false;
392
+ const scope = `${id}|connection:${session.id}`;
393
+ const expiryScope = `${scope}|${session.cloud}`;
394
+ const expiries = this.state.expiries;
395
+ const previous = await this.peekSecret(id, session.id, session.cloud, session.domain);
396
+ if (options?.primaryResponse === "legacy" && options.signOutMark != null && this.state.cloud.observedSince(scope, options.signOutMark) || !canStore() || options?.expectedStoredAccessToken != null && previous?.accessToken !== options.expectedStoredAccessToken) return false;
397
+ const changed = getSessionIdentity(previous) !== getSessionIdentity(session);
398
+ const replaced = changed || previous?.account?.id !== session.account?.id;
399
+ if (replaced) this.retireStoredWrites(scope, session.cloud);
400
+ if (changed) this._onWillChangeSession.fire({
401
+ integrationId: id,
402
+ session,
403
+ previousDomain: previous?.domain
404
+ });
405
+ if (!canStore()) return false;
406
+ const trackedExpiry = expiries.get(expiryScope);
407
+ const nextExpiry = sessionExpiry(session.expiresAt);
408
+ if (typeof trackedExpiry === "number") expiries.set(expiryScope, Math.min(trackedExpiry, nextExpiry));
409
+ const logoutAtDispatch = this.lastCloudLogout;
410
+ try {
411
+ await this.writeSecret(id, session, options?.resource, origin);
412
+ } catch (ex) {
413
+ if (origin != null && !this.state.cloud.allows(origin)) throw ex;
414
+ this.retirePendingStores(scope, session.cloud);
415
+ if (session.cloud) this.state.cloud.observe(scope, this.state.epoch);
416
+ expiries.set(expiryScope, null);
417
+ throw ex;
418
+ }
419
+ if (origin != null && !this.state.cloud.allows(origin)) return false;
420
+ if (origin != null) this.state.cloud.published(scope, origin.mark);
421
+ if (expiries.has(expiryScope)) expiries.set(expiryScope, nextExpiry);
422
+ if (replaced || nextExpiry !== sessionExpiry(previous?.expiresAt)) {
423
+ const mark = session.cloud && this.lastCloudLogout !== logoutAtDispatch ? this.lastCloudLogout : ++this.state.epoch;
424
+ this.state.publications.set(expiryScope, mark);
425
+ if (options?.expectedStoredAccessToken != null && session.accessToken !== options.expectedStoredAccessToken) this.state.signOuts.set(expiryScope, mark);
426
+ }
427
+ if (session.cloud && options?.primaryResponse !== "legacy") {
428
+ this.state.cloud.observe(scope, options?.sync?.isCurrent() === false ? options.sync.mark : ++this.state.epoch);
429
+ if (options?.primaryResponse === "named" && options.signOutMark != null && options.sync?.isCurrent() !== false && this.supersedingPrimary(id, session, options.signOutMark) == null) {
430
+ const primaryMark = ++this.state.epoch;
431
+ await this.setPrimaryConnectionCore(id, session.id);
432
+ this.state.cloud.observePrimary(id, session.domain, session.id, primaryMark);
433
+ }
243
434
  }
244
- await this.writeSecret(id, session, options?.resource);
245
- if (options?.expectedStoredAccessToken != null && session.accessToken !== options.expectedStoredAccessToken) this.retirePendingStores(`${id}|connection:${session.id}`);
246
435
  return true;
247
436
  });
248
437
  }
249
- async peekStoredSession(id, connectionId, cloud, domain) {
438
+ peekStoredSession(id, connectionId, cloud, domain) {
250
439
  return this.withLock(id, async () => {
251
- const json = await this.ctx.storage.getSecret(this.getSecretKey(id, connectionId, cloud));
252
- if (json == null) return void 0;
253
- try {
254
- return convertStoredSessionToSession(JSON.parse(json), {
255
- connectionId,
256
- domain,
257
- scopes: []
258
- }, cloud);
259
- } catch {
260
- return;
261
- }
440
+ if (this._disposed) return void 0;
441
+ const session = await this.peekSecret(id, connectionId, cloud, domain);
442
+ return this._disposed ? void 0 : session ?? void 0;
262
443
  });
263
444
  }
445
+ async peekSecret(id, connectionId, cloud, domain) {
446
+ const json = await this.ctx.storage.getSecret(this.getSecretKey(id, connectionId, cloud));
447
+ if (json == null) return void 0;
448
+ try {
449
+ const stored = JSON.parse(json);
450
+ if (this.isRetiredSecret(stored, cloud)) return null;
451
+ return convertStoredSessionToSession(stored, {
452
+ connectionId,
453
+ domain,
454
+ scopes: []
455
+ }, cloud);
456
+ } catch {
457
+ return;
458
+ }
459
+ }
460
+ isRetiredSecret(session, cloud) {
461
+ if (!cloud && session.cloud !== false && session.expiresAt != null) return this.hasCloudLogout;
462
+ return (cloud || session.cloud === true) && !this.state.cloud.allows(session.cloudOrigin);
463
+ }
264
464
  getStoredSession(id, descriptor) {
265
465
  return this.withLock(id, async () => {
466
+ if (this._disposed) return void 0;
266
467
  const sessionId = this.resolveConnectionId(id, descriptor);
267
468
  let session = descriptor.cloud === true ? void 0 : await this.readSecret(id, sessionId, false);
469
+ if (this._disposed) return void 0;
268
470
  let cloudIfMissing = false;
269
- if (session != null) {
270
- if (session.expiresAt != null) {
271
- cloudIfMissing = true;
272
- try {
273
- await this.deleteSecrets(id, session.id);
274
- await this.writeSecret(id, session);
275
- } catch {}
276
- }
471
+ if (session != null && session.cloud !== false && session.expiresAt != null) {
472
+ cloudIfMissing = true;
473
+ try {
474
+ await this.deleteSecrets(id, session.id);
475
+ if (this.hasCloudLogout) return void 0;
476
+ await this.writeSecret(id, {
477
+ ...session,
478
+ cloud: true
479
+ });
480
+ } catch {}
277
481
  }
278
482
  if (session == null && descriptor.cloud !== false) {
279
483
  cloudIfMissing = true;
280
484
  session = await this.readSecret(id, sessionId, true);
281
485
  }
282
- return convertStoredSessionToSession(session, descriptor, cloudIfMissing);
486
+ return this._disposed || session != null && this.isRetiredSecret(session, cloudIfMissing) ? void 0 : convertStoredSessionToSession(session, descriptor, cloudIfMissing);
283
487
  });
284
488
  }
285
489
  /**
@@ -289,67 +493,75 @@ var ConfiguredIntegrationService = class {
289
493
  */
290
494
  deleteStoredSessions(id, descriptor, cloud, options) {
291
495
  return this.withLock(id, async () => {
496
+ if (this._disposed || options?.sync?.isCurrent() === false) return false;
292
497
  const connectionId = this.resolveConnectionId(id, descriptor);
498
+ if (options?.unobservedSince != null && this.state.cloud.observedSince(`${id}|connection:${connectionId}`, options.unobservedSince)) return false;
293
499
  if (options?.signOutMark != null && this.isSessionRetiredSince(id, {
294
500
  id: connectionId,
295
- domain: descriptor.domain
501
+ domain: descriptor.domain,
502
+ cloud
296
503
  }, options.signOutMark)) return false;
297
504
  if (options?.signOut) this.retirePendingStores(isSelfManagedHostIntegrationId(id) && descriptor.domain ? this.getHostScope(id, descriptor.domain) : id);
298
- this._onWillRemoveSessions.fire({
299
- integrationId: id,
300
- connectionId,
301
- cloud,
302
- domain: descriptor.domain
505
+ await this.deleteSecrets(id, connectionId, cloud, {
506
+ ...options,
507
+ onRemoving: () => this._onWillRemoveSessions.fire({
508
+ integrationId: id,
509
+ connectionId,
510
+ cloud,
511
+ domain: descriptor.domain
512
+ })
303
513
  });
304
- await this.deleteSecrets(id, connectionId, cloud, options);
305
514
  return true;
306
515
  });
307
516
  }
308
517
  /** Signs out of every stored session of the provider, or of one self-managed host when `domain` is given. */
309
- deleteAllStoredSessions(id, cloud, domain) {
518
+ deleteAllStoredSessions(id, cloud, domain, sync) {
519
+ const scope = isSelfManagedHostIntegrationId(id) && domain != null ? this.getHostScope(id, domain) : id;
310
520
  return this.withLock(id, async () => {
311
- this.retirePendingStores(isSelfManagedHostIntegrationId(id) && domain != null ? this.getHostScope(id, domain) : id);
312
- this._onWillRemoveSessions.fire({
313
- integrationId: id,
314
- cloud,
315
- domain
521
+ if (this._disposed || sync?.isCurrent() === false || sync && this.hasNewCloudConnection(id, domain, sync.mark)) return false;
522
+ await this.duringRemoval(scope, cloud, async () => {
523
+ this._onWillRemoveSessions.fire({
524
+ integrationId: id,
525
+ cloud,
526
+ domain
527
+ });
528
+ if (this._disposed) return;
529
+ await this.deleteAllSecrets(id, cloud, domain);
316
530
  });
317
- await this.deleteAllSecrets(id, cloud, domain);
531
+ return !this._disposed;
318
532
  });
319
533
  }
320
- /**
321
- * Reclaims all stored configuration + secrets for the given (typically retired) integration ids.
322
- * Used to clean up state left behind when an id is removed from the model — e.g. the local
323
- * self-managed `github-enterprise`/`gitlab-self-hosted` ids dropped when integrations went cloud-only.
324
- * Domains are read from the stored config (secrets are keyed by domain); ids with no stored config
325
- * are a no-op.
326
- */
327
534
  async purgeStoredConfiguration(ids) {
328
- const stored = this.ctx.storage.get("integrations:configured");
329
- if (stored == null) return;
330
- let changed = false;
331
- for (const id of ids) {
332
- if (!(id in stored)) continue;
333
- for (const descriptor of stored[id] ?? []) {
334
- const connectionId = descriptor.id || descriptor.domain || providersMetadata[id]?.domain || id;
335
- await this.ctx.storage.deleteSecret(this.getLocalSecretKey(id, connectionId));
336
- await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, connectionId));
337
- if (descriptor.domain) await this.ctx.storage.deleteWorkspace(`connected:${id}:${descriptor.domain}`);
338
- }
339
- changed = true;
340
- }
341
- if (!changed) return;
342
- const remaining = Object.fromEntries(Object.entries(stored).filter(([key]) => !ids.includes(key)));
343
- await this.ctx.storage.store("integrations:configured", remaining);
535
+ for (const id of ids) await this.withLock(id, async () => {
536
+ const descriptors = this.ctx.storage.get("integrations:configured")?.[id];
537
+ if (descriptors == null) return;
538
+ await this.duringRemoval(id, void 0, async () => {
539
+ for (const descriptor of descriptors) {
540
+ const key = descriptor.id || descriptor.domain || providersMetadata[id]?.domain || id;
541
+ await this.ctx.storage.deleteSecret(this.getLocalSecretKey(id, key));
542
+ await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, key));
543
+ if (descriptor.domain) await this.ctx.storage.deleteWorkspace(`connected:${id}:${descriptor.domain}`);
544
+ }
545
+ await this.storeConfigured(id);
546
+ });
547
+ });
344
548
  }
345
549
  async deleteSecrets(id, connectionId, cloud, options) {
346
- this.retireStoredWrites(`${id}|connection:${connectionId}`);
347
- if (cloud == null || cloud === false) await this.ctx.storage.deleteSecret(this.getLocalSecretKey(id, connectionId));
348
- if (cloud == null || cloud === true) await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, connectionId));
349
- if (options?.preserveConfigured) return;
350
- await this.removeConfigured(id, {
351
- connectionId,
352
- cloud
550
+ await this.duringRemoval(`${id}|connection:${connectionId}`, cloud, async () => {
551
+ if (options?.onRemoving != null) {
552
+ options.onRemoving();
553
+ if (this._disposed) return;
554
+ }
555
+ if (cloud == null || cloud === false) await this.ctx.storage.deleteSecret(this.getLocalSecretKey(id, connectionId));
556
+ if (cloud == null || cloud === true) {
557
+ await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, connectionId));
558
+ this.state.cloud.remove(`${id}|connection:${connectionId}`);
559
+ }
560
+ if (options?.preserveConfigured) return;
561
+ await this.removeConfigured(id, {
562
+ connectionId,
563
+ cloud
564
+ });
353
565
  });
354
566
  }
355
567
  async deleteAllSecrets(id, cloud, domain) {
@@ -362,8 +574,11 @@ var ConfiguredIntegrationService = class {
362
574
  if (domain != null) return;
363
575
  await this.deleteSecrets(id, providersMetadata[id]?.domain || id, cloud);
364
576
  }
365
- async writeSecret(id, session, resource) {
366
- await this.ctx.storage.storeSecret(this.getSecretKey(id, session.id, session.cloud ?? false), JSON.stringify(session));
577
+ async writeSecret(id, session, resource, cloudOrigin) {
578
+ await this.ctx.storage.storeSecret(this.getSecretKey(id, session.id, session.cloud ?? false), JSON.stringify(cloudOrigin == null ? session : {
579
+ ...session,
580
+ cloudOrigin
581
+ }));
367
582
  await this.addOrUpdateConfigured({
368
583
  id: session.id,
369
584
  integrationId: id,
@@ -382,9 +597,11 @@ var ConfiguredIntegrationService = class {
382
597
  let storedSession;
383
598
  try {
384
599
  const sessionJSON = await this.ctx.storage.getSecret(this.getSecretKey(id, sessionId, cloud));
600
+ if (this._disposed) return void 0;
385
601
  if (sessionJSON) {
386
602
  storedSession = JSON.parse(sessionJSON);
387
603
  if (storedSession != null) {
604
+ if (this.isRetiredSecret(storedSession, cloud)) return void 0;
388
605
  const configured = this.configured.get(id);
389
606
  const connectionId = storedSession.id ?? sessionId;
390
607
  const sessionCloud = storedSession.cloud ?? cloud;
@@ -403,6 +620,7 @@ var ConfiguredIntegrationService = class {
403
620
  }
404
621
  }
405
622
  } catch (_ex) {
623
+ if (this._disposed) return void 0;
406
624
  try {
407
625
  await this.deleteSecrets(id, sessionId, cloud);
408
626
  } catch {}
@@ -500,8 +718,19 @@ var ConfiguredIntegrationService = class {
500
718
  * Marks the given connection as the primary/default for the provider and clears the flag on its
501
719
  * siblings. Persists immediately instead of relying on a session re-store to carry the primary flag.
502
720
  */
503
- setPrimaryConnection(id, connectionId) {
504
- return this.withLock(id, () => this.setPrimaryConnectionCore(id, connectionId));
721
+ setPrimaryConnection(id, connectionId, list) {
722
+ return this.withLock(id, async () => {
723
+ if (this._disposed) return;
724
+ if (list != null && (!list.sync.isCurrent() || this.state.cloud.supersedingPrimary(id, list.domain, connectionId, list.sync.mark) != null)) return;
725
+ await this.setPrimaryConnectionCore(id, connectionId);
726
+ if (list != null || this._disposed) return;
727
+ const selected = this.getConfigured(id, { cloud: true }).find((c) => c.id === connectionId && c.primary);
728
+ if (selected != null) {
729
+ const mark = ++this.state.epoch;
730
+ this.state.cloud.observe(`${id}|connection:${connectionId}`, mark);
731
+ this.state.cloud.observePrimary(id, selected.domain, connectionId, mark);
732
+ }
733
+ });
505
734
  }
506
735
  async setPrimaryConnectionCore(id, connectionId) {
507
736
  const descriptors = this.configured.get(id);
@@ -523,9 +752,8 @@ var ConfiguredIntegrationService = class {
523
752
  };
524
753
  });
525
754
  if (!changed) return;
526
- this.configured.set(id, updated);
755
+ await this.storeConfigured(id, updated);
527
756
  this.fireChange(id);
528
- await this.storeConfigured();
529
757
  }
530
758
  /**
531
759
  * Removes a single connection (its secret + configured descriptor). If it was the primary and other
@@ -535,13 +763,12 @@ var ConfiguredIntegrationService = class {
535
763
  */
536
764
  deleteConnection(id, connectionId, cloud) {
537
765
  return this.withLock(id, async () => {
538
- this.retirePendingStores(`${id}|connection:${connectionId}`);
539
- this._onWillRemoveSessions.fire({
766
+ if (this._disposed) return;
767
+ await this.deleteSecrets(id, connectionId, cloud, { onRemoving: () => this._onWillRemoveSessions.fire({
540
768
  integrationId: id,
541
769
  connectionId,
542
770
  cloud
543
- });
544
- await this.deleteSecrets(id, connectionId, cloud);
771
+ }) });
545
772
  });
546
773
  }
547
774
  _addedIds = /* @__PURE__ */ new Set();
@@ -573,6 +800,14 @@ var ConfiguredIntegrationService = class {
573
800
  this._fireChangeDebounced();
574
801
  }
575
802
  };
803
+ function isLegacyCloudSecret(raw) {
804
+ try {
805
+ const session = JSON.parse(raw);
806
+ return session?.cloud === true || session?.cloud !== false && session?.expiresAt != null;
807
+ } catch {
808
+ return false;
809
+ }
810
+ }
576
811
  function convertStoredSessionToSession(storedSession, descriptor, cloudIfMissing) {
577
812
  if (storedSession == null) return void 0;
578
813
  return {