Skip to content

Latest commit

 

History

History
349 lines (245 loc) · 19.8 KB

runtime-and-token-refresh.md

File metadata and controls

349 lines (245 loc) · 19.8 KB

Runtime And Token Refresh

The Runtime And Token Refresh module is the browser-side coordination layer for renewing OpenFrame access credentials. It provides one refresh policy to the API clients, authentication flows, relay integrations, and native shells that need to recover from an expired access token.

Its central design goal is to distinguish a dead session from a temporarily unavailable authentication service. A rejected credential ends the session, while network failures, gateway failures, rate limits, WAF responses, and timeouts remain retryable. The module also prevents refresh-token rotation races between concurrent requests and browser tabs.

Source: token-refresh-manager.ts

Responsibilities

The module is responsible for:

  • Refreshing bearer-token and cookie-based sessions through /oauth/refresh.
  • Delegating refresh ownership to a native authentication plugin when the application shell provides one.
  • Serializing browser-tab refresh operations with the Web Locks API.
  • Joining concurrent refresh calls within the current JavaScript realm.
  • Sharing rotation and outage state between tabs with safe, token-free localStorage markers.
  • Retrying server-side failures without retrying transport failures that might have hidden a successful token rotation.
  • Spacing failed refresh cycles with progressive backoff.
  • Proactively refreshing credentials before they expire when expiry information is available.
  • Preserving newer credentials when an older request returns a stale 401.

It does not decide whether an individual API operation should be retried, nor should callers use its boolean helper to decide whether to sign a user out. Callers that need to distinguish a terminal session from a transient outage must use the three-state refreshTokens result.

Architecture Overview

The module sits between credential storage, runtime configuration, browser coordination primitives, and the callers that observed an authentication failure.

flowchart LR
    Callers["API clients and authenticated integrations"] --> Manager["Token Refresh Manager"]
    Manager --> Store["Token Store"]
    Manager --> Endpoint["Runtime Host and /oauth/refresh"]
    Manager --> Lock["Web Lock and localStorage"]
    Manager --> Native["Native Authentication Plugin"]
    Manager --> Result["refreshed, transient, or terminal"]
Loading

Integration Boundaries

Boundary Role Behavior
Token store Supplies access and refresh credentials, token epochs, and rotation updates Bearer mode reads and writes tokens; cookie mode keeps credentials in the browser cookie jar
Runtime configuration Supplies the shared host URL The refresh path is /oauth/refresh; when no host is configured, the path remains relative
Native shell May own the entire refresh operation The manager adopts tokens returned by refreshTokens and does not write them back to the shell
Browser coordination Coordinates tabs and preserves state across tab-local managers Web Locks serialize work; storage markers advertise rotations and backoff deadlines
Refresh endpoint Rotates the session credential The BFF resolves the tenant from the refresh credential; the manager does not append a tenant query parameter

Public API

RefreshOutcome

type RefreshOutcome = 'refreshed' | 'transient' | 'terminal'

The result describes what the refresh attempt says about the session, not whether the original application request succeeded.

  • refreshed: a newer usable credential is available, or another tab replaced the credential while this call was in flight.
  • transient: the session could not be verified now, but the failure does not prove that the session is dead.
  • terminal: the refresh credential was rejected with 401, or a bearer rotation succeeded without returning a replacement access token.

CredentialSnapshot

CredentialSnapshot records the token epoch and access token before a refresh request. It is used internally to recognize a credential replacement that happened while the request was in flight. Although it is a core component of the module, it is not an exported application API.

interface CredentialSnapshot {
  epoch: number
  accessToken: string | null
}

CycleBackoff

CycleBackoff is the token-free state shared by the current realm and, when storage is available, by other tabs.

interface CycleBackoff {
  until: number
  failures: number
}

until is the next permitted cycle deadline. failures counts consecutive transient cycles and selects the next delay.

RefreshOptions

interface RefreshOptions {
  ignoreBackoff?: boolean
}

ignoreBackoff is intended for the explicit retry action behind the session-verification failure screen. It starts a cycle immediately, but any resulting failure still arms the normal next backoff step.

refreshTokens

function refreshTokens(
  observedEpoch?: number,
  options?: RefreshOptions,
): Promise<RefreshOutcome>

This is the primary entry point. observedEpoch should be the token epoch captured immediately before the request that returned 401. If the epoch changed before refresh begins, the request is known to be stale and the function returns refreshed without rotating again.

Calls made concurrently in the same realm join the existing promise. Calls in other tabs coordinate through the Web Lock and rotation marker.

refreshAccessToken

function refreshAccessToken(observedEpoch?: number): Promise<boolean>

This compatibility helper maps only refreshed to true. It is suitable for integrations that only need to know whether a request may be retried, such as socket or embed adapters. It intentionally conflates transient and terminal; session termination decisions must use refreshTokens.

refreshIfStale

function refreshIfStale(): Promise<void>

This foreground or lifecycle-oriented helper refreshes only when the credential is considered stale. It does nothing when a native shell owns refreshing, when a bearer token is still outside its refresh leeway, or when cookie mode has no evidence of an old rotation.

getRefreshBackoffRemainingMs

function getRefreshBackoffRemainingMs(): number

Returns the remaining delay before another refresh cycle may begin. It returns zero when no backoff is pending. A session-verification UI can use this value to schedule its retry without creating a new request storm.

isTokenRefreshing And waitForRefresh

function isTokenRefreshing(): boolean
function waitForRefresh(): Promise<boolean>

isTokenRefreshing exposes whether a realm-local refresh is active. waitForRefresh waits for that refresh, returning true only when it ends in refreshed; it returns false if no refresh is in progress.

Refresh Modes

Bearer Mode

In bearer mode, the manager obtains the refresh token from the token store and sends it in the Refresh-Token header. A successful response may return access and refresh tokens in either response headers or JSON fields, supporting both casing conventions used by deployed authentication services.

The manager prefers response headers, then checks these JSON names:

  • access_token or accessToken
  • refresh_token or refreshToken

When a stored bearer refresh token was used but a successful response contains no replacement access token, the rotation is considered terminal. The old refresh token may already be spent, so retaining it would create a misleading authenticated state.

Cookie Mode

In cookie mode, the browser sends the refresh cookie through credentials: 'include'. No token material is stored in the module. A successful rotation advances the local token epoch and publishes a timestamp so other tabs can recognize the rotation.

Because cookie expiry cannot be inspected locally, proactive refresh uses the time since the last rotation rather than a decoded JWT expiry.

Native Shell Mode

When nativeAuthPlugin() exposes refreshTokens, the native shell owns refresh-token access and rotation. The web manager:

  1. Passes the currently held access token as rejectedAccessToken.
  2. Lets the shell perform one refresh attempt and store the resulting pair.
  3. Adopts the returned tokens with adoptNativeTokens rather than writing them back.
  4. Treats empty tokens as terminal and rejected plugin calls as transient.
  5. Applies the same cycle backoff policy to native failures.

This avoids spending a rotating refresh token twice and protects cold-start states where credentials are temporarily unreadable from the platform keychain.

Outcome Classification

The manager classifies responses according to what they prove about the session.

Event Outcome Reason
Refresh succeeds with a usable access token refreshed The caller can retry with the current credential
Another tab or caller replaced the credential during the request refreshed The original 401 is stale; another refresh must not invalidate the newer token
Refresh returns 401 and no newer credential exists terminal The authentication service rejected the credential
Fetch throws, including an abort caused by the local timeout transient The response may be unavailable or the service may recover
Response is 5xx, 408, or 429 Retry within the cycle, then transient The failure is server-side and resending is considered safe
Response is a WAF 403, a routing 400, or another non-401 client error transient The response does not prove that the user's credential is dead
Native refresh rejects transient The shell reports an operational failure, not a confirmed sign-out
Bearer rotation succeeds without a replacement access token terminal The stored bearer refresh token was used and may now be spent

A 401 normally clears stored tokens through clearStoredTokens. The exception is a stale 401: if the credential epoch or access token changed while the request was in flight, the manager preserves the newer credential and returns refreshed.

Refresh Cycle And Retry Policy

A cycle consists of an initial refresh attempt followed by limited retries for safe server-side failures. The cycle has two independent bounds:

  • A 35-second request timeout prevents one hung request from blocking all callers indefinitely.
  • A 30-second cycle budget prevents slow gateway failures from being followed by another long attempt.

Server-side failures use delays of 1 second and 2.5 seconds. Transport failures are not retried immediately because a lost response may have arrived after the server rotated the refresh credential. Resending the superseded credential could produce a 401 and incorrectly terminate the session.

flowchart TD
    Start["Refresh requested"] --> Attempt["POST /oauth/refresh"]
    Attempt --> Status{"Response classification"}
    Status -->|"Success"| Refreshed["Store or adopt rotation"]
    Status -->|"401"| CredentialChanged{"Credential changed while waiting?"}
    CredentialChanged -->|"Yes"| Refreshed
    CredentialChanged -->|"No"| Terminal["Clear credentials and return terminal"]
    Status -->|"5xx, 408, or 429"| Budget{"Retry delay fits cycle budget?"}
    Budget -->|"Yes"| Delay["Wait 1 s or 2.5 s"]
    Delay --> Attempt
    Budget -->|"No"| Transient["Arm backoff and return transient"]
    Status -->|"Transport, timeout, or other response"| Transient
Loading

Cross-Tab Serialization

Refresh tokens rotate, and the backend does not provide a compare-and-swap operation. Two tabs refreshing at the same time can therefore leave one tab with a spent token. The manager uses two coordination mechanisms:

  1. Web Lock: Browser tabs request the openframe-token-refresh lock. A lock holder checks for a rotation performed while the caller waited, checks the current backoff, and then executes the cycle.
  2. Rotation marker: The of_token_rotated_at localStorage value contains only a timestamp. Its storage event tells other tabs to advance their token epoch. A waiting tab can also inspect the marker directly if its storage event has not arrived yet.

The lock wait is bounded at the refresh timeout plus 10 seconds. If the holder appears stuck, the waiting tab proceeds without serialization. This preserves availability and limits the worst case to the previous refresh race rather than an indefinitely blocked authentication flow.

A storage removal is not treated as a rotation. This prevents a tab signing out from making another tab believe it has a newer credential to retry with.

Backoff And Failure Cycles

A transient cycle writes a backoff marker under of_token_refresh_backoff in the form <deadline>:<consecutive failures>. The marker is also retained in memory so private browsing or quota failures cannot collapse retries into immediate back-to-back cycles.

The configured cycle delays are:

Consecutive transient cycles Delay before the next cycle
1 5 seconds
2 15 seconds
3 and later 60 seconds

The first transient cycle is treated specially. A caller can wait out its deadline and run one more cycle. Only a second consecutive failure is answered as an established transient outage. This permits a temporary network change or auth-service restart to recover without immediately displaying a session-verification failure state.

A successful rotation or terminal session result clears the cycle backoff. A failure that occurs after the maximum deadline has elapsed starts a new outage sequence at the first delay rather than inheriting an old sign-in's capped failure count.

stateDiagram-v2
    [*] --> Ready
    Ready --> FirstFailure: transient cycle
    FirstFailure --> Ready: refreshed
    FirstFailure --> Terminal: terminal
    FirstFailure --> SecondAttempt: first deadline reached
    SecondAttempt --> Ready: refreshed
    SecondAttempt --> Outage: transient cycle
    Outage --> Outage: transient cycle, increasing delay
    Outage --> Ready: refreshed
    Ready --> Terminal: terminal
    Terminal --> [*]
Loading

Proactive Refresh

refreshIfStale reduces the chance that a page returns to the foreground and sends many requests with an almost-expired credential.

For bearer tokens, the manager decodes only the JWT payload locally and refreshes when the access token has less than two minutes remaining. Malformed, opaque, or unreadable tokens do not produce an expiry; the normal 401 path remains responsible for recovery.

For cookie mode, the manager cannot inspect the cookie's expiration. It refreshes after more than 13 minutes have elapsed since the last known rotation. If there is no rotation marker, it does not infer staleness.

Native shells bypass this logic because the shell owns refresh.

Request And Data Flow

sequenceDiagram
    participant Caller as "Authenticated caller"
    participant Manager as "Token Refresh Manager"
    participant Lock as "Web Lock"
    participant Auth as "Refresh endpoint"
    participant Store as "Token store"
    Caller->>Manager: "refreshTokens(observedEpoch)"
    Manager->>Manager: "Compare observed epoch with current epoch"
    alt "Epoch is stale"
        Manager-->>Caller: "refreshed"
    else "Refresh is needed"
        Manager->>Lock: "Acquire openframe-token-refresh"
        Lock->>Manager: "Run one cycle"
        Manager->>Auth: "POST /oauth/refresh with cookie or header"
        Auth-->>Manager: "Success, retryable failure, or terminal 401"
        alt "Success"
            Manager->>Store: "Set or adopt tokens"
            Manager-->>Caller: "refreshed"
        else "Terminal 401"
            Manager->>Store: "Clear stored tokens"
            Manager-->>Caller: "terminal"
        else "Transient failure"
            Manager->>Manager: "Arm shared backoff"
            Manager-->>Caller: "transient"
        end
    end
Loading

Security And Reliability Properties

  • No token material in coordination storage: localStorage contains timestamps and counters only.
  • No tenant identifier in the refresh URL: tenant resolution remains bound to the refresh credential, and the manager avoids placing a bare UUID in a URL.
  • Stale-request protection: token epochs prevent a late 401 from destroying a credential obtained by another request or tab.
  • Rotation-aware timeout behavior: the manager waits longer than the gateway's documented connect and read timeout so it does not abandon a response that may contain a valid rotation.
  • Safe retry boundary: only failures classified as server-side and safe to resend are retried inside a cycle.
  • Bounded coordination: both request execution and lock waiting have upper bounds.
  • Graceful storage degradation: if localStorage is unavailable, the realm-local marker still protects backoff behavior; only cross-tab sharing is lost.
  • Native ownership: native refresh tokens remain under shell control when a native plugin is present.

Operational Scenarios

Multiple Requests Receive 401

The first caller creates the realm-local refresh promise. Other callers join it. If a caller captured an older token epoch, it returns refreshed immediately rather than inheriting a failure from a rotation it did not need.

Two Tabs Wake Together

One tab obtains the Web Lock and rotates the credential. It publishes the rotation timestamp. The other tab either observes the storage event or adopts the marker after lock acquisition and returns refreshed without spending the refresh token again.

The Authentication Service Is Down

Server-side failures are retried only within the bounded cycle. The cycle then arms a shared 5-second backoff. The first failure is followed by one scheduled cycle; if that also fails, subsequent callers receive transient during the progressively longer outage backoff instead of generating a request storm.

The Refresh Request Hangs

The request is aborted after 35 seconds and classified as transient. The manager does not immediately resend the request because the server might have rotated the credential even though the browser did not receive the response.

A Refresh Returns 401 After Another Tab Rotated

The credential snapshot no longer matches the current token epoch or access token. The manager treats the response as stale, does not clear tokens, and returns refreshed so the original caller can retry.

The Native Shell Is in a Keychain Cold Start

If no bearer refresh token is available while the native shell is still hydrating credentials, the web path skips a credential-less refresh. This avoids clearing valid native credentials merely because they were not readable yet.

Maintenance Guidance

When changing this module:

  1. Preserve the distinction between terminal and transient; do not map every refresh failure to sign-out.
  2. Keep refresh-token rotation serialized across tabs and avoid introducing a second refresh implementation in an API client or adapter.
  3. Treat transport failures conservatively because the server may have rotated a credential before the response was lost.
  4. Update both the in-memory and storage backoff behavior when changing outage pacing.
  5. Keep coordination markers free of access tokens, refresh tokens, tenant identifiers, or other sensitive values.
  6. Test bearer mode, cookie mode, native mode, SSR or test realms without browser APIs, storage failures, stale epochs, lock timeouts, and concurrent tabs.
  7. Verify that response parsing continues to support the deployed header and JSON casing conventions.

Related Module Boundaries

The Runtime And Token Refresh module is part of the broader library utility layer. Its direct implementation dependencies are credential storage, force-logout behavior, native shell integration, platform detection, and runtime host configuration. API clients and authentication adapters should consume its public refresh functions rather than duplicating refresh policy.