Repository navigation
JWT expiry check + reactive auth retry in telemetry transfers - #38
Conversation
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>
WalkthroughAdded JWT expiration validation with a 30-second grace window to Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
skillmeter/scripts/logger.js (2)
372-374: Race condition between concurrent transfers is benign but worth documenting.When
flushAndTransferruns bothtransferEventLogandtransferTranscriptconcurrently, both may detect 401/403 and callcredstore.setLicenseToken("")simultaneously. Per the relevant code snippets,setLicenseTokenlacks 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
transferEventLogandtransferTranscriptnow 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
📒 Files selected for processing (1)
skillmeter/scripts/logger.js
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:
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`)
Plus a JWT-expiry table test on 7 cases (far-future, far-past, within-grace, no-exp, null, …) — all pass.
Out of scope
🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Refactor