-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtoken-refresh.ts
More file actions
65 lines (56 loc) · 1.85 KB
/
token-refresh.ts
File metadata and controls
65 lines (56 loc) · 1.85 KB
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
/**
* Token Refresh
*
* Proactively refreshes OAuth tokens before they expire.
* This runs in the background on every CLI command to ensure
* users don't get unexpectedly logged out.
*/
import { readConfig, setAuthToken } from "./config.js";
import { refreshAccessToken } from "./oauth.js";
// Threshold: 5 days in milliseconds
// If token expires within this time, we'll refresh it
const REFRESH_THRESHOLD_MS = 5 * 24 * 60 * 60 * 1000;
/**
* Check if token needs refresh and refresh it in the background.
*
* This function is designed to be called fire-and-forget.
* It NEVER throws - all errors are silently ignored.
*
* @example
* // At CLI startup (fire-and-forget, no .catch() needed)
* maybeRefreshTokenInBackground();
*/
export async function maybeRefreshTokenInBackground(): Promise<void> {
try {
const config = await readConfig();
// Skip if no auth configured
if (!config.auth?.token) {
return;
}
// Skip if no refresh token (e.g., API token auth, not OAuth)
if (!config.auth.refreshToken) {
return;
}
// Skip if no expiration info (shouldn't happen, but be safe)
if (!config.auth.expiresAt) {
return;
}
// Check if token expires within 5 days
const timeUntilExpiry = config.auth.expiresAt - Date.now();
if (timeUntilExpiry > REFRESH_THRESHOLD_MS) {
return; // Token is still fresh, no action needed
}
// Token needs refresh - do it
const tokenResponse = await refreshAccessToken(config.auth.refreshToken);
// Save the new token
await setAuthToken(
tokenResponse.access_token,
tokenResponse.expires_in,
tokenResponse.refresh_token
);
} catch {
// Silently ignore all errors - this is fire-and-forget
// If refresh fails, the token will expire naturally and
// the user will need to re-login with `sentry auth login`
}
}