Heuristic:AI QL Tuui JWT Token Refresh
| Knowledge Sources | |
|---|---|
| Domains | LLM, Authentication, Security |
| Last Updated | 2026-10-24 20:38 GMT |
Overview
Automatically refresh JWT-based API tokens when the remaining lifetime drops below 1 second, by executing a configurable CLI command to retrieve a fresh token.
Description
Some LLM providers use short-lived JWT tokens for authentication. Hardcoding a token means it expires and requests start failing with 401 errors. The JWT token refresh heuristic checks the token's exp claim before each request. If the remaining lifetime is <= 1 second, it spawns the configured apiCli shell command to obtain a fresh token, updates the chatbot config in place, and proceeds with the new token. If the token has no exp claim, it is treated as never-expiring and never refreshed.
Usage
Apply this heuristic when integrating with LLM providers that use short-lived JWT tokens. The symptom is intermittent 401 errors after the token expires, requiring manual restart or token re-entry.
The Insight (Rule of Thumb)
- Action: Decode the JWT (
jwt-decode), checkexpagainst current time before each request. - Value: Refresh threshold:
remaining <= 1second. If noexpclaim, skip refresh (never-expiring token). - Trade-off: Adds a
jwtDecodecall per request; ifapiCliis slow, adds latency to the first request after expiry. - Fallback: If
apiKeyis empty butapiCliis set, always refresh. If decode fails (not a JWT), silently skip.
Reasoning
Short-lived tokens improve security (reduced exposure window) but require automatic refresh to maintain usability. The 1-second threshold is intentionally aggressive — it refreshes just before the token becomes invalid, minimizing wasted refresh calls while avoiding any window where an expired token is used. The apiCli command pattern allows integration with any token provider (cloud CLIs, custom scripts) without hardcoding provider-specific OAuth flows.
Code Evidence
JWT expiry check from `src/renderer/composables/chatCompletions.ts:86-118`:
async function checkTokenUpdate(chatbotConfig: ChatbotConfig): Promise<string | undefined> {
if (chatbotConfig.apiCli) {
try {
if (!chatbotConfig.apiKey) {
return await updateToken(chatbotConfig.apiCli)
}
const payload = jwtDecode(chatbotConfig.apiKey)
if (!payload.exp) {
return // Never expired
}
const currentTime = Math.floor(Date.now() / 1000)
const remaining = payload.exp - currentTime
if (remaining <= 1) {
return await updateToken(chatbotConfig.apiCli)
}
} catch {
// Crashed, not a JWT token or update failed
}
}
return
}
Token update via CLI from `src/renderer/composables/chatCompletions.ts:76-84`:
async function updateToken(cli: string): Promise<string | undefined> {
try {
return await getApiToken(cli)
} catch {
snackbarStore.showWarningMessage('chat.token-fail')
return
}
}