@knpkv/atlassian-common 1.5.0 → 1.7.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 (40) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +31 -0
  3. package/dist/cli-auth/AtlassianCliAuth.d.ts +110 -0
  4. package/dist/cli-auth/AtlassianCliAuth.d.ts.map +1 -0
  5. package/dist/cli-auth/AtlassianCliAuth.js +298 -0
  6. package/dist/cli-auth/AtlassianCliAuth.js.map +1 -0
  7. package/dist/cli-auth/authCommand.d.ts +34 -0
  8. package/dist/cli-auth/authCommand.d.ts.map +1 -0
  9. package/dist/cli-auth/authCommand.js +127 -0
  10. package/dist/cli-auth/authCommand.js.map +1 -0
  11. package/dist/cli-auth/index.d.ts +14 -0
  12. package/dist/cli-auth/index.d.ts.map +1 -0
  13. package/dist/cli-auth/index.js +14 -0
  14. package/dist/cli-auth/index.js.map +1 -0
  15. package/dist/cli-auth/internal/NodeLayers.d.ts +5 -0
  16. package/dist/cli-auth/internal/NodeLayers.d.ts.map +1 -0
  17. package/dist/cli-auth/internal/NodeLayers.js +17 -0
  18. package/dist/cli-auth/internal/NodeLayers.js.map +1 -0
  19. package/dist/cli-auth/internal/oauthServer.d.ts +54 -0
  20. package/dist/cli-auth/internal/oauthServer.d.ts.map +1 -0
  21. package/dist/cli-auth/internal/oauthServer.js +94 -0
  22. package/dist/cli-auth/internal/oauthServer.js.map +1 -0
  23. package/dist/cli-auth/openBrowser.d.ts +16 -0
  24. package/dist/cli-auth/openBrowser.d.ts.map +1 -0
  25. package/dist/cli-auth/openBrowser.js +30 -0
  26. package/dist/cli-auth/openBrowser.js.map +1 -0
  27. package/package.json +5 -1
  28. package/src/cli-auth/AtlassianCliAuth.ts +539 -0
  29. package/src/cli-auth/authCommand.ts +227 -0
  30. package/src/cli-auth/index.ts +20 -0
  31. package/src/cli-auth/internal/NodeLayers.ts +25 -0
  32. package/src/cli-auth/internal/oauthServer.ts +168 -0
  33. package/src/cli-auth/openBrowser.ts +47 -0
  34. package/test/ApiUpdateWorkflows.test.ts +78 -0
  35. package/test/cliAuth.authCommand.test.ts +153 -0
  36. package/test/cliAuth.guardrails.test.ts +76 -0
  37. package/test/cliAuth.login.test.ts +319 -0
  38. package/test/cliAuth.oauthServer.test.ts +276 -0
  39. package/test/cliAuth.openBrowser.test.ts +70 -0
  40. package/test/cliAuth.refresh.test.ts +304 -0
@@ -0,0 +1,539 @@
1
+ /**
2
+ * OAuth2 login, token refresh and profile management for an Atlassian CLI.
3
+ *
4
+ * **Mental model**
5
+ *
6
+ * - **One flow, many CLIs**: `jira` and `confluence` differ only in the storage
7
+ * namespace, scopes, the names in their messages and their "not logged in"
8
+ * error. {@link makeAtlassianCliAuth} takes those as options; each CLI keeps
9
+ * its own service tag and public interface and delegates to this.
10
+ * - **Refresh lock**: a `Ref<Option<Deferred>>` prevents concurrent refreshes —
11
+ * the first caller refreshes, the others await the same Deferred.
12
+ * - **Browser-based login**: starts a local callback server, opens the browser,
13
+ * and awaits the OAuth code with a 5-minute timeout. A browser that will not
14
+ * open is reported on stderr and the wait continues: the URL is printed first.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const layer = Layer.effect(
19
+ * JiraAuth,
20
+ * makeAtlassianCliAuth({ toolName: "jira-cli", commandName: "jira", productName: "Jira", scopes, authMissing })
21
+ * ).pipe(Layer.provide(NodeCliAuthLive))
22
+ * ```
23
+ *
24
+ * @module
25
+ */
26
+ import * as Clock from "effect/Clock"
27
+ import * as Console from "effect/Console"
28
+ import * as Crypto from "effect/Crypto"
29
+ import * as Deferred from "effect/Deferred"
30
+ import * as Effect from "effect/Effect"
31
+ import * as FileSystem from "effect/FileSystem"
32
+ import * as HttpClient from "effect/http/HttpClient"
33
+ import * as Option from "effect/Option"
34
+ import * as Path from "effect/Path"
35
+ import type * as PlatformError from "effect/PlatformError"
36
+ import { ChildProcessSpawner } from "effect/process"
37
+ import * as Redacted from "effect/Redacted"
38
+ import * as Ref from "effect/Ref"
39
+ import { buildAuthUrl, computeCodeChallenge, generateCodeVerifier } from "../auth/OAuthEndpoints.js"
40
+ import { OAuthError } from "../auth/OAuthErrors.js"
41
+ import {
42
+ buildOAuthTokenAt,
43
+ exchangeCodeForTokens,
44
+ getAccessibleResources,
45
+ getUserInfo,
46
+ refreshToken,
47
+ revokeToken
48
+ } from "../auth/OAuthOperations.js"
49
+ import { generateUUID } from "../auth/uuid.js"
50
+ import type { AuthProfile } from "../config/AuthProfiles.js"
51
+ import {
52
+ deleteActiveProfile,
53
+ deleteProfileBySelector,
54
+ loadActiveProfile,
55
+ loadActiveProfileToken,
56
+ loadProfiles,
57
+ saveProfileToken,
58
+ setActiveProfileBySelector
59
+ } from "../config/AuthProfiles.js"
60
+ import type { HomeDirectoryError } from "../config/ConfigPaths.js"
61
+ import { HomeDirectoryTag } from "../config/ConfigPaths.js"
62
+ import type { OAuthConfig, OAuthToken, OAuthUser } from "../config/OAuthSchemas.js"
63
+ import type { FileSystemError } from "../config/TokenStorage.js"
64
+ import { isTokenExpiredAt, loadOAuthConfig, saveOAuthConfig } from "../config/TokenStorage.js"
65
+ import { callbackUrl, HttpServerFactoryTag, startCallbackServer } from "./internal/oauthServer.js"
66
+ import { openBrowser } from "./openBrowser.js"
67
+
68
+ type StorageError = FileSystemError | HomeDirectoryError | PlatformError.PlatformError
69
+
70
+ /**
71
+ * What distinguishes one Atlassian CLI's auth from another's.
72
+ *
73
+ * @category Types
74
+ */
75
+ export interface AtlassianCliAuthOptions<MissingError> {
76
+ /** Storage namespace under `~/.config/atlassian/` (e.g. `"jira-cli"`). */
77
+ readonly toolName: string
78
+ /** Binary name used in hints such as "Run 'jira auth login'". */
79
+ readonly commandName: string
80
+ /** Product name used in "No Jira sites found for this account". */
81
+ readonly productName: string
82
+ /** OAuth scopes requested at login. */
83
+ readonly scopes: ReadonlyArray<string>
84
+ /** The CLI's own "not logged in" error, so callers keep catching their tag. */
85
+ readonly authMissing: () => MissingError
86
+ /**
87
+ * Consulted only when the tool has no stored OAuth config; a config it returns
88
+ * is saved under {@link toolName}, migrating it.
89
+ */
90
+ readonly legacyOAuthConfig?: Effect.Effect<
91
+ OAuthConfig | null,
92
+ FileSystemError | HomeDirectoryError,
93
+ FileSystem.FileSystem | Path.Path | HomeDirectoryTag
94
+ >
95
+ }
96
+
97
+ /**
98
+ * Options for the login method.
99
+ *
100
+ * @category Types
101
+ */
102
+ export interface LoginOptions {
103
+ /** Site URL to select (for accounts with multiple sites) */
104
+ readonly siteUrl?: string
105
+ }
106
+
107
+ /**
108
+ * Information about an accessible Atlassian site.
109
+ *
110
+ * @category Types
111
+ */
112
+ export interface AccessibleSite {
113
+ readonly id: string
114
+ readonly name: string
115
+ readonly url: string
116
+ }
117
+
118
+ /**
119
+ * Who an Atlassian CLI is: the part of {@link AtlassianCliAuthOptions} its `auth` commands also read.
120
+ * A CLI defines it once and passes the same value to both, so the setup text lists exactly the
121
+ * scopes `login` requests.
122
+ *
123
+ * @category Types
124
+ */
125
+ export type AtlassianCliDescriptor = Pick<AtlassianCliAuthOptions<never>, "commandName" | "productName" | "scopes">
126
+
127
+ /**
128
+ * The auth operations an Atlassian CLI exposes.
129
+ *
130
+ * @category Types
131
+ */
132
+ export interface AtlassianCliAuth<MissingError> {
133
+ /** Configure OAuth client credentials */
134
+ readonly configure: (config: OAuthConfig) => Effect.Effect<void, StorageError>
135
+ /** Check if OAuth is configured */
136
+ readonly isConfigured: () => Effect.Effect<boolean, StorageError>
137
+ /** Start OAuth login flow. Returns list of sites if multiple are available and none was chosen. */
138
+ readonly login: (
139
+ options?: LoginOptions
140
+ ) => Effect.Effect<ReadonlyArray<AccessibleSite> | void, OAuthError | StorageError>
141
+ /** Revoke (best effort) and remove stored authentication */
142
+ readonly logout: () => Effect.Effect<void, OAuthError | StorageError>
143
+ /** Get access token, refreshing if needed */
144
+ readonly getAccessToken: () => Effect.Effect<Redacted.Redacted<string>, MissingError | OAuthError | StorageError>
145
+ /** Get cloud ID from stored token */
146
+ readonly getCloudId: () => Effect.Effect<string, MissingError | StorageError>
147
+ /** Get site URL from stored token */
148
+ readonly getSiteUrl: () => Effect.Effect<string, MissingError | StorageError>
149
+ /** Get current user info from stored token */
150
+ readonly getCurrentUser: () => Effect.Effect<OAuthUser | null, StorageError>
151
+ /** Get active auth profile */
152
+ readonly getActiveProfile: () => Effect.Effect<AuthProfile | null, StorageError>
153
+ /** List stored auth profiles */
154
+ readonly listProfiles: () => Effect.Effect<ReadonlyArray<AuthProfile>, StorageError>
155
+ /** Switch active profile by ID, name, site URL, cloud ID, or account ID */
156
+ readonly switchProfile: (selector: string) => Effect.Effect<AuthProfile | null, StorageError>
157
+ /** Remove stored profile by ID, name, site URL, cloud ID, or account ID */
158
+ readonly removeProfile: (selector: string) => Effect.Effect<AuthProfile | null, StorageError>
159
+ /** Check if user is logged in */
160
+ readonly isLoggedIn: () => Effect.Effect<boolean, StorageError>
161
+ }
162
+
163
+ type RefreshDeferred = Deferred.Deferred<OAuthToken, OAuthError | StorageError>
164
+
165
+ // Atlassian rotates refresh tokens: the response carries a replacement and the
166
+ // one we sent is consumed server-side. Interrupting between the round-trip and
167
+ // the save therefore destroys the credential — the next refresh fails and
168
+ // `getAccessToken` reacts by deleting the token file, so the user is silently
169
+ // logged out and has to log in again.
170
+ //
171
+ // Interruption is routine here, not hypothetical: this runs during layer
172
+ // construction on every CLI invocation, and jcf's nvim statusline kills the
173
+ // process on `VimLeave`. So the grant and the persist are atomic.
174
+ //
175
+ // The region carries its own deadline rather than relying on a caller's.
176
+ // `Effect.timeout` is a race, and racing an uninterruptible loser means waiting
177
+ // for it — an outer bound would go inert and, worse, an uninterruptible region
178
+ // with no deadline of its own absorbs SIGINT/SIGTERM entirely
179
+ // (`NodeRuntime.runMain`'s signal handlers only interrupt the main fiber),
180
+ // leaving a process that ignores Ctrl-C. The deadline forked inside the region
181
+ // is itself interruptible, so it does bound this.
182
+ //
183
+ // Abandoning the round-trip cannot prove the grant did not land: Atlassian may
184
+ // consume the refresh token and rotate it after we have stopped listening, and
185
+ // no client-side deadline changes that. So the deadline is paired with the rule
186
+ // in `getAccessToken` — a refresh that fails without a verdict never deletes the
187
+ // stored token. The credential survives to be retried, and only a real
188
+ // rejection ends the session.
189
+ const REFRESH_TIMEOUT = "30 seconds"
190
+
191
+ /**
192
+ * Build an Atlassian CLI's auth operations.
193
+ *
194
+ * Requires an `HttpClient`, a `ChildProcessSpawner` (browser launch), `Crypto`
195
+ * (PKCE), the callback-server factory, and the file system and home directory the
196
+ * tokens are stored under. `NodeCliAuthLive` supplies the last three on Node.
197
+ *
198
+ * @category Constructors
199
+ */
200
+ export const makeAtlassianCliAuth = Effect.fn("AtlassianCliAuth.make")(<MissingError>(
201
+ options: AtlassianCliAuthOptions<MissingError>
202
+ ): Effect.Effect<
203
+ AtlassianCliAuth<MissingError>,
204
+ never,
205
+ | HttpClient.HttpClient
206
+ | ChildProcessSpawner.ChildProcessSpawner
207
+ | Crypto.Crypto
208
+ | HttpServerFactoryTag
209
+ | FileSystem.FileSystem
210
+ | Path.Path
211
+ | HomeDirectoryTag
212
+ > =>
213
+ Effect.gen(function*() {
214
+ const { authMissing, commandName, productName, scopes, toolName } = options
215
+ const httpClient = yield* HttpClient.HttpClient
216
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner
217
+ const cryptoService = yield* Crypto.Crypto
218
+ const serverFactory = yield* HttpServerFactoryTag
219
+
220
+ const withHttp = Effect.provideService(HttpClient.HttpClient, httpClient)
221
+ const withCrypto = Effect.provideService(Crypto.Crypto, cryptoService)
222
+ const fileSystem = yield* FileSystem.FileSystem
223
+ const path = yield* Path.Path
224
+ const homeDirectory = yield* HomeDirectoryTag
225
+ const withStorage = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
226
+ effect.pipe(
227
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
228
+ Effect.provideService(Path.Path, path),
229
+ Effect.provideService(HomeDirectoryTag, homeDirectory)
230
+ )
231
+
232
+ const loadToken = () => loadActiveProfileToken(toolName).pipe(withStorage)
233
+ const saveToken = (token: OAuthToken) => saveProfileToken(toolName, token).pipe(withStorage)
234
+ const deleteToken = () => deleteActiveProfile(toolName).pipe(withStorage)
235
+ const saveConfig = (config: OAuthConfig) => saveOAuthConfig(toolName, config).pipe(withStorage)
236
+ const legacyOAuthConfig = options.legacyOAuthConfig
237
+ const loadConfig = Effect.fn("AtlassianCliAuth.loadConfig")(() =>
238
+ Effect.gen(function*() {
239
+ const config = yield* loadOAuthConfig(toolName)
240
+ if (config !== null || legacyOAuthConfig === undefined) return config
241
+ const legacy = yield* legacyOAuthConfig
242
+ if (legacy !== null) {
243
+ yield* saveOAuthConfig(toolName, legacy)
244
+ }
245
+ return legacy
246
+ }).pipe(withStorage)
247
+ )
248
+
249
+ const refreshLock = yield* Ref.make<Option.Option<RefreshDeferred>>(Option.none())
250
+
251
+ // The URL is printed before this runs, so a browser that will not open is
252
+ // reported and the wait for the callback continues.
253
+ const openBrowserOrWarn = Effect.fn("AtlassianCliAuth.openBrowserOrWarn")((url: string): Effect.Effect<void> =>
254
+ openBrowser(url).pipe(
255
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
256
+ Effect.catchTags({
257
+ BrowserOpenError: (error) =>
258
+ Console.error(`Could not open a browser (${error.command} exited ${error.exitCode}); visit the URL above.`),
259
+ PlatformError: () => Console.error("Could not open a browser; visit the URL above.")
260
+ })
261
+ )
262
+ )
263
+
264
+ const getConfig = Effect.fn("AtlassianCliAuth.getConfig")((): Effect.Effect<
265
+ OAuthConfig,
266
+ OAuthError | StorageError
267
+ > =>
268
+ Effect.gen(function*() {
269
+ const config = yield* loadConfig()
270
+ if (config === null) {
271
+ return yield* new OAuthError({
272
+ step: "authorize",
273
+ cause: `OAuth not configured. Run '${commandName} auth configure' first.`
274
+ })
275
+ }
276
+ return config
277
+ })
278
+ )
279
+
280
+ const refreshAndPersist = Effect.fn("AtlassianCliAuth.refreshAndPersist")((
281
+ token: OAuthToken,
282
+ config: OAuthConfig
283
+ ): Effect.Effect<OAuthToken, OAuthError | StorageError> =>
284
+ Effect.uninterruptible(
285
+ Effect.gen(function*() {
286
+ const updated = yield* refreshToken(token, config).pipe(
287
+ withHttp,
288
+ Effect.timeout(REFRESH_TIMEOUT),
289
+ Effect.catchTag(
290
+ "TimeoutError",
291
+ () => Effect.fail(new OAuthError({ step: "refresh", cause: `no response within ${REFRESH_TIMEOUT}` }))
292
+ )
293
+ )
294
+ yield* saveToken(updated)
295
+ return updated
296
+ })
297
+ )
298
+ )
299
+
300
+ const isConfigured = Effect.fn("AtlassianCliAuth.isConfigured")(() =>
301
+ loadConfig().pipe(Effect.map((config) => config !== null))
302
+ )
303
+
304
+ const login = Effect.fn("AtlassianCliAuth.login")((
305
+ loginOptions?: LoginOptions
306
+ ): Effect.Effect<ReadonlyArray<AccessibleSite> | void, OAuthError | StorageError> =>
307
+ Effect.gen(function*() {
308
+ const config = yield* getConfig()
309
+ const state = yield* generateUUID().pipe(withCrypto)
310
+ const codeVerifier = yield* generateCodeVerifier().pipe(withCrypto)
311
+ const codeChallenge = yield* computeCodeChallenge(codeVerifier).pipe(withCrypto)
312
+
313
+ const { code, port } = yield* Effect.scoped(
314
+ Effect.gen(function*() {
315
+ const { codePromise, port } = yield* startCallbackServer(state).pipe(
316
+ Effect.provideService(HttpServerFactoryTag, serverFactory)
317
+ )
318
+ const authUrl = buildAuthUrl({
319
+ clientId: config.clientId,
320
+ state,
321
+ port,
322
+ redirectUri: callbackUrl(port),
323
+ scopes: [...scopes],
324
+ codeChallenge
325
+ })
326
+
327
+ yield* Console.log(`Opening browser for Atlassian login (callback on port ${port})...`)
328
+ yield* Console.log(`If browser doesn't open, visit: ${authUrl}`)
329
+ yield* openBrowserOrWarn(authUrl)
330
+ yield* Console.log("Waiting for authorization (press Ctrl+C to cancel)...")
331
+
332
+ const code = yield* codePromise.pipe(
333
+ Effect.timeout("5 minutes"),
334
+ Effect.catchTag(
335
+ "TimeoutError",
336
+ () => Effect.fail(new OAuthError({ step: "authorize", cause: "Authorization timed out" }))
337
+ )
338
+ )
339
+ return { code, port }
340
+ })
341
+ )
342
+
343
+ yield* Console.log("Exchanging code for tokens...")
344
+ const tokens = yield* exchangeCodeForTokens(code, config, {
345
+ port,
346
+ redirectUri: callbackUrl(port),
347
+ codeVerifier
348
+ }).pipe(withHttp)
349
+
350
+ yield* Console.log("Fetching accessible sites...")
351
+ const sites = yield* getAccessibleResources(tokens.access_token).pipe(withHttp)
352
+
353
+ const [first, ...others] = sites
354
+ if (first === undefined) {
355
+ return yield* new OAuthError({
356
+ step: "authorize",
357
+ cause: `No ${productName} sites found for this account`
358
+ })
359
+ }
360
+
361
+ let site = first
362
+ if (others.length > 0) {
363
+ const siteUrl = loginOptions?.siteUrl
364
+ if (siteUrl === undefined || siteUrl === "") {
365
+ yield* Console.log(`Multiple ${productName} sites found. Please select one:`)
366
+ for (const s of sites) {
367
+ yield* Console.log(` - ${s.name}: ${s.url}`)
368
+ }
369
+ yield* Console.log(`\nRun '${commandName} auth login --site <url>' to select a site`)
370
+ return sites.map((s) => ({ id: s.id, name: s.name, url: s.url }))
371
+ }
372
+ const matched = sites.find((s) => s.url === siteUrl)
373
+ if (matched === undefined) {
374
+ const available = sites.map((s) => ` - ${s.name}: ${s.url}`).join("\n")
375
+ return yield* new OAuthError({
376
+ step: "authorize",
377
+ cause: `Site '${siteUrl}' not found. Available sites:\n${available}`
378
+ })
379
+ }
380
+ site = matched
381
+ }
382
+
383
+ yield* Console.log("Fetching user info...")
384
+ const user = yield* getUserInfo(tokens.access_token).pipe(withHttp)
385
+
386
+ const nowMs = yield* Clock.currentTimeMillis
387
+ yield* saveToken(buildOAuthTokenAt(tokens, site, user, nowMs))
388
+ yield* Console.log(`Logged in as ${user.name} (${user.email})`)
389
+ return undefined
390
+ })
391
+ )
392
+
393
+ const logout = Effect.fn("AtlassianCliAuth.logout")((): Effect.Effect<void, OAuthError | StorageError> =>
394
+ Effect.gen(function*() {
395
+ const token = yield* loadToken()
396
+ if (token === null) {
397
+ yield* Console.log("Not logged in")
398
+ return
399
+ }
400
+
401
+ const config = yield* loadConfig()
402
+ if (config !== null) {
403
+ yield* revokeToken(token, config).pipe(
404
+ withHttp,
405
+ Effect.tap(() => Effect.log("Token revoked with Atlassian")),
406
+ Effect.catch((error) => Effect.log(`Warning: Failed to revoke token: ${error.message}`))
407
+ )
408
+ }
409
+
410
+ yield* deleteToken()
411
+ })
412
+ )
413
+
414
+ const getAccessToken = Effect.fn("AtlassianCliAuth.getAccessToken")((): Effect.Effect<
415
+ Redacted.Redacted<string>,
416
+ MissingError | OAuthError | StorageError
417
+ > =>
418
+ Effect.gen(function*() {
419
+ const token = yield* loadToken()
420
+ if (token === null) {
421
+ return yield* Effect.fail(authMissing())
422
+ }
423
+
424
+ const nowMs = yield* Clock.currentTimeMillis
425
+ if (!isTokenExpiredAt(token, nowMs)) {
426
+ return Redacted.make(token.access_token)
427
+ }
428
+
429
+ // Atomically check-then-set refresh lock to avoid TOCTOU race
430
+ const deferred = yield* Deferred.make<OAuthToken, OAuthError | StorageError>()
431
+ const existing = yield* Ref.modify(refreshLock, (current) =>
432
+ Option.isSome(current)
433
+ ? ([current.value, current] satisfies readonly [RefreshDeferred, Option.Option<RefreshDeferred>])
434
+ : ([deferred, Option.some(deferred)] satisfies readonly [RefreshDeferred, Option.Option<RefreshDeferred>]))
435
+
436
+ // Another fiber is already refreshing — just await its result
437
+ if (existing !== deferred) {
438
+ const refreshed = yield* Deferred.await(existing)
439
+ return Redacted.make(refreshed.access_token)
440
+ }
441
+
442
+ const refresh = Effect.gen(function*() {
443
+ const config = yield* getConfig()
444
+ // stderr, not stdout: this fires from inside layer construction, so it
445
+ // lands ahead of whatever the command prints. On `--json` that used to
446
+ // put a line of prose in front of the document, and the release
447
+ // automation parsing it failed *after* the remote writes had happened.
448
+ yield* Console.error("Token expired, refreshing...")
449
+ return yield* refreshAndPersist(token, config)
450
+ }).pipe(
451
+ Effect.catchTag("OAuthError", (error) => {
452
+ // Discard the stored credential only when Atlassian actually rejected
453
+ // it. A refresh can fail without saying anything about the token —
454
+ // transport error, timeout, interruption — and in those cases the
455
+ // grant may even have been consumed server-side, so the one thing we
456
+ // must not do is delete the replacement's only trail. Deleting on any
457
+ // `step === "refresh"` failure turned a flaky network into a silent
458
+ // logout, which is worse than retrying and is unrecoverable.
459
+ //
460
+ // Not every 4xx is a verdict either. `429` is the one this most needs
461
+ // to survive — several `jira`/`jcf` processes on an expired token hit
462
+ // the endpoint together, one wins the rotation and the rest are
463
+ // rate-limited — while `408`/`425` restate the timeout case and `407`
464
+ // and other middlebox replies never came from Atlassian at all.
465
+ //
466
+ // Status alone is still too coarse. `refreshToken` sends the client
467
+ // credentials in the body, so a wrong or rotated `clientSecret` comes
468
+ // back as `400 invalid_client`; deleting the token there destroys a
469
+ // working credential over a config problem, and the re-login it forces
470
+ // would fail the same way until `auth configure` is run. Only
471
+ // `invalid_grant` means the stored token itself is spent, and that is
472
+ // the only thing that ends the session — on a `403` too, since a bare
473
+ // 403 is just as likely to come from a proxy or WAF as from Atlassian
474
+ // revoking anything. An unparseable body leaves `errorCode` absent and
475
+ // the token in place.
476
+ const { errorCode, status } = error
477
+ const rejected = errorCode === "invalid_grant" && (status === 400 || status === 403)
478
+ if (error.step === "refresh" && rejected) {
479
+ return Effect.gen(function*() {
480
+ yield* deleteToken()
481
+ return yield* new OAuthError({
482
+ step: "refresh",
483
+ cause: `Refresh token expired. Please run '${commandName} auth login' to re-authenticate.`,
484
+ status,
485
+ errorCode
486
+ })
487
+ })
488
+ }
489
+ return Effect.fail(error)
490
+ })
491
+ )
492
+
493
+ // This fiber owns the refresh. Publish every exit to the waiters —
494
+ // success, failure, and interruption of this fiber alike — so none of
495
+ // them blocks on a result that would otherwise never arrive.
496
+ const result = yield* refresh.pipe(
497
+ Effect.onExit((exit) =>
498
+ Ref.set(refreshLock, Option.none()).pipe(Effect.andThen(Deferred.done(deferred, exit)))
499
+ )
500
+ )
501
+
502
+ return Redacted.make(result.access_token)
503
+ })
504
+ )
505
+
506
+ const storedTokenField = <A>(read: (token: OAuthToken) => A) => (): Effect.Effect<A, MissingError | StorageError> =>
507
+ loadToken().pipe(
508
+ Effect.flatMap((token) => token === null ? Effect.fail(authMissing()) : Effect.succeed(read(token)))
509
+ )
510
+
511
+ return {
512
+ configure: Effect.fn("AtlassianCliAuth.configure")(saveConfig),
513
+ isConfigured,
514
+ login,
515
+ logout,
516
+ getAccessToken,
517
+ getCloudId: Effect.fn("AtlassianCliAuth.getCloudId")(storedTokenField((token) => token.cloud_id)),
518
+ getSiteUrl: Effect.fn("AtlassianCliAuth.getSiteUrl")(storedTokenField((token) => token.site_url)),
519
+ getCurrentUser: Effect.fn("AtlassianCliAuth.getCurrentUser")(() =>
520
+ loadToken().pipe(Effect.map((token) => token?.user ?? null))
521
+ ),
522
+ getActiveProfile: Effect.fn("AtlassianCliAuth.getActiveProfile")(() =>
523
+ loadActiveProfile(toolName).pipe(withStorage)
524
+ ),
525
+ listProfiles: Effect.fn("AtlassianCliAuth.listProfiles")(() =>
526
+ loadProfiles(toolName).pipe(Effect.map((store) => store.profiles), withStorage)
527
+ ),
528
+ switchProfile: Effect.fn("AtlassianCliAuth.switchProfile")((selector) =>
529
+ setActiveProfileBySelector(toolName, selector).pipe(withStorage)
530
+ ),
531
+ removeProfile: Effect.fn("AtlassianCliAuth.removeProfile")((selector) =>
532
+ deleteProfileBySelector(toolName, selector).pipe(withStorage)
533
+ ),
534
+ isLoggedIn: Effect.fn("AtlassianCliAuth.isLoggedIn")(() =>
535
+ loadToken().pipe(Effect.map((token) => token !== null))
536
+ )
537
+ }
538
+ })
539
+ )