• Sets authentication tokens and stores them

    Implements comprehensive token storage by:

    1. Calculating the exact expiry timestamp for future validation
    2. Storing tokens in memory for fastest access
    3. Persisting tokens in encrypted storage for restarts
    4. Synchronizing token state with the Spotify API module
    5. Scheduling automatic token refresh before expiry

    This function serves as the single source of truth for setting tokens across the entire application, ensuring consistent state in all token storage locations.

    Parameters

    • tokens: AuthTokens

      Complete set of authentication tokens to store

    Returns void

    // After receiving tokens from OAuth flow
    setTokens({
    accessToken: "new-spotify-access-token",
    refreshToken: "new-spotify-refresh-token",
    expiresIn: 3600
    });
    export function setTokens(tokens: AuthTokens): void {
    try {
    const { accessToken, refreshToken, expiresIn } = tokens;

    // Calculate expiry timestamp (current time + expires_in duration in seconds)
    const expiryTimestamp = Date.now() + expiresIn * 1000;

    // Store in memory
    setAccessTokenState(accessToken);
    setRefreshTokenState(refreshToken);
    setTokenExpiryState(expiryTimestamp);

    // Store in encrypted persistent storage
    saveEncryptedTokens({
    accessToken,
    refreshToken,
    expiresAt: expiryTimestamp,
    });

    // Set tokens in spotify API module for compatibility
    spotifyApi.setTokens(accessToken, refreshToken, expiresIn);

    // Schedule token refresh if function is set
    if (scheduleTokenRefreshFn) {
    scheduleTokenRefreshFn(expiresIn);
    }

    saveLog("Authentication tokens stored successfully", "DEBUG");
    } catch (error) {
    saveLog(`Failed to store authentication tokens: ${error}`, "ERROR");
    }
    }