Skip to content

feat(telemetry): robust on-demand JWT refresh + non-destructive 401 handling (v0.16.0) - #73

Merged
minarc merged 1 commit into
mainfrom
feat/robust-jwt-refresh
Jun 17, 2026
Merged

minarc merged 1 commit into
mainfrom
feat/robust-jwt-refresh

Conversation

@minarc

@minarc minarc commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The license JWT has a 15-min TTL but was refreshed only at SessionStart (session_start.js → tryRefreshLicense). Mid-session and the retry daemon ran with an expired token, causing two failures (verified against ~6.5k stuck events, May–Jun):

  1. The drain skipped uploads entirely — getEndpointFromToken returns null for an expired token, so it returned before any attempt (even though the collector accepts unauthenticated uploads).
  2. On 401/403, transfer.js called setLicenseToken(""), destroying the license on a transient rejection.

P1 — robust, non-destructive refresh

  • lib/license-activation.js: ensureFreshLicense(deviceId, {force}) — best-effort, cross-process single-flight (mtime lock, 60s cooldown / 15s staleness) around refreshLicense (orchestration lifted from logger.tryRefreshLicense, which now delegates). Pure shouldRefresh(...) split out for unit testing. Lives in this leaf module to avoid a logger ↔ transfer require cycle.
  • lib/transfer.js: refresh once per drain batch (covers SessionStart, daemon, session-end — daemon needs no change); on 401/403 refresh-and-retry, never wipe the token; read the token uncached so the long-lived daemon observes cross-process refreshes; resolve endpoint via getEndpointFromTokenAllowExpired fallback so a drain still delivers while refresh is pending.
  • lib/jwt.js: getEndpointFromTokenAllowExpired — endpoint is routing info, valid even from an expired token (never used for auth).
  • credstore.js: getLicenseTokenUncached (disk-bypass read).

P2

  • monitors/retry_daemon.js: in-memory adaptive backoff (exp ×2 up to 30 min, reset on queue progress) via new transfer.queuedFileCount(). Empty-queue sweeps no longer trigger a refresh.

Compatibility

Works before and after the server-side POST /refresh route (skillbench-infra #45): until it's deployed, refresh falls back to the silent gh path (unchanged). The collector still accepts unauthenticated uploads, so delivery never depends on a valid token.

Verification

  • node -c on all 6 changed files; no require cycle.
  • shouldRefresh unit decision table — 9/9 (cooldown vs staleness, force bypasses cooldown but respects in-flight lock).
  • Hermetic fake-server E2E (isolated HOME/ROOT, server returns 401-once-then-202): single /refresh per batch despite 3 files + a 401, token preserved (not wiped), zero refresh on empty queue, all files delivered → .sent.

Version

0.15.0 → 0.16.0 (feat).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Enhanced license token handling with automatic refresh capabilities on authentication failures.
    • Improved retry logic for data uploads with adaptive backoff intervals to reduce unnecessary network requests.
  • Chores

    • Version updated to 0.16.0.

…andling; v0.16.0

The license JWT (15-min TTL) was refreshed only at SessionStart, so mid-session
and retry-daemon uploads ran with an expired token. Two failure modes followed:
the drain skipped uploads entirely (expired token -> no resolvable endpoint),
and a 401 wiped the stored license (`setLicenseToken("")`).

P1:
- lib/license-activation.js: add `ensureFreshLicense(deviceId,{force})` —
  best-effort, cross-process single-flight (mtime lock, 60s cooldown / 15s
  staleness) wrapper around the refresh orchestration (`refreshLicense`, lifted
  from logger.tryRefreshLicense, which now delegates). Pure `shouldRefresh`
  decision split out for testing. Placed in this leaf module to avoid a
  logger<->transfer require cycle.
- transfer.js: refresh once per drain batch (covers SessionStart, daemon,
  session-end); on 401/403 refresh-and-retry instead of wiping the token;
  read the token uncached so the long-lived daemon sees cross-process refreshes.
- jwt.js: `getEndpointFromTokenAllowExpired` — endpoint is routing info, valid
  even from an expired token (collector accepts unauth), so a drain still
  delivers while refresh is pending.
- credstore.js: `getLicenseTokenUncached` (disk-bypass read for the daemon).

P2:
- retry_daemon.js: in-memory adaptive backoff (exp up to 30m, reset on queue
  progress) via new transfer.queuedFileCount(); empty-queue sweeps no longer
  fire a refresh.

Verified: node -c (6 files), no require cycle, shouldRefresh unit table 9/9,
hermetic fake-server E2E (single /refresh per batch, token preserved on 401,
zero refresh on empty queue, all files delivered). Works before/after the
server-side /refresh route (skillbench-infra #45) via the gh fallback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: acac12f7-1605-44fc-8d2d-2b6b544d6ce7

📥 Commits

Reviewing files that changed from the base of the PR and between 2ea51c1 and 66ea1b5.

📒 Files selected for processing (7)
  • skillmeter/.claude-plugin/plugin.json
  • skillmeter/scripts/credstore.js
  • skillmeter/scripts/lib/jwt.js
  • skillmeter/scripts/lib/license-activation.js
  • skillmeter/scripts/lib/transfer.js
  • skillmeter/scripts/logger.js
  • skillmeter/scripts/monitors/retry_daemon.js

Walkthrough

Adds a cross-process single-flight license token refresh system using a lock file with cooldown and stale thresholds. Introduces uncached token reads, expired-JWT-tolerant endpoint resolution, and refreshLicense/ensureFreshLicense orchestrators in license-activation.js. Updates transfer.js to retry uploads on 401/403 with a refreshed token before falling back to unauthenticated upload. Refactors logger.js to delegate to the new API, adds adaptive backoff to the retry daemon, and bumps the plugin version to 0.16.0.

Changes

License Refresh Reliability & Retry Hardening

Layer / File(s) Summary
Uncached token read and expired-JWT endpoint resolution
skillmeter/scripts/credstore.js, skillmeter/scripts/lib/jwt.js
getLicenseTokenUncached() reads license_jwt directly from disk bypassing the in-process cache. getEndpointFromTokenAllowExpired() resolves the telemetry endpoint from a JWT claim without the expiry gate. Both are exported.
License refresh orchestration with lock-file single-flight
skillmeter/scripts/lib/license-activation.js
Adds fs/LOG_DIR imports, LICENSE_REFRESH_COOLDOWN_MS/LICENSE_REFRESH_STALE_MS constants, pure shouldRefresh() decision logic, refreshLicense() orchestrator (JWT rotation via /refresh with gh fallback), and ensureFreshLicense() as a never-throw best-effort wrapper with cross-process lock-file coordination.
Transfer upload retry with refresh-on-401/403 fallback
skillmeter/scripts/lib/transfer.js
transferEventLog and uploadPendingTranscript use uncached tokens, skip expired JWTs, resolve endpoints via getEndpointFromTokenAllowExpired, and on 401/403 call ensureFreshLicense once then retry; failed retries attempt an unauthenticated upload. drainFailedLogs and drainPendingTranscripts call ensureFreshLicense once per batch. Adds and exports queuedFileCount().
Logger delegation and retry daemon adaptive backoff
skillmeter/scripts/logger.js, skillmeter/scripts/monitors/retry_daemon.js
logger.js replaces inline refresh logic with a thin wrapper delegating to refreshLicense. retry_daemon.js adds MAX_INTERVAL_MS and replaces the fixed sleep with an exponential backoff loop that resets when the queue shrinks.
Plugin version bump
skillmeter/.claude-plugin/plugin.json
Version incremented from 0.15.0 to 0.16.0.

Sequence Diagram(s)

sequenceDiagram
  rect rgba(70, 130, 180, 0.5)
    Note over transfer.js,TelemetryEndpoint: Upload with auth-retry
    transfer.js->>credstore.js: getLicenseTokenUncached()
    credstore.js-->>transfer.js: token (dropped if expired)
    transfer.js->>jwt.js: getEndpointFromTokenAllowExpired(token)
    jwt.js-->>transfer.js: endpoint URL (or null → keep file for retry)
    transfer.js->>TelemetryEndpoint: POST event log / transcript with JWT
  end
  rect rgba(220, 100, 60, 0.5)
    Note over transfer.js,ensureFreshLicense: 401/403 refresh-and-retry path
    TelemetryEndpoint-->>transfer.js: 401 or 403
    transfer.js->>ensureFreshLicense: ensureFreshLicense(deviceId, {force:true})
    ensureFreshLicense->>license-activation.js: shouldRefresh() → acquire lock file
    license-activation.js->>credstore.js: getLicenseTokenUncached()
    license-activation.js->>ActivationEndpoint: POST /refresh (or gh auth token fallback)
    ActivationEndpoint-->>license-activation.js: new JWT
    ensureFreshLicense-->>transfer.js: fresh token
    transfer.js->>TelemetryEndpoint: retry POST with fresh JWT
    alt retry still fails
      transfer.js->>TelemetryEndpoint: unauthenticated upload fallback
    end
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

  • jhunlee-dev

Poem

🐇 Hops through the token maze with glee,
A lock file guards the refresh spree,
Expired JWTs? No need to cry—
Retry with fresh creds on the fly!
If 401 bites, we bounce right back,
The queue shrinks fast upon our track. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: implementing robust on-demand JWT refresh with non-destructive 401 handling, and includes the version bump to v0.16.0.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/robust-jwt-refresh

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 OpenGrep (1.22.0)

OpenGrep fatal error (exit code 2):
┌──────────────┐
│ Opengrep CLI │
└──────────────┘

�[32m✔�[39m �[1mOpengrep OSS�[0m
�[32m✔�[39m Basic security coverage for first-party code vulnerabilities.

�[1m Loading rules from local config...�[0m
[00.15][ERROR]: Error: exception Glob.Lexer.Syntax_error("malformed glob pattern: missing ']'")
Raised at Glob__Lexer.syntax_error in file "libs/glob/Lexer.mll", line 8, characters 2-26
Called from Glob__Lexer.__ocaml_lex_token_rec in file "libs/glob/Lexer.mll", line 29, characters 26-53
Cal


Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant