All files / src/lib/db auth.ts

94.17% Statements 210/223
87.14% Branches 122/140
100% Functions 35/35
94.17% Lines 210/223

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706                                  206x     206x                               206x       3629x 3629x                                   3x 3x 3x 3x 3x 3x 3x   3x           3x 3x       206x                                           1180x 1180x 1076x   104x 1180x 3x   101x                         1890x 1890x 1469x   421x 1890x 115x   306x               277x                     88x 83x   5x 4x   1x               1314x 1314x 51x 51x 51x       1263x 1263x   1263x 923x           340x 50x     290x               1263x 290x       973x 973x 891x   82x                             11x 11x 11x 11x 1x   10x 7x     3x                                 2x 2x 2x 2x 1x     1x     1x                                     793x 793x 793x 793x 157x   636x     636x 636x                                     2000x 1081x   919x 919x 919x       919x 919x 50x 50x 50x       869x 869x   869x 264x     605x 53x     552x   869x 552x       317x 317x 212x   105x         5571x                   864x 309x   555x 555x 555x         5559x         4274x                                         1076x 1076x 1076x 1076x 1076x                 1076x         1076x       1076x   1076x                                 1076x 1076x 1076x 1076x       269x 269x 269x       269x 269x 269x 269x   269x 269x 269x 269x   269x     269x 269x 269x             123x 123x       206x                                         2531x 440x   2531x         4325x         440x 1x 1x 1x       439x 439x 439x                     439x 71x     368x 256x     112x 112x 108x   4x                 436x                                         346x 210x   136x 136x 136x   38x 38x           136x 136x                             206x         4x 4x   4x 4x 2x 2x   2x           2x               2x 1x   2x                 865x 865x 1x 1x 1x       864x 864x   864x   864x   221x 221x 217x   4x     643x 643x   643x 551x     92x 865x 865x 865x 865x   865x 88x               4x                         4x       4x 4x 4x   4x      
/**
 * Authentication credential storage (single-row table pattern).
 */
 
import { createHash } from "node:crypto";
import { DEFAULT_SENTRY_URL, getConfiguredSentryUrl } from "../constants.js";
import { getEnv } from "../env.js";
import { getEnvTokenHost } from "../env-token-host.js";
import { logger } from "../logger.js";
import { normalizeOrigin } from "../sentry-urls.js";
import { withDbSpan } from "../telemetry.js";
import { getDatabase } from "./index.js";
import { clearAllIssueOrgCache } from "./issue-org-cache.js";
import { clearTrustedHostState } from "./regions.js";
import { runUpsert } from "./utils.js";
 
/** Refresh when less than 10% of token lifetime remains */
export const REFRESH_THRESHOLD = 0.1;
 
/** Default token lifetime (1 hour) for tokens without issuedAt */
export const DEFAULT_TOKEN_LIFETIME_MS = 3600 * 1000;
 
type AuthRow = {
  token: string | null;
  refresh_token: string | null;
  expires_at: number | null;
  issued_at: number | null;
  updated_at: number;
  /**
   * Origin URL the token was issued against (e.g., `https://sentry.io` or
   * `https://sentry.example.com`). NULL for rows written before schema v16;
   * lazily migrated by `migrateNullHostIfPresent` on first access.
   */
  host: string | null;
};
 
const log = logger.withTag("auth");
 
/** Read the single auth row. Returns `undefined` when no row exists. */
function getAuthRow(): AuthRow | undefined {
  const db = getDatabase();
  return db.query("SELECT * FROM auth WHERE id = 1").get() as
    | AuthRow
    | undefined;
}
 
/**
 * Lazy migration for rows created before schema v16 (NULL `host`).
 *
 * Uses the BOOT-TIME env snapshot (`getEnvTokenHost`), captured before the
 * `.sentryclirc` shim could mutate env. Reading the current env directly
 * would either default self-hosted users to SaaS (when the shim hasn't run
 * yet) or migrate to a poisoned rc URL (when it has).
 *
 * Users whose shell env was wrong at upgrade time can recover with
 * `sentry auth logout && sentry auth login`. Returns the migrated host
 * (never NULL on return).
 */
function migrateNullHost(row: AuthRow): string {
  const bootHost = getEnvTokenHost();
  const migratedHost = normalizeOrigin(bootHost);
  const host = migratedHost ?? DEFAULT_SENTRY_URL;
  try {
    withDbSpan("migrateAuthHost", () => {
      const db = getDatabase();
      db.query("UPDATE auth SET host = ? WHERE id = 1").run(host);
    });
    log.info(`Migrated stored credentials to host-scoped model: ${host}`);
  } catch {
    // Non-fatal: if the migration write fails, callers still get a
    // well-formed host from this function. The migration will retry
    // on the next access.
  }
  row.host = host;
  return host;
}
 
/** Prefix for environment variable auth sources in {@link AuthSource} */
export const ENV_SOURCE_PREFIX = "env:";
 
/** Where the auth token originated */
export type AuthSource = "env:SENTRY_AUTH_TOKEN" | "env:SENTRY_TOKEN" | "oauth";
 
export type AuthConfig = {
  token?: string;
  refreshToken?: string;
  expiresAt?: number;
  issuedAt?: number;
  source: AuthSource;
};
 
/**
 * Read the raw token string from environment variables, ignoring all filters.
 *
 * Unlike {@link getEnvToken}, this always returns the env token if set, even
 * when stored OAuth credentials would normally take priority. Used by the HTTP
 * layer to check "was an env token provided?" independent of whether it's being
 * used, and by the per-endpoint permission cache.
 */
export function getRawEnvToken(): string | undefined {
  const authToken = getEnv().SENTRY_AUTH_TOKEN?.trim();
  if (authToken) {
    return authToken;
  }
  const sentryToken = getEnv().SENTRY_TOKEN?.trim();
  if (sentryToken) {
    return sentryToken;
  }
  return;
}
 
/**
 * Read token from environment variables.
 * `SENTRY_AUTH_TOKEN` takes priority over `SENTRY_TOKEN` (matches legacy sentry-cli).
 * Empty or whitespace-only values are treated as unset.
 *
 * This function is intentionally pure (no DB access). The "prefer stored OAuth
 * over env token" logic lives in {@link getAuthToken} and {@link getAuthConfig}
 * which check the DB first when `SENTRY_FORCE_ENV_TOKEN` is not set.
 */
function getEnvToken(): { token: string; source: AuthSource } | undefined {
  const authToken = getEnv().SENTRY_AUTH_TOKEN?.trim();
  if (authToken) {
    return { token: authToken, source: "env:SENTRY_AUTH_TOKEN" };
  }
  const sentryToken = getEnv().SENTRY_TOKEN?.trim();
  if (sentryToken) {
    return { token: sentryToken, source: "env:SENTRY_TOKEN" };
  }
  return;
}
 
/**
 * Check if authentication is coming from an environment variable.
 * Use this to skip refresh/OAuth logic that doesn't apply to env tokens.
 */
export function isEnvTokenActive(): boolean {
  return getEnvToken() !== undefined;
}
 
/**
 * Get the name of the env var providing a token, for error messages.
 * Returns the specific variable name (e.g. "SENTRY_AUTH_TOKEN" or "SENTRY_TOKEN")
 * by checking which env var {@link getRawEnvToken} would read.
 * Falls back to "SENTRY_AUTH_TOKEN" if no env var is set.
 */
export function getActiveEnvVarName(): string {
  // Match getRawEnvToken() priority: SENTRY_AUTH_TOKEN first, then SENTRY_TOKEN
  if (getEnv().SENTRY_AUTH_TOKEN?.trim()) {
    return "SENTRY_AUTH_TOKEN";
  }
  if (getEnv().SENTRY_TOKEN?.trim()) {
    return "SENTRY_TOKEN";
  }
  return "SENTRY_AUTH_TOKEN";
}
 
export function getAuthConfig(): AuthConfig | undefined {
  // When SENTRY_FORCE_ENV_TOKEN is set, check env first (old behavior).
  // Otherwise, check the DB first — stored OAuth takes priority over env tokens.
  // This is the core fix for #646: wizard-generated build tokens no longer
  // silently override the user's interactive login.
  const forceEnv = getEnv().SENTRY_FORCE_ENV_TOKEN?.trim();
  if (forceEnv) {
    const envToken = getEnvToken();
    Eif (envToken) {
      return { token: envToken.token, source: envToken.source };
    }
  }
 
  const dbConfig = withDbSpan("getAuthConfig", () => {
    const row = getAuthRow();
 
    if (!row?.token) {
      return;
    }
 
    // Skip expired tokens without a refresh token — they're unusable.
    // Expired tokens WITH a refresh token are kept: auth refresh and
    // refreshToken() need them to perform the OAuth refresh flow.
    if (row.expires_at && Date.now() > row.expires_at && !row.refresh_token) {
      return;
    }
 
    return {
      token: row.token ?? undefined,
      refreshToken: row.refresh_token ?? undefined,
      expiresAt: row.expires_at ?? undefined,
      issuedAt: row.issued_at ?? undefined,
      source: "oauth" as const,
    };
  });
  if (dbConfig) {
    return dbConfig;
  }
 
  // No stored OAuth — fall back to env token
  const envToken = getEnvToken();
  if (envToken) {
    return { token: envToken.token, source: envToken.source };
  }
  return;
}
 
/**
 * Read the host the stored OAuth token is scoped to.
 *
 * Lazy-migrates NULL hosts (rows from before schema v16) to the currently-
 * configured host on first access. Returns `undefined` when no stored token
 * exists — callers should fall through to the env-token host snapshot.
 *
 * This function is intentionally tolerant of "no DB" errors (tests that
 * bypass DB init). On DB failure, returns `undefined` and trust-scoping
 * falls back to the caller's default behavior.
 */
export function getStoredAuthHost(): string | undefined {
  try {
    return withDbSpan("getStoredAuthHost", () => {
      const row = getAuthRow();
      if (!row?.token) {
        return;
      }
      if (row.host) {
        return row.host;
      }
      // Lazy migration for pre-v16 rows
      return migrateNullHost(row);
    });
  } catch {
    return;
  }
}
 
/**
 * Check whether a usable stored token exists in the auth row.
 *
 * Mirrors the "usable" criteria in `getAuthConfig`: a token is usable if it
 * has a bearer value AND (no expiry, OR not expired, OR expired-with-refresh).
 *
 * Used by {@link getActiveTokenHost} to decide whether to prefer stored
 * OAuth's host over the env-token snapshot.
 */
export function hasUsableStoredToken(): boolean {
  try {
    return withDbSpan("hasUsableStoredToken", () => {
      const row = getAuthRow();
      if (!row?.token) {
        return false;
      }
      // Match getAuthConfig's filter: expired-no-refresh rows are unusable
      Iif (row.expires_at && Date.now() > row.expires_at && !row.refresh_token) {
        return false;
      }
      return true;
    });
  } catch {
    return false;
  }
}
 
/**
 * Atomically check usability AND retrieve the stored host, in a single
 * DB read. Used by `getActiveTokenHost` so that a concurrent
 * `clearAuth()` (library mode) can't interleave between a
 * `hasUsableStoredToken()` check and a `getStoredAuthHost()` read,
 * producing an inconsistent "usable but undefined host" fallback.
 *
 * Returns `undefined` when no usable stored token exists. When present,
 * returns the normalized host string (migrating pre-v16 NULL rows on
 * first access, same as {@link getStoredAuthHost}).
 */
export function getUsableStoredTokenHost(): string | undefined {
  try {
    return withDbSpan("getUsableStoredTokenHost", () => {
      const row = getAuthRow();
      if (!row?.token) {
        return;
      }
      Iif (row.expires_at && Date.now() > row.expires_at && !row.refresh_token) {
        return;
      }
      Eif (row.host) {
        return row.host;
      }
      return migrateNullHost(row);
    });
  } catch {
    return;
  }
}
 
/** Memoized token. Wrapper distinguishes "not cached" from "cached as undefined". */
let cachedAuthToken: { value: string | undefined } | undefined;
 
/**
 * Get the active auth token.
 *
 * Default: checks the DB first (stored OAuth wins), then falls back to env vars.
 * With `SENTRY_FORCE_ENV_TOKEN=1`: checks env vars first (old behavior).
 */
export function getAuthToken(): string | undefined {
  if (cachedAuthToken !== undefined) {
    return cachedAuthToken.value;
  }
  const value = computeAuthToken();
  cachedAuthToken = { value };
  return value;
}
 
function computeAuthToken(): string | undefined {
  const forceEnv = getEnv().SENTRY_FORCE_ENV_TOKEN?.trim();
  if (forceEnv) {
    const envToken = getEnvToken();
    Eif (envToken) {
      return envToken.token;
    }
  }
 
  const dbToken = withDbSpan("getAuthToken", () => {
    const row = getAuthRow();
 
    if (!row?.token) {
      return;
    }
 
    if (row.expires_at && Date.now() > row.expires_at) {
      return;
    }
 
    return row.token;
  });
  if (dbToken) {
    return dbToken;
  }
 
  // No stored OAuth — fall back to env token
  const envToken = getEnvToken();
  if (envToken) {
    return envToken.token;
  }
  return;
}
 
/** Reset the memoized auth token. Tests only — call between auth-state mutations. */
export function resetAuthTokenCache(): void {
  cachedAuthToken = undefined;
}
 
/** Memoized result for {@link hasStoredAuthCredentials}. Same wrapper contract as {@link cachedAuthToken}. */
let cachedHasStoredCreds: { value: boolean } | undefined;
 
/** Memoized full auth row for {@link refreshToken}. Same wrapper contract as {@link cachedAuthToken}. */
let cachedAuthRow: { value: AuthRow | undefined } | undefined;
 
function getCachedAuthRow(): AuthRow | undefined {
  if (cachedAuthRow !== undefined) {
    return cachedAuthRow.value;
  }
  const row = getAuthRow();
  cachedAuthRow = { value: row };
  return row;
}
 
/** Reset the memoized auth row. Tests only — call between auth-state mutations. */
export function resetAuthRowCache(): void {
  cachedAuthRow = undefined;
}
 
/** Reset the memoized stored-credentials flag. Tests only — call between auth-state mutations. */
export function resetHasStoredCredsCache(): void {
  cachedHasStoredCreds = undefined;
}
 
/**
 * Options for persisting a token.
 *
 * @property host - Origin URL the token was issued against. When omitted on
 *   an update (e.g., access-token refresh), the existing row's host is
 *   preserved. When omitted on a fresh write, defaults to the
 *   currently-configured host (`SENTRY_HOST`/`SENTRY_URL`) or `DEFAULT_SENTRY_URL`.
 */
export type SetAuthTokenOptions = {
  host?: string;
};
 
export function setAuthToken(
  token: string,
  expiresIn?: number,
  newRefreshToken?: string,
  options?: SetAuthTokenOptions
): void {
  withDbSpan("setAuthToken", () => {
    const db = getDatabase();
    const now = Date.now();
    const expiresAt = expiresIn ? now + expiresIn * 1000 : null;
    const issuedAt = expiresIn ? now : null;
 
    // Host resolution precedence:
    //   1. Explicit `options.host` (login command, tests)
    //   2. Existing row's `host` (refresh flow preserves the original scope)
    //   3. Currently-configured host (getConfiguredSentryUrl)
    //   4. SaaS default
    // Always normalized to scheme+host[+port] via normalizeOrigin.
    const existingHost = (
      db.query("SELECT host FROM auth WHERE id = 1").get() as
        | { host: string | null }
        | undefined
    )?.host;
    const rawHost =
      options?.host ??
      existingHost ??
      getConfiguredSentryUrl() ??
      DEFAULT_SENTRY_URL;
    const host = normalizeOrigin(rawHost) ?? DEFAULT_SENTRY_URL;
 
    runUpsert(
      db,
      "auth",
      {
        id: 1,
        token,
        refresh_token: newRefreshToken ?? null,
        expires_at: expiresAt,
        issued_at: issuedAt,
        updated_at: now,
        host,
      },
      ["id"]
    );
  });
  // Auth row changed — drop memoized fingerprint, token, row, and
  // stored-credentials flag so the next read reflects the new row.
  resetIdentityFingerprintCache();
  resetAuthTokenCache();
  resetAuthRowCache();
  resetHasStoredCredsCache();
}
 
export async function clearAuth(): Promise<void> {
  withDbSpan("clearAuth", () => {
    const db = getDatabase();
    db.query("DELETE FROM auth WHERE id = 1").run();
    // Also clear user info, org region cache, pagination cursors, and the
    // issue-id → org cache (scoped to the current user's permissions) when
    // logging out.
    db.query("DELETE FROM user_info WHERE id = 1").run();
    db.query("DELETE FROM org_regions").run();
    db.query("DELETE FROM pagination_cursors").run();
    clearAllIssueOrgCache();
  });
  resetIdentityFingerprintCache();
  resetAuthTokenCache();
  resetAuthRowCache();
  resetHasStoredCredsCache();
  // Evict in-process trust extensions tied to the now-cleared identity.
  clearTrustedHostState();
 
  // Dynamic import avoids the auth→response-cache→auth cycle.
  try {
    const { clearResponseCache } = await import("../response-cache.js");
    await clearResponseCache();
  } catch {
    // Non-fatal: cache directory may not exist yet
  }
}
 
export function isAuthenticated(): boolean {
  const token = getAuthToken();
  return !!token;
}
 
/** Fingerprint returned when no token is present (logged out, no env var). */
export const ANON_IDENTITY = "<anon>";
 
/** Memoized fingerprint. Identity doesn't change within a single CLI run. */
let cachedFingerprint: string | undefined;
 
/**
 * Opaque fingerprint of the active bearer identity, used to namespace
 * response-cache keys so entries never leak across accounts. Mirrors
 * `getAuthConfig` precedence: forced env token > stored OAuth
 * (refresh_token preferred for stability across access-token rotation,
 * falling through expired access-only rows) > env token > anonymous.
 *
 * Memoized. Reset on every mutation point (`setAuthToken`,
 * `clearAuth`), so both the common case (OAuth access-token refresh
 * with a stable refresh_token — fingerprint unchanged in practice)
 * and the uncommon case (server-rotated refresh_token — fingerprint
 * changes, cache naturally re-populates under the new identity) work
 * correctly. Tests that mutate auth state between cases call
 * {@link resetIdentityFingerprintCache}.
 */
export function getIdentityFingerprint(): string {
  if (cachedFingerprint === undefined) {
    cachedFingerprint = computeIdentityFingerprint();
  }
  return cachedFingerprint;
}
 
/** Reset the memoized fingerprint. Tests only — call between auth-state mutations. */
export function resetIdentityFingerprintCache(): void {
  cachedFingerprint = undefined;
}
 
function computeIdentityFingerprint(): string {
  // Forced env-token: matches what `refreshToken()` will actually send.
  if (getEnv().SENTRY_FORCE_ENV_TOKEN?.trim()) {
    const envToken = getRawEnvToken();
    Eif (envToken) {
      return hashIdentity("env", envToken);
    }
  }
 
  const row = withDbSpan("getIdentityFingerprint", () => {
    const db = getDatabase();
    return db
      .query("SELECT token, refresh_token, expires_at FROM auth WHERE id = 1")
      .get() as
      | {
          token: string | null;
          refresh_token: string | null;
          expires_at: number | null;
        }
      | undefined;
  });
  // Prefer refresh_token: stable across access-token rotation.
  if (row?.refresh_token) {
    return hashIdentity("oauth", row.refresh_token);
  }
  // Access-only row: skip if expired (mirrors getAuthConfig).
  if (row?.token && !(row.expires_at && Date.now() > row.expires_at)) {
    return hashIdentity("oauth-access", row.token);
  }
 
  const envToken = getRawEnvToken();
  if (envToken) {
    return hashIdentity("env", envToken);
  }
  return ANON_IDENTITY;
}
 
/**
 * 16-char MD5 hex of `kind|secret`. Not used for auth — just a cheap
 * cache namespace. Collisions are benign (identities would share a
 * cache slot, same as the anonymous case).
 */
function hashIdentity(kind: string, secret: string): string {
  return createHash("md5")
    .update(`${kind}|${secret}`)
    .digest("hex")
    .slice(0, 16);
}
 
/**
 * Check if usable OAuth credentials are stored in the database.
 *
 * Returns true when the `auth` table has either:
 * - A non-expired token, or
 * - An expired token with a refresh token (will be refreshed on next use)
 *
 * Memoized within the process. Reset on {@link setAuthToken} and
 * {@link clearAuth} mutations. Tests call {@link resetHasStoredCredsCache}
 * between cases.
 *
 * Used by the login command to decide whether to prompt for re-authentication
 * when an env token is present.
 */
export function hasStoredAuthCredentials(): boolean {
  if (cachedHasStoredCreds !== undefined) {
    return cachedHasStoredCreds.value;
  }
  const row = getAuthRow();
  let result = false;
  if (row?.token) {
    // Non-expired token
    if (!row.expires_at || Date.now() <= row.expires_at) {
      result = true;
    } else E{
      // Expired but has refresh token — will be refreshed on next use
      result = !!row.refresh_token;
    }
  }
  cachedHasStoredCreds = { value: result };
  return result;
}
 
export type RefreshTokenOptions = {
  /** Bypass threshold check and always refresh */
  force?: boolean;
};
 
export type RefreshTokenResult = {
  token: string;
  refreshed: boolean;
  expiresAt?: number;
  expiresIn?: number;
};
 
let refreshPromise: Promise<RefreshTokenResult> | null = null;
 
async function performTokenRefresh(
  storedRefreshToken: string
): Promise<RefreshTokenResult> {
  const { refreshAccessToken } = await import("../oauth.js");
  const { AuthError } = await import("../errors.js");
 
  try {
    const tokenResponse = await refreshAccessToken(storedRefreshToken);
    const now = Date.now();
    const expiresAt = now + tokenResponse.expires_in * 1000;
 
    await setAuthToken(
      tokenResponse.access_token,
      tokenResponse.expires_in,
      tokenResponse.refresh_token ?? storedRefreshToken
    );
 
    return {
      token: tokenResponse.access_token,
      refreshed: true,
      expiresAt,
      expiresIn: tokenResponse.expires_in,
    };
  } catch (error) {
    // Only clear auth on explicit rejection, not network errors
    if (error instanceof AuthError) {
      await clearAuth();
    }
    throw error;
  }
}
 
/** Get a valid token, refreshing if needed. Use force=true after 401 responses. */
export async function refreshToken(
  options: RefreshTokenOptions = {}
): Promise<RefreshTokenResult> {
  // With SENTRY_FORCE_ENV_TOKEN, env token takes priority (no refresh needed).
  const forceEnv = getEnv().SENTRY_FORCE_ENV_TOKEN?.trim();
  if (forceEnv) {
    const envToken = getEnvToken();
    Eif (envToken) {
      return { token: envToken.token, refreshed: false };
    }
  }
 
  const { force = false } = options;
  const { AuthError } = await import("../errors.js");
 
  const row = getCachedAuthRow();
 
  if (!row?.token) {
    // No stored token — try env token as fallback
    const envToken = getEnvToken();
    if (envToken) {
      return { token: envToken.token, refreshed: false };
    }
    throw new AuthError("not_authenticated");
  }
 
  const now = Date.now();
  const expiresAt = row.expires_at;
 
  if (!expiresAt) {
    return { token: row.token, refreshed: false };
  }
 
  const issuedAt = row.issued_at ?? expiresAt - DEFAULT_TOKEN_LIFETIME_MS;
  const totalLifetime = expiresAt - issuedAt;
  const remainingLifetime = expiresAt - now;
  const remainingRatio = remainingLifetime / totalLifetime;
  const expiresIn = Math.max(0, Math.floor(remainingLifetime / 1000));
 
  if (!force && remainingRatio > REFRESH_THRESHOLD && now < expiresAt) {
    return {
      token: row.token,
      refreshed: false,
      expiresAt,
      expiresIn,
    };
  }
 
  Iif (!row.refresh_token) {
    await clearAuth();
    // Fall back to env token if available (consistent with getAuthToken/getAuthConfig)
    const envToken = getEnvToken();
    if (envToken) {
      return { token: envToken.token, refreshed: false };
    }
    throw new AuthError(
      "expired",
      "Session expired and no refresh token available. Run 'sentry auth login'."
    );
  }
 
  Iif (refreshPromise) {
    return refreshPromise;
  }
 
  refreshPromise = performTokenRefresh(row.refresh_token);
  try {
    return await refreshPromise;
  } finally {
    refreshPromise = null;
  }
}