Skip to content

JWT expiry check + reactive auth retry in telemetry transfers - #38

Merged
minarc merged 1 commit into
mainfrom
fix/jwt-expiry-and-retry
Apr 21, 2026
Merged

minarc merged 1 commit into
mainfrom
fix/jwt-expiry-and-retry

Conversation

@minarc

@minarc minarc commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The plugin stored the license JWT indefinitely and always sent it. The JWT has a 15-minute `exp` claim, so once it's past, every transfer loops forever on HTTP 401: the server rejects it, we log "HTTP 401", the file stays in place, next SessionStart's `retryFailedLogs` picks it up and sends the same expired JWT. Events get permanently stuck; that's Critical #4 from the bug analysis.

This PR applies a belt-and-suspenders fix.

Behavior

Proactive — `isJwtExpired(token)` decodes the payload and checks `exp` (30s grace for clock skew). Before any transfer, we drop the `Authorization` header when the cached JWT is already past its exp. PR #35 made auth optional server-side, so the request still succeeds.

Reactive — if the server returns 401 or 403 despite our header, we:

  1. `credstore.setLicenseToken("")` — clear the bad token so subsequent hooks don't reuse it.
  2. Retry the request once without Authorization.

Other 4xx statuses (400, 404, 413, …) do not trigger retry — resending the same payload won't help. The file is left in place for next-session `retryFailedLogs`.

Applied to both `transferEventLog` and `transferTranscript`.

Verified (stubbed `global.fetch`)

Scenario Expected Got
Expired JWT in credstore 1 call, no Authorization, 202 success ✅
Valid-looking JWT + server 401 2 calls, retry drops auth, license cleared, file → `.sent` ✅
Valid-looking JWT + server 400 1 call (no retry), license preserved, file left for retry ✅

Plus a JWT-expiry table test on 7 cases (far-future, far-past, within-grace, no-exp, null, …) — all pass.

Out of scope

  • Token refresh on 401 (silent gh re-activation). Current PR just drops the bad token; the next `/sk-activate` or session-level silent activate handles re-auth. Adding inline refresh in the transfer path makes the hot path more complex and is a separate decision.
  • Critical dev #6 — per-file retry counter cap. Stuck files still accumulate; the counter is tracked as a follow-up.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced JWT token validation with automatic expiration detection and grace period handling.
    • Improved authentication failure resilience with automatic retry logic for authorization errors.
    • Optimized token cache management to proactively clear expired tokens before requests.
  • Refactor

    • Streamlined request header construction and consolidated logging utilities.

The plugin stored the license JWT indefinitely and always sent it as
`Authorization: Bearer …`. Two concrete failure modes:

1. The JWT has a 15-minute `exp` claim. Once past, every subsequent
   transfer hits the server with an expired token. The server
   rejects it; we log "HTTP 401" and leave the file in place. Next
   SessionStart's retryFailedLogs picks the same file up and sends
   the same expired JWT again — permanent 401 loop, events stuck.
2. A mid-lifetime revocation (server rotates keys, plugin cache
   gets stale, etc.) produces the same loop without ever expiring
   client-side.

Fix is belt-and-suspenders in logger.js:

Proactive: isJwtExpired(token) decodes the JWT payload and returns
true when `exp` is already past (30s grace for clock skew). Before
transferring we drop the Authorization header when the cached JWT
is expired. PR #35 made auth optional server-side so the request
still succeeds.

Reactive: if the server returns 401 or 403 despite our header,
credstore.setLicenseToken("") clears the bad token (so the next
hook doesn't reuse it) and we retry once without Authorization.
Retry applies only to those two statuses — other 4xx (400, 404,
413, …) leave the file for next-session retry since they won't
recover from a naive resend.

Applied to both transferEventLog and transferTranscript with
matching control flow.

Verified with stubbed fetch:
- expired JWT → 1 call, no Authorization, server happy-path accepts
- valid-looking JWT + server 401 → 2 calls, retry drops auth,
  license cleared, original file renamed to .sent
- valid-looking JWT + server 400 → 1 call (no retry), license
  preserved, original file left for later retry

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Added JWT expiration validation with a 30-second grace window to skillmeter/scripts/logger.js. Modified transferEventLog and transferTranscript to conditionally attach Authorization headers based on token validity. Implemented automatic token clearing and retry logic when receiving 401/403 responses after token-authenticated requests.

Changes

Cohort / File(s) Summary
JWT Expiration and Authorization Management
skillmeter/scripts/logger.js
Added isJwtExpired() helper to check token expiration with 30-second grace window. Introduced buildHeaders() to conditionally include Authorization: Bearer header only for valid tokens. Both transferEventLog and transferTranscript now check token expiration before attaching headers.
Request and Retry Control Flow
skillmeter/scripts/logger.js
Updated transfer functions to POST with initial token; if response is 401/403 and token was used, clear stored license token and automatically retry without Authorization header. Centralized file rename logic into markSent() helper triggered after successful requests.

Sequence Diagram

sequenceDiagram
    participant Script as Event Transfer Script
    participant TokenMgmt as Token Management
    participant Server as Server Endpoint
    participant Storage as License Token Store

    rect rgba(135, 206, 235, 0.5)
        Note over Script,Storage: Initial Request Flow
        Script->>TokenMgmt: isJwtExpired(cachedToken)?
        TokenMgmt-->>Script: expired status
        Script->>TokenMgmt: buildHeaders(token)
        TokenMgmt-->>Script: headers with/without Authorization
        Script->>Server: POST with initialToken
    end

    rect rgba(255, 182, 193, 0.5)
        Note over Script,Storage: Retry Flow (on 401/403 with token)
        Server-->>Script: 401/403 Response
        Script->>Storage: setLicenseToken("")
        Storage-->>Script: token cleared
        Script->>Server: POST retry without Authorization
    end

    rect rgba(144, 238, 144, 0.5)
        Note over Script,Storage: Success Path
        Server-->>Script: 200 Response
        Script->>Script: markSent()
        Note over Script: File marked as sent
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • PR #35: Modifies transferEventLog/transferTranscript in logger.js to conditionally attach Authorization and retry without token on auth failures.
  • PR #7: Updates license token handling in logger.js, including JWT acquisition and usage in transfer functions.
  • PR #34: Extends JWT decoding and modifies how Authorization headers and endpoints are handled in logger.js transfer logic.

Suggested reviewers

  • jhunlee-dev

Poem

🐰 Tokens expire, but we've got grace!
With thirty seconds, we keep the pace.
When 401s rear their stubborn head,
We clear and retry—no token instead!

🚥 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 'JWT expiry check + reactive auth retry in telemetry transfers' directly and specifically summarizes the main changes: adding JWT expiration checking and implementing reactive authentication retry logic in telemetry transfer functions.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 fix/jwt-expiry-and-retry

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
skillmeter/scripts/logger.js (2)

372-374: Race condition between concurrent transfers is benign but worth documenting.

When flushAndTransfer runs both transferEventLog and transferTranscript concurrently, both may detect 401/403 and call credstore.setLicenseToken("") simultaneously. Per the relevant code snippets, setLicenseToken lacks synchronization, but since both are setting to empty string, the operation is idempotent and the final state is always correct.

Consider adding a brief comment noting this is intentionally safe due to idempotency.

Also applies to: 441-443

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skillmeter/scripts/logger.js` around lines 372 - 374, Add a brief inline
comment at the sites where transferEventLog and transferTranscript call
credstore.setLicenseToken("") (e.g., inside transferEventLog and
transferTranscript invoked by flushAndTransfer) explaining that concurrent calls
are benign because setLicenseToken is idempotent and no synchronization is
required; reference the functions transferEventLog, transferTranscript,
flushAndTransfer and the method credstore.setLicenseToken("") in the comment so
future readers understand this race is intentional and safe.

401-455: Consider extracting shared retry logic (optional refactor).

Both transferEventLog and transferTranscript now share nearly identical patterns for:

  • Proactive token expiry checking
  • Building headers conditionally
  • POST execution
  • Reactive 401/403 retry with token clearing

This duplication is acceptable for this PR's scope, but a follow-up could extract a shared transferWithAuthRetry(endpoint, headers, body, timeout, onSuccess) helper to centralize the auth retry logic.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skillmeter/scripts/logger.js` around lines 401 - 455, The transfer logic in
transferTranscript duplicates the same auth-check, header building, POST and
401/403-retry flow used elsewhere; extract that into a shared helper (e.g.,
transferWithAuthRetry) and replace the duplicated code in both
transferTranscript and transferEventLog with calls to it. Implement
transferWithAuthRetry to accept parameters (endpointPath or full URL, a
buildHeaders(token) function, body, timeout, and optional onSuccess callback),
have it perform the proactive token expiry check (using getLicenseToken and
isJwtExpired), call fetch with AbortSignal.timeout, handle res.ok success, on
401/403 when initial token was used call credstore.setLicenseToken("") and retry
with null token, and propagate/log failures and fetch errors the same way the
current doPost/then/catch does; then update transferTranscript to use
buildHeaders and compressed body with transferWithAuthRetry instead of the
inline doPost logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@skillmeter/scripts/logger.js`:
- Around line 372-374: Add a brief inline comment at the sites where
transferEventLog and transferTranscript call credstore.setLicenseToken("")
(e.g., inside transferEventLog and transferTranscript invoked by
flushAndTransfer) explaining that concurrent calls are benign because
setLicenseToken is idempotent and no synchronization is required; reference the
functions transferEventLog, transferTranscript, flushAndTransfer and the method
credstore.setLicenseToken("") in the comment so future readers understand this
race is intentional and safe.
- Around line 401-455: The transfer logic in transferTranscript duplicates the
same auth-check, header building, POST and 401/403-retry flow used elsewhere;
extract that into a shared helper (e.g., transferWithAuthRetry) and replace the
duplicated code in both transferTranscript and transferEventLog with calls to
it. Implement transferWithAuthRetry to accept parameters (endpointPath or full
URL, a buildHeaders(token) function, body, timeout, and optional onSuccess
callback), have it perform the proactive token expiry check (using
getLicenseToken and isJwtExpired), call fetch with AbortSignal.timeout, handle
res.ok success, on 401/403 when initial token was used call
credstore.setLicenseToken("") and retry with null token, and propagate/log
failures and fetch errors the same way the current doPost/then/catch does; then
update transferTranscript to use buildHeaders and compressed body with
transferWithAuthRetry instead of the inline doPost logic.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2e134a99-4365-4015-ab23-0e6e5f211f46

📥 Commits

Reviewing files that changed from the base of the PR and between b8fc9e6 and 319bc1c.

📒 Files selected for processing (1)
  • skillmeter/scripts/logger.js

@minarc
minarc requested a review from jhunlee-dev April 21, 2026 18:02
@minarc
minarc merged commit 167766e into main Apr 21, 2026
1 check passed
@TheStarkor
TheStarkor deleted the fix/jwt-expiry-and-retry branch September 21, 2026 18:40
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.

2 participants