feat(auth): add OAuth refresh token session handling - #205

Merged
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support
Apr 22, 2026
Merged

feat(auth): add OAuth refresh token session handling#205
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support

Conversation

@wyattjoh

@wyattjohwyattjoh commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Summary

OAuth access tokens issued to the CLI are now short-lived JWTs. The credential store previously persisted only the raw access token, so once the token's exp passed every authenticated command failed with a 401 and forced the user back through clerk auth login. This change persists the full OAuth session, refreshes the access token transparently from the stored refresh token, and routes every auth failure through a single typed error so downstream code can react without string-matching.

What changed

  • Credential store now holds a session, not a bare token.storeToken accepts either a legacy access-token string or an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and persists it as JSON to the same keyring/file slot. getToken() stays backwards-compatible for readers that only want the string, so a session written by an older build is still readable.
  • New getValidToken() decodes the access-token JWT exp, and if it is within a 30s leeway of expiry calls the OAuth token endpoint with the stored refresh token, writes the new session back, and returns the fresh access token. invalid_grant responses wipe the stored session and raise AUTH_REQUIRED so the user is told to re-login rather than hitting a silent 401 loop.
  • All authenticated call sites route through getValidToken(): login, whoami, plapi requests, init heuristics, and every doctor check that needs a live session. Presence-only probes (is the user logged in at all?) use the new hasStoredCredentials() so we don't refresh as a side effect of non-auth flows.
  • Doctor validates the refresh path. The auth-related checks now pull the session through getValidToken() so clerk doctor surfaces refresh failures (expired refresh token, server-side revoke) the same way it surfaces other auth breakage, instead of reporting a healthy session while the next real call 401s.
  • Centralized auth error handling. New AuthError subclass of CliError carries a reason discriminator (not_logged_in / session_expired) with default per-reason messages, always codes to AUTH_REQUIRED, and replaces the hand-rolled CliError throws in whoami, plapi.getAuthToken, and credential-store. Doctor's token check now uses a new isAuthError() type guard covering both AuthError and ApiError(401|403) instead of regex-matching (401|403) substrings in error messages, so message-copy changes can't silently break the check.

Test plan

  • bun run format:check, bun run lint, bun run typecheck, bun run test
  • Unit coverage for getValidToken(): valid JWT returns unchanged, near-expiry JWT triggers a refresh and rewrites the session, invalid_grant clears credentials and throws AUTH_REQUIRED.
  • Doctor test covers the refresh-failure path by injecting an AuthError({ reason: "session_expired" }) into getValidToken() and asserting the check fails with the re-login remedy.
  • Manual: log in, force the access token past exp, run clerk whoami and confirm a refresh request fires and the session is rewritten transparently.
  • Manual: revoke the refresh token server-side, rerun a command, confirm the CLI reports session expired and clears the stored credentials.
  • Full E2E CI run on the PR.

@changeset-bot

changeset-botBot commented Apr 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9991c0c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
clerkMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch 2 times, most recently from dbb4068 to b1ea0f7CompareApril 22, 2026 15:36
@wyattjoh
wyattjoh marked this pull request as ready for review April 22, 2026 15:37
@coderabbitai

coderabbitaiBot commented Apr 22, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds OAuth refresh-token support across the CLI: credential storage now persists an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and exposes createOAuthSession, getStoredSession, hasStoredCredentials, and getValidToken. getValidToken validates expiry and attempts refresh via refreshAccessToken, deleting credentials and throwing AuthError(reason: "session_expired") on invalid_grant. Introduces AuthError and isAuthError. Commands and doctor/init/whoami/plapi call getValidToken instead of getToken. Tests and mocks updated to exercise session persistence and refresh flows; token-exchange gains refreshAccessToken.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 6.98% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Title check✅ PassedThe title accurately describes the main change: adding OAuth refresh token session handling to automatically refresh expired access tokens.
Description check✅ PassedThe description comprehensively explains the OAuth refresh token feature, the problem it solves, implementation details, affected call sites, and test coverage.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

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


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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/cli-core/src/commands/auth/login.test.ts (3)

521-521: ⚠️ Potential issue | 🔴 Critical

Build failure: mockGetToken is undefined.

The pipeline reports TS2304: Cannot find name 'mockGetToken'. This should be mockGetValidToken to match the mock defined at line 7.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 521, The test
references an undefined variable `mockGetToken`; replace that usage with the
correctly defined mock `mockGetValidToken` in the failing test (the call at the
line with mockGetToken.mockResolvedValue(null)) so the test uses the existing
mock variable `mockGetValidToken` instead of the non-existent `mockGetToken`.

553-553: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 553, The failing
test reuses the same mockGetToken reference across test cases which causes value
bleed and unpredictable behavior; update the tests to either reset/replace
mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.

582-582: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue("existing-token");+ mockGetValidToken.mockResolvedValue("existing-token");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 582, The test is
reusing the same mock reference mockGetToken which causes cross-test leakage;
change the setup to create an isolated mock or set a one-time resolution so
other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/commands/init/heuristics.ts`:
- Around line 6-7: The isAuthenticated check currently relies on
getStoredSession()/getValidToken deserialization and can misclassify legacy
stored credentials; change isAuthenticated to perform a credential-presence
check instead (e.g., verify existence of any stored credential/token rather than
successful session deserialization). Update the logic in heuristics.ts where
isAuthenticated is implemented/used (referencing getStoredSession, getValidToken
and the isAuthenticated call) to detect presence of credentials in the store and
return true for legacy tokens, ensuring keyless init isn't incorrectly chosen;
keep existing validation flows for full session usage separate from this
presence check.
In `@packages/cli-core/src/lib/plapi.ts`:
- Around line 60-64: The API command tests are failing because getValidToken()
now throws an AuthError with reason "not_logged_in"; update the api command test
mocks in index.test.ts to either mock getValidToken() to throw an AuthError
instance with the same reason/message/docsUrl and assert that the command
surface handles/propagates that error, or change the mock to return a valid
token for tests that expect authenticated behavior; specifically adjust the mock
setup and assertions to reference AuthError and getValidToken() so the tests
reflect the new unauthenticated PLAPI path.
---
Outside diff comments:
In `@packages/cli-core/src/commands/auth/login.test.ts`:
- Line 521: The test references an undefined variable `mockGetToken`; replace
that usage with the correctly defined mock `mockGetValidToken` in the failing
test (the call at the line with mockGetToken.mockResolvedValue(null)) so the
test uses the existing mock variable `mockGetValidToken` instead of the
non-existent `mockGetToken`.
- Line 553: The failing test reuses the same mockGetToken reference across test
cases which causes value bleed and unpredictable behavior; update the tests to
either reset/replace mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.
- Line 582: The test is reusing the same mock reference mockGetToken which
causes cross-test leakage; change the setup to create an isolated mock or set a
one-time resolution so other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b17f3a36-f5cd-4db0-a653-43dfc0f9b368

📥 Commits

Reviewing files that changed from the base of the PR and between ef06e2c and b1ea0f7.

📒 Files selected for processing (18)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment threadpackages/cli-core/src/commands/init/heuristics.ts Outdated
Comment threadpackages/cli-core/src/lib/plapi.ts
@kylemac
kylemac requested a review from jfosheeApril 22, 2026 16:08
Align the implementation with the documented "pure credential-presence
check" intent. The previous code deserialized via getStoredSession() and
returned false for legacy raw-string credentials that don't match the
OAuthSession shape, incorrectly sending those users to the keyless init
flow.
@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch from 6009648 to 026c76cCompareApril 22, 2026 17:26

@rafa-thaytorafa-thayto 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.

LGTM

const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

If two parallel CLI calls hit getValidToken() while the token is expired, both will race into refreshStoredSession with the same refresh token. If the server rotates refresh tokens on use, the second call gets invalid_grant and nukes the credentials the first call just wrote.

Not likely in typical CLI usage, but could bite in CI scripts running clerk commands in parallel. A module-level promise guard would deduplicate:

Suggested change
}
letrefreshInFlight: Promise<string>|undefined;
asyncfunctionrefreshStoredSession(session: OAuthSession): Promise<string>{
if(refreshInFlight)returnrefreshInFlight;
refreshInFlight=doRefreshStoredSession(session).finally(()=>{
refreshInFlight=undefined;
});
returnrefreshInFlight;
}
asyncfunctiondoRefreshStoredSession(session: OAuthSession): Promise<string>{

Non-blocking, happy to merge as-is and handle this as a follow-up.

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

I got a version that's resilient to this change when more than one cli is operating at once. Don't think we needed the in-process protections as much as the cross-process ones.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/lib/credential-store.ts`:
- Around line 324-340: getValidToken treats any non-JSON legacy stored value as
an expired session because getStoredSession only handles the new JSON shape; to
fix this, update the flow to accept legacy raw tokens: in getStoredSession (or
in parseStoredSession) detect if readStoredValue() returns a plain string
(legacy raw token) and return an OAuthSession-like object (or at least an object
with accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2b91a154-39a2-4ecc-9516-cdbcd12329a3

📥 Commits

Reviewing files that changed from the base of the PR and between 6009648 and 026c76c.

📒 Files selected for processing (21)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/api/index.test.ts
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/lib/credential-store.test.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/api/index.test.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment on lines +324 to +340
export async function getStoredSession(): Promise<OAuthSession | null> {
const value = await readStoredValue();
if (!value) return null;
return parseStoredSession(value);
}

return fileGet();
export async function hasStoredCredentials(): Promise<boolean> {
return (await readStoredValue()) !== null;
}

export async function getValidToken(): Promise<string | null> {
const session = await getStoredSession();
if (!session) {
if (await hasStoredCredentials()) {
throw sessionExpiredError();
}
return null;

@coderabbitaicoderabbitaiBotApr 22, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Legacy raw credentials are treated as expired immediately.

getStoredSession() only recognizes the new JSON shape, so any pre-upgrade raw access token falls into this branch and becomes session_expired. Since authenticated commands now go through getValidToken(), upgrading will force every previously logged-in user to re-authenticate even when their stored token is still valid.

Suggested fix
 export async function getValidToken(): Promise<string | null> {
- const session = await getStoredSession();- if (!session) {- if (await hasStoredCredentials()) {- throw sessionExpiredError();- }- return null;- }+ const value = await readStoredValue();+ if (!value) return null;++ const session = parseStoredSession(value);+ if (!session) {+ const expiresAt = getJwtExpiryMs(value);+ if (expiresAt !== null && expiresAt <= Date.now() + JWT_EXPIRY_LEEWAY_MS) {+ throw sessionExpiredError();+ }+ return value;+ }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/lib/credential-store.ts` around lines 324 - 340,
getValidToken treats any non-JSON legacy stored value as an expired session
because getStoredSession only handles the new JSON shape; to fix this, update
the flow to accept legacy raw tokens: in getStoredSession (or in
parseStoredSession) detect if readStoredValue() returns a plain string (legacy
raw token) and return an OAuthSession-like object (or at least an object with
accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This is intentional

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@wyattjoh, understood — forcing a one-time re-authentication for users with a legacy raw token on upgrade is an intentional migration cut-over. I'll note this for future reviews.


✏️ Learnings added
Learnt from: wyattjoh
Repo: clerk/cli PR: 205
File: packages/cli-core/src/lib/credential-store.ts:324-340
Timestamp: 2026-04-22T17:39:54.554Z
Learning: In clerk/cli credential-store (`packages/cli-core/src/lib/credential-store.ts`), `getValidToken()` intentionally treats any stored credential that cannot be parsed as a valid `OAuthSession` JSON (i.e. a legacy raw access token string) as a `session_expired` error, forcing a one-time re-authentication on upgrade. Do not flag this as a bug — it is a deliberate migration design decision by the author.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: wyattjoh
Repo: clerk/cli PR: 118
File: packages/cli-core/src/commands/init/skills.ts:117-124
Timestamp: 2026-04-07T22:06:40.516Z
Learning: In clerk/cli, cancellation from inquirer/prompts (e.g., Ctrl+C resulting in UserAbortError / ExitPromptError) is handled globally in cli-program.ts (around the existing global catch). Therefore, command-level prompt call sites (e.g., confirm(), select()) in packages/cli-core/src should not wrap these prompt calls in local try/catch for UserAbortError/ExitPromptError cancellations—such local handling would be dead code and should remain consistent with the shared cancellation behavior.

Learnt from: wyattjoh
Repo: clerk/cli PR: 153
File: .claude/rules/scripts.md:36-36
Timestamp: 2026-04-13T23:09:41.178Z
Learning: In the clerk/cli repository, do not treat `Bun.$` (Bun Shell API) as experimental/unstable during code review. `Bun.$` is a stable, documented core Bun runtime feature (similar in status to `Bun.spawn` and `Bun.file`), so reviewers should not raise warnings that it relies on experimental APIs.

@jfosheejfoshee 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.

Some initial comments. I am still reviewing. :-)

Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
Comment threadpackages/cli-core/src/lib/credential-store.ts
Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

@wyattjoh
wyattjoh requested a review from jfosheeApril 22, 2026 18:05

@jfosheejfoshee 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.

Looks good. I did a manual test locally w/ a 5 min access token. Worked fine. It would just be nice to see something in the trace log that it was doing a refresh.

Another nice-to-have would be a manual refresh? like clerk auth refresh? wdyt? could be an internal only testing command.

async function refreshStoredSession(session: OAuthSession): Promise<string> {
let tokenResponse: TokenResponse;
try {
tokenResponse = await refreshAccessToken(session.refreshToken);

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.

I would like to see in the debug trace that we are doing a refresh. Is this the place to log it?

@wyattjoh
wyattjoh merged commit 23a3089 into mainApr 22, 2026
10 checks passed
@wyattjoh
wyattjoh deleted the wyattjoh/oauth-refresh-token-support branch April 22, 2026 18:39
@github-actionsgithub-actionsBot mentioned this pull request Apr 22, 2026
Sign up for freeto 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.

3 participants

@wyattjoh@jfoshee@rafa-thayto
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

feat(auth): add OAuth refresh token session handling - #205

Merged
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support
Apr 22, 2026
Merged

feat(auth): add OAuth refresh token session handling#205
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support

Conversation

@wyattjoh

@wyattjohwyattjoh commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Summary

OAuth access tokens issued to the CLI are now short-lived JWTs. The credential store previously persisted only the raw access token, so once the token's exp passed every authenticated command failed with a 401 and forced the user back through clerk auth login. This change persists the full OAuth session, refreshes the access token transparently from the stored refresh token, and routes every auth failure through a single typed error so downstream code can react without string-matching.

What changed

  • Credential store now holds a session, not a bare token.storeToken accepts either a legacy access-token string or an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and persists it as JSON to the same keyring/file slot. getToken() stays backwards-compatible for readers that only want the string, so a session written by an older build is still readable.
  • New getValidToken() decodes the access-token JWT exp, and if it is within a 30s leeway of expiry calls the OAuth token endpoint with the stored refresh token, writes the new session back, and returns the fresh access token. invalid_grant responses wipe the stored session and raise AUTH_REQUIRED so the user is told to re-login rather than hitting a silent 401 loop.
  • All authenticated call sites route through getValidToken(): login, whoami, plapi requests, init heuristics, and every doctor check that needs a live session. Presence-only probes (is the user logged in at all?) use the new hasStoredCredentials() so we don't refresh as a side effect of non-auth flows.
  • Doctor validates the refresh path. The auth-related checks now pull the session through getValidToken() so clerk doctor surfaces refresh failures (expired refresh token, server-side revoke) the same way it surfaces other auth breakage, instead of reporting a healthy session while the next real call 401s.
  • Centralized auth error handling. New AuthError subclass of CliError carries a reason discriminator (not_logged_in / session_expired) with default per-reason messages, always codes to AUTH_REQUIRED, and replaces the hand-rolled CliError throws in whoami, plapi.getAuthToken, and credential-store. Doctor's token check now uses a new isAuthError() type guard covering both AuthError and ApiError(401|403) instead of regex-matching (401|403) substrings in error messages, so message-copy changes can't silently break the check.

Test plan

  • bun run format:check, bun run lint, bun run typecheck, bun run test
  • Unit coverage for getValidToken(): valid JWT returns unchanged, near-expiry JWT triggers a refresh and rewrites the session, invalid_grant clears credentials and throws AUTH_REQUIRED.
  • Doctor test covers the refresh-failure path by injecting an AuthError({ reason: "session_expired" }) into getValidToken() and asserting the check fails with the re-login remedy.
  • Manual: log in, force the access token past exp, run clerk whoami and confirm a refresh request fires and the session is rewritten transparently.
  • Manual: revoke the refresh token server-side, rerun a command, confirm the CLI reports session expired and clears the stored credentials.
  • Full E2E CI run on the PR.

@changeset-bot

changeset-botBot commented Apr 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9991c0c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
clerkMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch 2 times, most recently from dbb4068 to b1ea0f7CompareApril 22, 2026 15:36
@wyattjoh
wyattjoh marked this pull request as ready for review April 22, 2026 15:37
@coderabbitai

coderabbitaiBot commented Apr 22, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds OAuth refresh-token support across the CLI: credential storage now persists an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and exposes createOAuthSession, getStoredSession, hasStoredCredentials, and getValidToken. getValidToken validates expiry and attempts refresh via refreshAccessToken, deleting credentials and throwing AuthError(reason: "session_expired") on invalid_grant. Introduces AuthError and isAuthError. Commands and doctor/init/whoami/plapi call getValidToken instead of getToken. Tests and mocks updated to exercise session persistence and refresh flows; token-exchange gains refreshAccessToken.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 6.98% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Title check✅ PassedThe title accurately describes the main change: adding OAuth refresh token session handling to automatically refresh expired access tokens.
Description check✅ PassedThe description comprehensively explains the OAuth refresh token feature, the problem it solves, implementation details, affected call sites, and test coverage.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

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


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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/cli-core/src/commands/auth/login.test.ts (3)

521-521: ⚠️ Potential issue | 🔴 Critical

Build failure: mockGetToken is undefined.

The pipeline reports TS2304: Cannot find name 'mockGetToken'. This should be mockGetValidToken to match the mock defined at line 7.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 521, The test
references an undefined variable `mockGetToken`; replace that usage with the
correctly defined mock `mockGetValidToken` in the failing test (the call at the
line with mockGetToken.mockResolvedValue(null)) so the test uses the existing
mock variable `mockGetValidToken` instead of the non-existent `mockGetToken`.

553-553: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 553, The failing
test reuses the same mockGetToken reference across test cases which causes value
bleed and unpredictable behavior; update the tests to either reset/replace
mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.

582-582: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue("existing-token");+ mockGetValidToken.mockResolvedValue("existing-token");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 582, The test is
reusing the same mock reference mockGetToken which causes cross-test leakage;
change the setup to create an isolated mock or set a one-time resolution so
other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/commands/init/heuristics.ts`:
- Around line 6-7: The isAuthenticated check currently relies on
getStoredSession()/getValidToken deserialization and can misclassify legacy
stored credentials; change isAuthenticated to perform a credential-presence
check instead (e.g., verify existence of any stored credential/token rather than
successful session deserialization). Update the logic in heuristics.ts where
isAuthenticated is implemented/used (referencing getStoredSession, getValidToken
and the isAuthenticated call) to detect presence of credentials in the store and
return true for legacy tokens, ensuring keyless init isn't incorrectly chosen;
keep existing validation flows for full session usage separate from this
presence check.
In `@packages/cli-core/src/lib/plapi.ts`:
- Around line 60-64: The API command tests are failing because getValidToken()
now throws an AuthError with reason "not_logged_in"; update the api command test
mocks in index.test.ts to either mock getValidToken() to throw an AuthError
instance with the same reason/message/docsUrl and assert that the command
surface handles/propagates that error, or change the mock to return a valid
token for tests that expect authenticated behavior; specifically adjust the mock
setup and assertions to reference AuthError and getValidToken() so the tests
reflect the new unauthenticated PLAPI path.
---
Outside diff comments:
In `@packages/cli-core/src/commands/auth/login.test.ts`:
- Line 521: The test references an undefined variable `mockGetToken`; replace
that usage with the correctly defined mock `mockGetValidToken` in the failing
test (the call at the line with mockGetToken.mockResolvedValue(null)) so the
test uses the existing mock variable `mockGetValidToken` instead of the
non-existent `mockGetToken`.
- Line 553: The failing test reuses the same mockGetToken reference across test
cases which causes value bleed and unpredictable behavior; update the tests to
either reset/replace mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.
- Line 582: The test is reusing the same mock reference mockGetToken which
causes cross-test leakage; change the setup to create an isolated mock or set a
one-time resolution so other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b17f3a36-f5cd-4db0-a653-43dfc0f9b368

📥 Commits

Reviewing files that changed from the base of the PR and between ef06e2c and b1ea0f7.

📒 Files selected for processing (18)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment threadpackages/cli-core/src/commands/init/heuristics.ts Outdated
Comment threadpackages/cli-core/src/lib/plapi.ts
@kylemac
kylemac requested a review from jfosheeApril 22, 2026 16:08
Align the implementation with the documented "pure credential-presence
check" intent. The previous code deserialized via getStoredSession() and
returned false for legacy raw-string credentials that don't match the
OAuthSession shape, incorrectly sending those users to the keyless init
flow.
@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch from 6009648 to 026c76cCompareApril 22, 2026 17:26

@rafa-thaytorafa-thayto 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.

LGTM

const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

If two parallel CLI calls hit getValidToken() while the token is expired, both will race into refreshStoredSession with the same refresh token. If the server rotates refresh tokens on use, the second call gets invalid_grant and nukes the credentials the first call just wrote.

Not likely in typical CLI usage, but could bite in CI scripts running clerk commands in parallel. A module-level promise guard would deduplicate:

Suggested change
}
letrefreshInFlight: Promise<string>|undefined;
asyncfunctionrefreshStoredSession(session: OAuthSession): Promise<string>{
if(refreshInFlight)returnrefreshInFlight;
refreshInFlight=doRefreshStoredSession(session).finally(()=>{
refreshInFlight=undefined;
});
returnrefreshInFlight;
}
asyncfunctiondoRefreshStoredSession(session: OAuthSession): Promise<string>{

Non-blocking, happy to merge as-is and handle this as a follow-up.

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

I got a version that's resilient to this change when more than one cli is operating at once. Don't think we needed the in-process protections as much as the cross-process ones.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/lib/credential-store.ts`:
- Around line 324-340: getValidToken treats any non-JSON legacy stored value as
an expired session because getStoredSession only handles the new JSON shape; to
fix this, update the flow to accept legacy raw tokens: in getStoredSession (or
in parseStoredSession) detect if readStoredValue() returns a plain string
(legacy raw token) and return an OAuthSession-like object (or at least an object
with accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2b91a154-39a2-4ecc-9516-cdbcd12329a3

📥 Commits

Reviewing files that changed from the base of the PR and between 6009648 and 026c76c.

📒 Files selected for processing (21)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/api/index.test.ts
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/lib/credential-store.test.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/api/index.test.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment on lines +324 to +340
export async function getStoredSession(): Promise<OAuthSession | null> {
const value = await readStoredValue();
if (!value) return null;
return parseStoredSession(value);
}

return fileGet();
export async function hasStoredCredentials(): Promise<boolean> {
return (await readStoredValue()) !== null;
}

export async function getValidToken(): Promise<string | null> {
const session = await getStoredSession();
if (!session) {
if (await hasStoredCredentials()) {
throw sessionExpiredError();
}
return null;

@coderabbitaicoderabbitaiBotApr 22, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Legacy raw credentials are treated as expired immediately.

getStoredSession() only recognizes the new JSON shape, so any pre-upgrade raw access token falls into this branch and becomes session_expired. Since authenticated commands now go through getValidToken(), upgrading will force every previously logged-in user to re-authenticate even when their stored token is still valid.

Suggested fix
 export async function getValidToken(): Promise<string | null> {
- const session = await getStoredSession();- if (!session) {- if (await hasStoredCredentials()) {- throw sessionExpiredError();- }- return null;- }+ const value = await readStoredValue();+ if (!value) return null;++ const session = parseStoredSession(value);+ if (!session) {+ const expiresAt = getJwtExpiryMs(value);+ if (expiresAt !== null && expiresAt <= Date.now() + JWT_EXPIRY_LEEWAY_MS) {+ throw sessionExpiredError();+ }+ return value;+ }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/lib/credential-store.ts` around lines 324 - 340,
getValidToken treats any non-JSON legacy stored value as an expired session
because getStoredSession only handles the new JSON shape; to fix this, update
the flow to accept legacy raw tokens: in getStoredSession (or in
parseStoredSession) detect if readStoredValue() returns a plain string (legacy
raw token) and return an OAuthSession-like object (or at least an object with
accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This is intentional

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@wyattjoh, understood — forcing a one-time re-authentication for users with a legacy raw token on upgrade is an intentional migration cut-over. I'll note this for future reviews.


✏️ Learnings added
Learnt from: wyattjoh
Repo: clerk/cli PR: 205
File: packages/cli-core/src/lib/credential-store.ts:324-340
Timestamp: 2026-04-22T17:39:54.554Z
Learning: In clerk/cli credential-store (`packages/cli-core/src/lib/credential-store.ts`), `getValidToken()` intentionally treats any stored credential that cannot be parsed as a valid `OAuthSession` JSON (i.e. a legacy raw access token string) as a `session_expired` error, forcing a one-time re-authentication on upgrade. Do not flag this as a bug — it is a deliberate migration design decision by the author.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: wyattjoh
Repo: clerk/cli PR: 118
File: packages/cli-core/src/commands/init/skills.ts:117-124
Timestamp: 2026-04-07T22:06:40.516Z
Learning: In clerk/cli, cancellation from inquirer/prompts (e.g., Ctrl+C resulting in UserAbortError / ExitPromptError) is handled globally in cli-program.ts (around the existing global catch). Therefore, command-level prompt call sites (e.g., confirm(), select()) in packages/cli-core/src should not wrap these prompt calls in local try/catch for UserAbortError/ExitPromptError cancellations—such local handling would be dead code and should remain consistent with the shared cancellation behavior.

Learnt from: wyattjoh
Repo: clerk/cli PR: 153
File: .claude/rules/scripts.md:36-36
Timestamp: 2026-04-13T23:09:41.178Z
Learning: In the clerk/cli repository, do not treat `Bun.$` (Bun Shell API) as experimental/unstable during code review. `Bun.$` is a stable, documented core Bun runtime feature (similar in status to `Bun.spawn` and `Bun.file`), so reviewers should not raise warnings that it relies on experimental APIs.

@jfosheejfoshee 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.

Some initial comments. I am still reviewing. :-)

Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
Comment threadpackages/cli-core/src/lib/credential-store.ts
Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

@wyattjoh
wyattjoh requested a review from jfosheeApril 22, 2026 18:05

@jfosheejfoshee 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.

Looks good. I did a manual test locally w/ a 5 min access token. Worked fine. It would just be nice to see something in the trace log that it was doing a refresh.

Another nice-to-have would be a manual refresh? like clerk auth refresh? wdyt? could be an internal only testing command.

async function refreshStoredSession(session: OAuthSession): Promise<string> {
let tokenResponse: TokenResponse;
try {
tokenResponse = await refreshAccessToken(session.refreshToken);

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.

I would like to see in the debug trace that we are doing a refresh. Is this the place to log it?

@wyattjoh
wyattjoh merged commit 23a3089 into mainApr 22, 2026
10 checks passed
@wyattjoh
wyattjoh deleted the wyattjoh/oauth-refresh-token-support branch April 22, 2026 18:39
@github-actionsgithub-actionsBot mentioned this pull request Apr 22, 2026
Sign up for freeto 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.

3 participants

@wyattjoh@jfoshee@rafa-thayto
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(auth): add OAuth refresh token session handling - #205

Merged
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support
Apr 22, 2026
Merged

feat(auth): add OAuth refresh token session handling#205
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support

Conversation

@wyattjoh

@wyattjohwyattjoh commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Summary

OAuth access tokens issued to the CLI are now short-lived JWTs. The credential store previously persisted only the raw access token, so once the token's exp passed every authenticated command failed with a 401 and forced the user back through clerk auth login. This change persists the full OAuth session, refreshes the access token transparently from the stored refresh token, and routes every auth failure through a single typed error so downstream code can react without string-matching.

What changed

  • Credential store now holds a session, not a bare token.storeToken accepts either a legacy access-token string or an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and persists it as JSON to the same keyring/file slot. getToken() stays backwards-compatible for readers that only want the string, so a session written by an older build is still readable.
  • New getValidToken() decodes the access-token JWT exp, and if it is within a 30s leeway of expiry calls the OAuth token endpoint with the stored refresh token, writes the new session back, and returns the fresh access token. invalid_grant responses wipe the stored session and raise AUTH_REQUIRED so the user is told to re-login rather than hitting a silent 401 loop.
  • All authenticated call sites route through getValidToken(): login, whoami, plapi requests, init heuristics, and every doctor check that needs a live session. Presence-only probes (is the user logged in at all?) use the new hasStoredCredentials() so we don't refresh as a side effect of non-auth flows.
  • Doctor validates the refresh path. The auth-related checks now pull the session through getValidToken() so clerk doctor surfaces refresh failures (expired refresh token, server-side revoke) the same way it surfaces other auth breakage, instead of reporting a healthy session while the next real call 401s.
  • Centralized auth error handling. New AuthError subclass of CliError carries a reason discriminator (not_logged_in / session_expired) with default per-reason messages, always codes to AUTH_REQUIRED, and replaces the hand-rolled CliError throws in whoami, plapi.getAuthToken, and credential-store. Doctor's token check now uses a new isAuthError() type guard covering both AuthError and ApiError(401|403) instead of regex-matching (401|403) substrings in error messages, so message-copy changes can't silently break the check.

Test plan

  • bun run format:check, bun run lint, bun run typecheck, bun run test
  • Unit coverage for getValidToken(): valid JWT returns unchanged, near-expiry JWT triggers a refresh and rewrites the session, invalid_grant clears credentials and throws AUTH_REQUIRED.
  • Doctor test covers the refresh-failure path by injecting an AuthError({ reason: "session_expired" }) into getValidToken() and asserting the check fails with the re-login remedy.
  • Manual: log in, force the access token past exp, run clerk whoami and confirm a refresh request fires and the session is rewritten transparently.
  • Manual: revoke the refresh token server-side, rerun a command, confirm the CLI reports session expired and clears the stored credentials.
  • Full E2E CI run on the PR.

@changeset-bot

changeset-botBot commented Apr 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9991c0c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
clerkMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch 2 times, most recently from dbb4068 to b1ea0f7CompareApril 22, 2026 15:36
@wyattjoh
wyattjoh marked this pull request as ready for review April 22, 2026 15:37
@coderabbitai

coderabbitaiBot commented Apr 22, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds OAuth refresh-token support across the CLI: credential storage now persists an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and exposes createOAuthSession, getStoredSession, hasStoredCredentials, and getValidToken. getValidToken validates expiry and attempts refresh via refreshAccessToken, deleting credentials and throwing AuthError(reason: "session_expired") on invalid_grant. Introduces AuthError and isAuthError. Commands and doctor/init/whoami/plapi call getValidToken instead of getToken. Tests and mocks updated to exercise session persistence and refresh flows; token-exchange gains refreshAccessToken.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 6.98% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Title check✅ PassedThe title accurately describes the main change: adding OAuth refresh token session handling to automatically refresh expired access tokens.
Description check✅ PassedThe description comprehensively explains the OAuth refresh token feature, the problem it solves, implementation details, affected call sites, and test coverage.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

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


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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/cli-core/src/commands/auth/login.test.ts (3)

521-521: ⚠️ Potential issue | 🔴 Critical

Build failure: mockGetToken is undefined.

The pipeline reports TS2304: Cannot find name 'mockGetToken'. This should be mockGetValidToken to match the mock defined at line 7.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 521, The test
references an undefined variable `mockGetToken`; replace that usage with the
correctly defined mock `mockGetValidToken` in the failing test (the call at the
line with mockGetToken.mockResolvedValue(null)) so the test uses the existing
mock variable `mockGetValidToken` instead of the non-existent `mockGetToken`.

553-553: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 553, The failing
test reuses the same mockGetToken reference across test cases which causes value
bleed and unpredictable behavior; update the tests to either reset/replace
mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.

582-582: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue("existing-token");+ mockGetValidToken.mockResolvedValue("existing-token");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 582, The test is
reusing the same mock reference mockGetToken which causes cross-test leakage;
change the setup to create an isolated mock or set a one-time resolution so
other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/commands/init/heuristics.ts`:
- Around line 6-7: The isAuthenticated check currently relies on
getStoredSession()/getValidToken deserialization and can misclassify legacy
stored credentials; change isAuthenticated to perform a credential-presence
check instead (e.g., verify existence of any stored credential/token rather than
successful session deserialization). Update the logic in heuristics.ts where
isAuthenticated is implemented/used (referencing getStoredSession, getValidToken
and the isAuthenticated call) to detect presence of credentials in the store and
return true for legacy tokens, ensuring keyless init isn't incorrectly chosen;
keep existing validation flows for full session usage separate from this
presence check.
In `@packages/cli-core/src/lib/plapi.ts`:
- Around line 60-64: The API command tests are failing because getValidToken()
now throws an AuthError with reason "not_logged_in"; update the api command test
mocks in index.test.ts to either mock getValidToken() to throw an AuthError
instance with the same reason/message/docsUrl and assert that the command
surface handles/propagates that error, or change the mock to return a valid
token for tests that expect authenticated behavior; specifically adjust the mock
setup and assertions to reference AuthError and getValidToken() so the tests
reflect the new unauthenticated PLAPI path.
---
Outside diff comments:
In `@packages/cli-core/src/commands/auth/login.test.ts`:
- Line 521: The test references an undefined variable `mockGetToken`; replace
that usage with the correctly defined mock `mockGetValidToken` in the failing
test (the call at the line with mockGetToken.mockResolvedValue(null)) so the
test uses the existing mock variable `mockGetValidToken` instead of the
non-existent `mockGetToken`.
- Line 553: The failing test reuses the same mockGetToken reference across test
cases which causes value bleed and unpredictable behavior; update the tests to
either reset/replace mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.
- Line 582: The test is reusing the same mock reference mockGetToken which
causes cross-test leakage; change the setup to create an isolated mock or set a
one-time resolution so other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b17f3a36-f5cd-4db0-a653-43dfc0f9b368

📥 Commits

Reviewing files that changed from the base of the PR and between ef06e2c and b1ea0f7.

📒 Files selected for processing (18)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment threadpackages/cli-core/src/commands/init/heuristics.ts Outdated
Comment threadpackages/cli-core/src/lib/plapi.ts
@kylemac
kylemac requested a review from jfosheeApril 22, 2026 16:08
Align the implementation with the documented "pure credential-presence
check" intent. The previous code deserialized via getStoredSession() and
returned false for legacy raw-string credentials that don't match the
OAuthSession shape, incorrectly sending those users to the keyless init
flow.
@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch from 6009648 to 026c76cCompareApril 22, 2026 17:26

@rafa-thaytorafa-thayto 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.

LGTM

const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

If two parallel CLI calls hit getValidToken() while the token is expired, both will race into refreshStoredSession with the same refresh token. If the server rotates refresh tokens on use, the second call gets invalid_grant and nukes the credentials the first call just wrote.

Not likely in typical CLI usage, but could bite in CI scripts running clerk commands in parallel. A module-level promise guard would deduplicate:

Suggested change
}
letrefreshInFlight: Promise<string>|undefined;
asyncfunctionrefreshStoredSession(session: OAuthSession): Promise<string>{
if(refreshInFlight)returnrefreshInFlight;
refreshInFlight=doRefreshStoredSession(session).finally(()=>{
refreshInFlight=undefined;
});
returnrefreshInFlight;
}
asyncfunctiondoRefreshStoredSession(session: OAuthSession): Promise<string>{

Non-blocking, happy to merge as-is and handle this as a follow-up.

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

I got a version that's resilient to this change when more than one cli is operating at once. Don't think we needed the in-process protections as much as the cross-process ones.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/lib/credential-store.ts`:
- Around line 324-340: getValidToken treats any non-JSON legacy stored value as
an expired session because getStoredSession only handles the new JSON shape; to
fix this, update the flow to accept legacy raw tokens: in getStoredSession (or
in parseStoredSession) detect if readStoredValue() returns a plain string
(legacy raw token) and return an OAuthSession-like object (or at least an object
with accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2b91a154-39a2-4ecc-9516-cdbcd12329a3

📥 Commits

Reviewing files that changed from the base of the PR and between 6009648 and 026c76c.

📒 Files selected for processing (21)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/api/index.test.ts
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/lib/credential-store.test.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/api/index.test.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment on lines +324 to +340
export async function getStoredSession(): Promise<OAuthSession | null> {
const value = await readStoredValue();
if (!value) return null;
return parseStoredSession(value);
}

return fileGet();
export async function hasStoredCredentials(): Promise<boolean> {
return (await readStoredValue()) !== null;
}

export async function getValidToken(): Promise<string | null> {
const session = await getStoredSession();
if (!session) {
if (await hasStoredCredentials()) {
throw sessionExpiredError();
}
return null;

@coderabbitaicoderabbitaiBotApr 22, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Legacy raw credentials are treated as expired immediately.

getStoredSession() only recognizes the new JSON shape, so any pre-upgrade raw access token falls into this branch and becomes session_expired. Since authenticated commands now go through getValidToken(), upgrading will force every previously logged-in user to re-authenticate even when their stored token is still valid.

Suggested fix
 export async function getValidToken(): Promise<string | null> {
- const session = await getStoredSession();- if (!session) {- if (await hasStoredCredentials()) {- throw sessionExpiredError();- }- return null;- }+ const value = await readStoredValue();+ if (!value) return null;++ const session = parseStoredSession(value);+ if (!session) {+ const expiresAt = getJwtExpiryMs(value);+ if (expiresAt !== null && expiresAt <= Date.now() + JWT_EXPIRY_LEEWAY_MS) {+ throw sessionExpiredError();+ }+ return value;+ }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/lib/credential-store.ts` around lines 324 - 340,
getValidToken treats any non-JSON legacy stored value as an expired session
because getStoredSession only handles the new JSON shape; to fix this, update
the flow to accept legacy raw tokens: in getStoredSession (or in
parseStoredSession) detect if readStoredValue() returns a plain string (legacy
raw token) and return an OAuthSession-like object (or at least an object with
accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This is intentional

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@wyattjoh, understood — forcing a one-time re-authentication for users with a legacy raw token on upgrade is an intentional migration cut-over. I'll note this for future reviews.


✏️ Learnings added
Learnt from: wyattjoh
Repo: clerk/cli PR: 205
File: packages/cli-core/src/lib/credential-store.ts:324-340
Timestamp: 2026-04-22T17:39:54.554Z
Learning: In clerk/cli credential-store (`packages/cli-core/src/lib/credential-store.ts`), `getValidToken()` intentionally treats any stored credential that cannot be parsed as a valid `OAuthSession` JSON (i.e. a legacy raw access token string) as a `session_expired` error, forcing a one-time re-authentication on upgrade. Do not flag this as a bug — it is a deliberate migration design decision by the author.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: wyattjoh
Repo: clerk/cli PR: 118
File: packages/cli-core/src/commands/init/skills.ts:117-124
Timestamp: 2026-04-07T22:06:40.516Z
Learning: In clerk/cli, cancellation from inquirer/prompts (e.g., Ctrl+C resulting in UserAbortError / ExitPromptError) is handled globally in cli-program.ts (around the existing global catch). Therefore, command-level prompt call sites (e.g., confirm(), select()) in packages/cli-core/src should not wrap these prompt calls in local try/catch for UserAbortError/ExitPromptError cancellations—such local handling would be dead code and should remain consistent with the shared cancellation behavior.

Learnt from: wyattjoh
Repo: clerk/cli PR: 153
File: .claude/rules/scripts.md:36-36
Timestamp: 2026-04-13T23:09:41.178Z
Learning: In the clerk/cli repository, do not treat `Bun.$` (Bun Shell API) as experimental/unstable during code review. `Bun.$` is a stable, documented core Bun runtime feature (similar in status to `Bun.spawn` and `Bun.file`), so reviewers should not raise warnings that it relies on experimental APIs.

@jfosheejfoshee 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.

Some initial comments. I am still reviewing. :-)

Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
Comment threadpackages/cli-core/src/lib/credential-store.ts
Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

@wyattjoh
wyattjoh requested a review from jfosheeApril 22, 2026 18:05

@jfosheejfoshee 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.

Looks good. I did a manual test locally w/ a 5 min access token. Worked fine. It would just be nice to see something in the trace log that it was doing a refresh.

Another nice-to-have would be a manual refresh? like clerk auth refresh? wdyt? could be an internal only testing command.

async function refreshStoredSession(session: OAuthSession): Promise<string> {
let tokenResponse: TokenResponse;
try {
tokenResponse = await refreshAccessToken(session.refreshToken);

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.

I would like to see in the debug trace that we are doing a refresh. Is this the place to log it?

@wyattjoh
wyattjoh merged commit 23a3089 into mainApr 22, 2026
10 checks passed
@wyattjoh
wyattjoh deleted the wyattjoh/oauth-refresh-token-support branch April 22, 2026 18:39
@github-actionsgithub-actionsBot mentioned this pull request Apr 22, 2026
Sign up for freeto 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.

3 participants

@wyattjoh@jfoshee@rafa-thayto
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(auth): add OAuth refresh token session handling - #205

Merged
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support
Apr 22, 2026
Merged

feat(auth): add OAuth refresh token session handling#205
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support

Conversation

@wyattjoh

@wyattjohwyattjoh commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Summary

OAuth access tokens issued to the CLI are now short-lived JWTs. The credential store previously persisted only the raw access token, so once the token's exp passed every authenticated command failed with a 401 and forced the user back through clerk auth login. This change persists the full OAuth session, refreshes the access token transparently from the stored refresh token, and routes every auth failure through a single typed error so downstream code can react without string-matching.

What changed

  • Credential store now holds a session, not a bare token.storeToken accepts either a legacy access-token string or an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and persists it as JSON to the same keyring/file slot. getToken() stays backwards-compatible for readers that only want the string, so a session written by an older build is still readable.
  • New getValidToken() decodes the access-token JWT exp, and if it is within a 30s leeway of expiry calls the OAuth token endpoint with the stored refresh token, writes the new session back, and returns the fresh access token. invalid_grant responses wipe the stored session and raise AUTH_REQUIRED so the user is told to re-login rather than hitting a silent 401 loop.
  • All authenticated call sites route through getValidToken(): login, whoami, plapi requests, init heuristics, and every doctor check that needs a live session. Presence-only probes (is the user logged in at all?) use the new hasStoredCredentials() so we don't refresh as a side effect of non-auth flows.
  • Doctor validates the refresh path. The auth-related checks now pull the session through getValidToken() so clerk doctor surfaces refresh failures (expired refresh token, server-side revoke) the same way it surfaces other auth breakage, instead of reporting a healthy session while the next real call 401s.
  • Centralized auth error handling. New AuthError subclass of CliError carries a reason discriminator (not_logged_in / session_expired) with default per-reason messages, always codes to AUTH_REQUIRED, and replaces the hand-rolled CliError throws in whoami, plapi.getAuthToken, and credential-store. Doctor's token check now uses a new isAuthError() type guard covering both AuthError and ApiError(401|403) instead of regex-matching (401|403) substrings in error messages, so message-copy changes can't silently break the check.

Test plan

  • bun run format:check, bun run lint, bun run typecheck, bun run test
  • Unit coverage for getValidToken(): valid JWT returns unchanged, near-expiry JWT triggers a refresh and rewrites the session, invalid_grant clears credentials and throws AUTH_REQUIRED.
  • Doctor test covers the refresh-failure path by injecting an AuthError({ reason: "session_expired" }) into getValidToken() and asserting the check fails with the re-login remedy.
  • Manual: log in, force the access token past exp, run clerk whoami and confirm a refresh request fires and the session is rewritten transparently.
  • Manual: revoke the refresh token server-side, rerun a command, confirm the CLI reports session expired and clears the stored credentials.
  • Full E2E CI run on the PR.

@changeset-bot

changeset-botBot commented Apr 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9991c0c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
clerkMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch 2 times, most recently from dbb4068 to b1ea0f7CompareApril 22, 2026 15:36
@wyattjoh
wyattjoh marked this pull request as ready for review April 22, 2026 15:37
@coderabbitai

coderabbitaiBot commented Apr 22, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds OAuth refresh-token support across the CLI: credential storage now persists an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and exposes createOAuthSession, getStoredSession, hasStoredCredentials, and getValidToken. getValidToken validates expiry and attempts refresh via refreshAccessToken, deleting credentials and throwing AuthError(reason: "session_expired") on invalid_grant. Introduces AuthError and isAuthError. Commands and doctor/init/whoami/plapi call getValidToken instead of getToken. Tests and mocks updated to exercise session persistence and refresh flows; token-exchange gains refreshAccessToken.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 6.98% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Title check✅ PassedThe title accurately describes the main change: adding OAuth refresh token session handling to automatically refresh expired access tokens.
Description check✅ PassedThe description comprehensively explains the OAuth refresh token feature, the problem it solves, implementation details, affected call sites, and test coverage.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

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


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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/cli-core/src/commands/auth/login.test.ts (3)

521-521: ⚠️ Potential issue | 🔴 Critical

Build failure: mockGetToken is undefined.

The pipeline reports TS2304: Cannot find name 'mockGetToken'. This should be mockGetValidToken to match the mock defined at line 7.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 521, The test
references an undefined variable `mockGetToken`; replace that usage with the
correctly defined mock `mockGetValidToken` in the failing test (the call at the
line with mockGetToken.mockResolvedValue(null)) so the test uses the existing
mock variable `mockGetValidToken` instead of the non-existent `mockGetToken`.

553-553: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 553, The failing
test reuses the same mockGetToken reference across test cases which causes value
bleed and unpredictable behavior; update the tests to either reset/replace
mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.

582-582: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue("existing-token");+ mockGetValidToken.mockResolvedValue("existing-token");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 582, The test is
reusing the same mock reference mockGetToken which causes cross-test leakage;
change the setup to create an isolated mock or set a one-time resolution so
other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/commands/init/heuristics.ts`:
- Around line 6-7: The isAuthenticated check currently relies on
getStoredSession()/getValidToken deserialization and can misclassify legacy
stored credentials; change isAuthenticated to perform a credential-presence
check instead (e.g., verify existence of any stored credential/token rather than
successful session deserialization). Update the logic in heuristics.ts where
isAuthenticated is implemented/used (referencing getStoredSession, getValidToken
and the isAuthenticated call) to detect presence of credentials in the store and
return true for legacy tokens, ensuring keyless init isn't incorrectly chosen;
keep existing validation flows for full session usage separate from this
presence check.
In `@packages/cli-core/src/lib/plapi.ts`:
- Around line 60-64: The API command tests are failing because getValidToken()
now throws an AuthError with reason "not_logged_in"; update the api command test
mocks in index.test.ts to either mock getValidToken() to throw an AuthError
instance with the same reason/message/docsUrl and assert that the command
surface handles/propagates that error, or change the mock to return a valid
token for tests that expect authenticated behavior; specifically adjust the mock
setup and assertions to reference AuthError and getValidToken() so the tests
reflect the new unauthenticated PLAPI path.
---
Outside diff comments:
In `@packages/cli-core/src/commands/auth/login.test.ts`:
- Line 521: The test references an undefined variable `mockGetToken`; replace
that usage with the correctly defined mock `mockGetValidToken` in the failing
test (the call at the line with mockGetToken.mockResolvedValue(null)) so the
test uses the existing mock variable `mockGetValidToken` instead of the
non-existent `mockGetToken`.
- Line 553: The failing test reuses the same mockGetToken reference across test
cases which causes value bleed and unpredictable behavior; update the tests to
either reset/replace mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.
- Line 582: The test is reusing the same mock reference mockGetToken which
causes cross-test leakage; change the setup to create an isolated mock or set a
one-time resolution so other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b17f3a36-f5cd-4db0-a653-43dfc0f9b368

📥 Commits

Reviewing files that changed from the base of the PR and between ef06e2c and b1ea0f7.

📒 Files selected for processing (18)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment threadpackages/cli-core/src/commands/init/heuristics.ts Outdated
Comment threadpackages/cli-core/src/lib/plapi.ts
@kylemac
kylemac requested a review from jfosheeApril 22, 2026 16:08
Align the implementation with the documented "pure credential-presence
check" intent. The previous code deserialized via getStoredSession() and
returned false for legacy raw-string credentials that don't match the
OAuthSession shape, incorrectly sending those users to the keyless init
flow.
@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch from 6009648 to 026c76cCompareApril 22, 2026 17:26

@rafa-thaytorafa-thayto 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.

LGTM

const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

If two parallel CLI calls hit getValidToken() while the token is expired, both will race into refreshStoredSession with the same refresh token. If the server rotates refresh tokens on use, the second call gets invalid_grant and nukes the credentials the first call just wrote.

Not likely in typical CLI usage, but could bite in CI scripts running clerk commands in parallel. A module-level promise guard would deduplicate:

Suggested change
}
letrefreshInFlight: Promise<string>|undefined;
asyncfunctionrefreshStoredSession(session: OAuthSession): Promise<string>{
if(refreshInFlight)returnrefreshInFlight;
refreshInFlight=doRefreshStoredSession(session).finally(()=>{
refreshInFlight=undefined;
});
returnrefreshInFlight;
}
asyncfunctiondoRefreshStoredSession(session: OAuthSession): Promise<string>{

Non-blocking, happy to merge as-is and handle this as a follow-up.

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

I got a version that's resilient to this change when more than one cli is operating at once. Don't think we needed the in-process protections as much as the cross-process ones.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/lib/credential-store.ts`:
- Around line 324-340: getValidToken treats any non-JSON legacy stored value as
an expired session because getStoredSession only handles the new JSON shape; to
fix this, update the flow to accept legacy raw tokens: in getStoredSession (or
in parseStoredSession) detect if readStoredValue() returns a plain string
(legacy raw token) and return an OAuthSession-like object (or at least an object
with accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2b91a154-39a2-4ecc-9516-cdbcd12329a3

📥 Commits

Reviewing files that changed from the base of the PR and between 6009648 and 026c76c.

📒 Files selected for processing (21)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/api/index.test.ts
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/lib/credential-store.test.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/api/index.test.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment on lines +324 to +340
export async function getStoredSession(): Promise<OAuthSession | null> {
const value = await readStoredValue();
if (!value) return null;
return parseStoredSession(value);
}

return fileGet();
export async function hasStoredCredentials(): Promise<boolean> {
return (await readStoredValue()) !== null;
}

export async function getValidToken(): Promise<string | null> {
const session = await getStoredSession();
if (!session) {
if (await hasStoredCredentials()) {
throw sessionExpiredError();
}
return null;

@coderabbitaicoderabbitaiBotApr 22, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Legacy raw credentials are treated as expired immediately.

getStoredSession() only recognizes the new JSON shape, so any pre-upgrade raw access token falls into this branch and becomes session_expired. Since authenticated commands now go through getValidToken(), upgrading will force every previously logged-in user to re-authenticate even when their stored token is still valid.

Suggested fix
 export async function getValidToken(): Promise<string | null> {
- const session = await getStoredSession();- if (!session) {- if (await hasStoredCredentials()) {- throw sessionExpiredError();- }- return null;- }+ const value = await readStoredValue();+ if (!value) return null;++ const session = parseStoredSession(value);+ if (!session) {+ const expiresAt = getJwtExpiryMs(value);+ if (expiresAt !== null && expiresAt <= Date.now() + JWT_EXPIRY_LEEWAY_MS) {+ throw sessionExpiredError();+ }+ return value;+ }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/lib/credential-store.ts` around lines 324 - 340,
getValidToken treats any non-JSON legacy stored value as an expired session
because getStoredSession only handles the new JSON shape; to fix this, update
the flow to accept legacy raw tokens: in getStoredSession (or in
parseStoredSession) detect if readStoredValue() returns a plain string (legacy
raw token) and return an OAuthSession-like object (or at least an object with
accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This is intentional

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@wyattjoh, understood — forcing a one-time re-authentication for users with a legacy raw token on upgrade is an intentional migration cut-over. I'll note this for future reviews.


✏️ Learnings added
Learnt from: wyattjoh
Repo: clerk/cli PR: 205
File: packages/cli-core/src/lib/credential-store.ts:324-340
Timestamp: 2026-04-22T17:39:54.554Z
Learning: In clerk/cli credential-store (`packages/cli-core/src/lib/credential-store.ts`), `getValidToken()` intentionally treats any stored credential that cannot be parsed as a valid `OAuthSession` JSON (i.e. a legacy raw access token string) as a `session_expired` error, forcing a one-time re-authentication on upgrade. Do not flag this as a bug — it is a deliberate migration design decision by the author.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: wyattjoh
Repo: clerk/cli PR: 118
File: packages/cli-core/src/commands/init/skills.ts:117-124
Timestamp: 2026-04-07T22:06:40.516Z
Learning: In clerk/cli, cancellation from inquirer/prompts (e.g., Ctrl+C resulting in UserAbortError / ExitPromptError) is handled globally in cli-program.ts (around the existing global catch). Therefore, command-level prompt call sites (e.g., confirm(), select()) in packages/cli-core/src should not wrap these prompt calls in local try/catch for UserAbortError/ExitPromptError cancellations—such local handling would be dead code and should remain consistent with the shared cancellation behavior.

Learnt from: wyattjoh
Repo: clerk/cli PR: 153
File: .claude/rules/scripts.md:36-36
Timestamp: 2026-04-13T23:09:41.178Z
Learning: In the clerk/cli repository, do not treat `Bun.$` (Bun Shell API) as experimental/unstable during code review. `Bun.$` is a stable, documented core Bun runtime feature (similar in status to `Bun.spawn` and `Bun.file`), so reviewers should not raise warnings that it relies on experimental APIs.

@jfosheejfoshee 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.

Some initial comments. I am still reviewing. :-)

Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
Comment threadpackages/cli-core/src/lib/credential-store.ts
Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

@wyattjoh
wyattjoh requested a review from jfosheeApril 22, 2026 18:05

@jfosheejfoshee 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.

Looks good. I did a manual test locally w/ a 5 min access token. Worked fine. It would just be nice to see something in the trace log that it was doing a refresh.

Another nice-to-have would be a manual refresh? like clerk auth refresh? wdyt? could be an internal only testing command.

async function refreshStoredSession(session: OAuthSession): Promise<string> {
let tokenResponse: TokenResponse;
try {
tokenResponse = await refreshAccessToken(session.refreshToken);

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.

I would like to see in the debug trace that we are doing a refresh. Is this the place to log it?

@wyattjoh
wyattjoh merged commit 23a3089 into mainApr 22, 2026
10 checks passed
@wyattjoh
wyattjoh deleted the wyattjoh/oauth-refresh-token-support branch April 22, 2026 18:39
@github-actionsgithub-actionsBot mentioned this pull request Apr 22, 2026
Sign up for freeto 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.

3 participants

@wyattjoh@jfoshee@rafa-thayto
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

feat(auth): add OAuth refresh token session handling - #205

Merged
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support
Apr 22, 2026
Merged

feat(auth): add OAuth refresh token session handling#205
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support

Conversation

@wyattjoh

@wyattjohwyattjoh commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Summary

OAuth access tokens issued to the CLI are now short-lived JWTs. The credential store previously persisted only the raw access token, so once the token's exp passed every authenticated command failed with a 401 and forced the user back through clerk auth login. This change persists the full OAuth session, refreshes the access token transparently from the stored refresh token, and routes every auth failure through a single typed error so downstream code can react without string-matching.

What changed

  • Credential store now holds a session, not a bare token.storeToken accepts either a legacy access-token string or an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and persists it as JSON to the same keyring/file slot. getToken() stays backwards-compatible for readers that only want the string, so a session written by an older build is still readable.
  • New getValidToken() decodes the access-token JWT exp, and if it is within a 30s leeway of expiry calls the OAuth token endpoint with the stored refresh token, writes the new session back, and returns the fresh access token. invalid_grant responses wipe the stored session and raise AUTH_REQUIRED so the user is told to re-login rather than hitting a silent 401 loop.
  • All authenticated call sites route through getValidToken(): login, whoami, plapi requests, init heuristics, and every doctor check that needs a live session. Presence-only probes (is the user logged in at all?) use the new hasStoredCredentials() so we don't refresh as a side effect of non-auth flows.
  • Doctor validates the refresh path. The auth-related checks now pull the session through getValidToken() so clerk doctor surfaces refresh failures (expired refresh token, server-side revoke) the same way it surfaces other auth breakage, instead of reporting a healthy session while the next real call 401s.
  • Centralized auth error handling. New AuthError subclass of CliError carries a reason discriminator (not_logged_in / session_expired) with default per-reason messages, always codes to AUTH_REQUIRED, and replaces the hand-rolled CliError throws in whoami, plapi.getAuthToken, and credential-store. Doctor's token check now uses a new isAuthError() type guard covering both AuthError and ApiError(401|403) instead of regex-matching (401|403) substrings in error messages, so message-copy changes can't silently break the check.

Test plan

  • bun run format:check, bun run lint, bun run typecheck, bun run test
  • Unit coverage for getValidToken(): valid JWT returns unchanged, near-expiry JWT triggers a refresh and rewrites the session, invalid_grant clears credentials and throws AUTH_REQUIRED.
  • Doctor test covers the refresh-failure path by injecting an AuthError({ reason: "session_expired" }) into getValidToken() and asserting the check fails with the re-login remedy.
  • Manual: log in, force the access token past exp, run clerk whoami and confirm a refresh request fires and the session is rewritten transparently.
  • Manual: revoke the refresh token server-side, rerun a command, confirm the CLI reports session expired and clears the stored credentials.
  • Full E2E CI run on the PR.

@changeset-bot

changeset-botBot commented Apr 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9991c0c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
clerkMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch 2 times, most recently from dbb4068 to b1ea0f7CompareApril 22, 2026 15:36
@wyattjoh
wyattjoh marked this pull request as ready for review April 22, 2026 15:37
@coderabbitai

coderabbitaiBot commented Apr 22, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds OAuth refresh-token support across the CLI: credential storage now persists an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and exposes createOAuthSession, getStoredSession, hasStoredCredentials, and getValidToken. getValidToken validates expiry and attempts refresh via refreshAccessToken, deleting credentials and throwing AuthError(reason: "session_expired") on invalid_grant. Introduces AuthError and isAuthError. Commands and doctor/init/whoami/plapi call getValidToken instead of getToken. Tests and mocks updated to exercise session persistence and refresh flows; token-exchange gains refreshAccessToken.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 6.98% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Title check✅ PassedThe title accurately describes the main change: adding OAuth refresh token session handling to automatically refresh expired access tokens.
Description check✅ PassedThe description comprehensively explains the OAuth refresh token feature, the problem it solves, implementation details, affected call sites, and test coverage.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

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


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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/cli-core/src/commands/auth/login.test.ts (3)

521-521: ⚠️ Potential issue | 🔴 Critical

Build failure: mockGetToken is undefined.

The pipeline reports TS2304: Cannot find name 'mockGetToken'. This should be mockGetValidToken to match the mock defined at line 7.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 521, The test
references an undefined variable `mockGetToken`; replace that usage with the
correctly defined mock `mockGetValidToken` in the failing test (the call at the
line with mockGetToken.mockResolvedValue(null)) so the test uses the existing
mock variable `mockGetValidToken` instead of the non-existent `mockGetToken`.

553-553: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 553, The failing
test reuses the same mockGetToken reference across test cases which causes value
bleed and unpredictable behavior; update the tests to either reset/replace
mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.

582-582: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue("existing-token");+ mockGetValidToken.mockResolvedValue("existing-token");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 582, The test is
reusing the same mock reference mockGetToken which causes cross-test leakage;
change the setup to create an isolated mock or set a one-time resolution so
other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/commands/init/heuristics.ts`:
- Around line 6-7: The isAuthenticated check currently relies on
getStoredSession()/getValidToken deserialization and can misclassify legacy
stored credentials; change isAuthenticated to perform a credential-presence
check instead (e.g., verify existence of any stored credential/token rather than
successful session deserialization). Update the logic in heuristics.ts where
isAuthenticated is implemented/used (referencing getStoredSession, getValidToken
and the isAuthenticated call) to detect presence of credentials in the store and
return true for legacy tokens, ensuring keyless init isn't incorrectly chosen;
keep existing validation flows for full session usage separate from this
presence check.
In `@packages/cli-core/src/lib/plapi.ts`:
- Around line 60-64: The API command tests are failing because getValidToken()
now throws an AuthError with reason "not_logged_in"; update the api command test
mocks in index.test.ts to either mock getValidToken() to throw an AuthError
instance with the same reason/message/docsUrl and assert that the command
surface handles/propagates that error, or change the mock to return a valid
token for tests that expect authenticated behavior; specifically adjust the mock
setup and assertions to reference AuthError and getValidToken() so the tests
reflect the new unauthenticated PLAPI path.
---
Outside diff comments:
In `@packages/cli-core/src/commands/auth/login.test.ts`:
- Line 521: The test references an undefined variable `mockGetToken`; replace
that usage with the correctly defined mock `mockGetValidToken` in the failing
test (the call at the line with mockGetToken.mockResolvedValue(null)) so the
test uses the existing mock variable `mockGetValidToken` instead of the
non-existent `mockGetToken`.
- Line 553: The failing test reuses the same mockGetToken reference across test
cases which causes value bleed and unpredictable behavior; update the tests to
either reset/replace mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.
- Line 582: The test is reusing the same mock reference mockGetToken which
causes cross-test leakage; change the setup to create an isolated mock or set a
one-time resolution so other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b17f3a36-f5cd-4db0-a653-43dfc0f9b368

📥 Commits

Reviewing files that changed from the base of the PR and between ef06e2c and b1ea0f7.

📒 Files selected for processing (18)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment threadpackages/cli-core/src/commands/init/heuristics.ts Outdated
Comment threadpackages/cli-core/src/lib/plapi.ts
@kylemac
kylemac requested a review from jfosheeApril 22, 2026 16:08
Align the implementation with the documented "pure credential-presence
check" intent. The previous code deserialized via getStoredSession() and
returned false for legacy raw-string credentials that don't match the
OAuthSession shape, incorrectly sending those users to the keyless init
flow.
@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch from 6009648 to 026c76cCompareApril 22, 2026 17:26

@rafa-thaytorafa-thayto 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.

LGTM

const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

If two parallel CLI calls hit getValidToken() while the token is expired, both will race into refreshStoredSession with the same refresh token. If the server rotates refresh tokens on use, the second call gets invalid_grant and nukes the credentials the first call just wrote.

Not likely in typical CLI usage, but could bite in CI scripts running clerk commands in parallel. A module-level promise guard would deduplicate:

Suggested change
}
letrefreshInFlight: Promise<string>|undefined;
asyncfunctionrefreshStoredSession(session: OAuthSession): Promise<string>{
if(refreshInFlight)returnrefreshInFlight;
refreshInFlight=doRefreshStoredSession(session).finally(()=>{
refreshInFlight=undefined;
});
returnrefreshInFlight;
}
asyncfunctiondoRefreshStoredSession(session: OAuthSession): Promise<string>{

Non-blocking, happy to merge as-is and handle this as a follow-up.

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

I got a version that's resilient to this change when more than one cli is operating at once. Don't think we needed the in-process protections as much as the cross-process ones.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/lib/credential-store.ts`:
- Around line 324-340: getValidToken treats any non-JSON legacy stored value as
an expired session because getStoredSession only handles the new JSON shape; to
fix this, update the flow to accept legacy raw tokens: in getStoredSession (or
in parseStoredSession) detect if readStoredValue() returns a plain string
(legacy raw token) and return an OAuthSession-like object (or at least an object
with accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2b91a154-39a2-4ecc-9516-cdbcd12329a3

📥 Commits

Reviewing files that changed from the base of the PR and between 6009648 and 026c76c.

📒 Files selected for processing (21)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/api/index.test.ts
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/lib/credential-store.test.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/api/index.test.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment on lines +324 to +340
export async function getStoredSession(): Promise<OAuthSession | null> {
const value = await readStoredValue();
if (!value) return null;
return parseStoredSession(value);
}

return fileGet();
export async function hasStoredCredentials(): Promise<boolean> {
return (await readStoredValue()) !== null;
}

export async function getValidToken(): Promise<string | null> {
const session = await getStoredSession();
if (!session) {
if (await hasStoredCredentials()) {
throw sessionExpiredError();
}
return null;

@coderabbitaicoderabbitaiBotApr 22, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Legacy raw credentials are treated as expired immediately.

getStoredSession() only recognizes the new JSON shape, so any pre-upgrade raw access token falls into this branch and becomes session_expired. Since authenticated commands now go through getValidToken(), upgrading will force every previously logged-in user to re-authenticate even when their stored token is still valid.

Suggested fix
 export async function getValidToken(): Promise<string | null> {
- const session = await getStoredSession();- if (!session) {- if (await hasStoredCredentials()) {- throw sessionExpiredError();- }- return null;- }+ const value = await readStoredValue();+ if (!value) return null;++ const session = parseStoredSession(value);+ if (!session) {+ const expiresAt = getJwtExpiryMs(value);+ if (expiresAt !== null && expiresAt <= Date.now() + JWT_EXPIRY_LEEWAY_MS) {+ throw sessionExpiredError();+ }+ return value;+ }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/lib/credential-store.ts` around lines 324 - 340,
getValidToken treats any non-JSON legacy stored value as an expired session
because getStoredSession only handles the new JSON shape; to fix this, update
the flow to accept legacy raw tokens: in getStoredSession (or in
parseStoredSession) detect if readStoredValue() returns a plain string (legacy
raw token) and return an OAuthSession-like object (or at least an object with
accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This is intentional

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@wyattjoh, understood — forcing a one-time re-authentication for users with a legacy raw token on upgrade is an intentional migration cut-over. I'll note this for future reviews.


✏️ Learnings added
Learnt from: wyattjoh
Repo: clerk/cli PR: 205
File: packages/cli-core/src/lib/credential-store.ts:324-340
Timestamp: 2026-04-22T17:39:54.554Z
Learning: In clerk/cli credential-store (`packages/cli-core/src/lib/credential-store.ts`), `getValidToken()` intentionally treats any stored credential that cannot be parsed as a valid `OAuthSession` JSON (i.e. a legacy raw access token string) as a `session_expired` error, forcing a one-time re-authentication on upgrade. Do not flag this as a bug — it is a deliberate migration design decision by the author.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: wyattjoh
Repo: clerk/cli PR: 118
File: packages/cli-core/src/commands/init/skills.ts:117-124
Timestamp: 2026-04-07T22:06:40.516Z
Learning: In clerk/cli, cancellation from inquirer/prompts (e.g., Ctrl+C resulting in UserAbortError / ExitPromptError) is handled globally in cli-program.ts (around the existing global catch). Therefore, command-level prompt call sites (e.g., confirm(), select()) in packages/cli-core/src should not wrap these prompt calls in local try/catch for UserAbortError/ExitPromptError cancellations—such local handling would be dead code and should remain consistent with the shared cancellation behavior.

Learnt from: wyattjoh
Repo: clerk/cli PR: 153
File: .claude/rules/scripts.md:36-36
Timestamp: 2026-04-13T23:09:41.178Z
Learning: In the clerk/cli repository, do not treat `Bun.$` (Bun Shell API) as experimental/unstable during code review. `Bun.$` is a stable, documented core Bun runtime feature (similar in status to `Bun.spawn` and `Bun.file`), so reviewers should not raise warnings that it relies on experimental APIs.

@jfosheejfoshee 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.

Some initial comments. I am still reviewing. :-)

Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
Comment threadpackages/cli-core/src/lib/credential-store.ts
Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

@wyattjoh
wyattjoh requested a review from jfosheeApril 22, 2026 18:05

@jfosheejfoshee 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.

Looks good. I did a manual test locally w/ a 5 min access token. Worked fine. It would just be nice to see something in the trace log that it was doing a refresh.

Another nice-to-have would be a manual refresh? like clerk auth refresh? wdyt? could be an internal only testing command.

async function refreshStoredSession(session: OAuthSession): Promise<string> {
let tokenResponse: TokenResponse;
try {
tokenResponse = await refreshAccessToken(session.refreshToken);

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.

I would like to see in the debug trace that we are doing a refresh. Is this the place to log it?

@wyattjoh
wyattjoh merged commit 23a3089 into mainApr 22, 2026
10 checks passed
@wyattjoh
wyattjoh deleted the wyattjoh/oauth-refresh-token-support branch April 22, 2026 18:39
@github-actionsgithub-actionsBot mentioned this pull request Apr 22, 2026
Sign up for freeto 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.

3 participants

@wyattjoh@jfoshee@rafa-thayto
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(auth): add OAuth refresh token session handling - #205

Merged
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support
Apr 22, 2026
Merged

feat(auth): add OAuth refresh token session handling#205
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support

Conversation

@wyattjoh

@wyattjohwyattjoh commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Summary

OAuth access tokens issued to the CLI are now short-lived JWTs. The credential store previously persisted only the raw access token, so once the token's exp passed every authenticated command failed with a 401 and forced the user back through clerk auth login. This change persists the full OAuth session, refreshes the access token transparently from the stored refresh token, and routes every auth failure through a single typed error so downstream code can react without string-matching.

What changed

  • Credential store now holds a session, not a bare token.storeToken accepts either a legacy access-token string or an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and persists it as JSON to the same keyring/file slot. getToken() stays backwards-compatible for readers that only want the string, so a session written by an older build is still readable.
  • New getValidToken() decodes the access-token JWT exp, and if it is within a 30s leeway of expiry calls the OAuth token endpoint with the stored refresh token, writes the new session back, and returns the fresh access token. invalid_grant responses wipe the stored session and raise AUTH_REQUIRED so the user is told to re-login rather than hitting a silent 401 loop.
  • All authenticated call sites route through getValidToken(): login, whoami, plapi requests, init heuristics, and every doctor check that needs a live session. Presence-only probes (is the user logged in at all?) use the new hasStoredCredentials() so we don't refresh as a side effect of non-auth flows.
  • Doctor validates the refresh path. The auth-related checks now pull the session through getValidToken() so clerk doctor surfaces refresh failures (expired refresh token, server-side revoke) the same way it surfaces other auth breakage, instead of reporting a healthy session while the next real call 401s.
  • Centralized auth error handling. New AuthError subclass of CliError carries a reason discriminator (not_logged_in / session_expired) with default per-reason messages, always codes to AUTH_REQUIRED, and replaces the hand-rolled CliError throws in whoami, plapi.getAuthToken, and credential-store. Doctor's token check now uses a new isAuthError() type guard covering both AuthError and ApiError(401|403) instead of regex-matching (401|403) substrings in error messages, so message-copy changes can't silently break the check.

Test plan

  • bun run format:check, bun run lint, bun run typecheck, bun run test
  • Unit coverage for getValidToken(): valid JWT returns unchanged, near-expiry JWT triggers a refresh and rewrites the session, invalid_grant clears credentials and throws AUTH_REQUIRED.
  • Doctor test covers the refresh-failure path by injecting an AuthError({ reason: "session_expired" }) into getValidToken() and asserting the check fails with the re-login remedy.
  • Manual: log in, force the access token past exp, run clerk whoami and confirm a refresh request fires and the session is rewritten transparently.
  • Manual: revoke the refresh token server-side, rerun a command, confirm the CLI reports session expired and clears the stored credentials.
  • Full E2E CI run on the PR.

@changeset-bot

changeset-botBot commented Apr 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9991c0c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
clerkMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch 2 times, most recently from dbb4068 to b1ea0f7CompareApril 22, 2026 15:36
@wyattjoh
wyattjoh marked this pull request as ready for review April 22, 2026 15:37
@coderabbitai

coderabbitaiBot commented Apr 22, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds OAuth refresh-token support across the CLI: credential storage now persists an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and exposes createOAuthSession, getStoredSession, hasStoredCredentials, and getValidToken. getValidToken validates expiry and attempts refresh via refreshAccessToken, deleting credentials and throwing AuthError(reason: "session_expired") on invalid_grant. Introduces AuthError and isAuthError. Commands and doctor/init/whoami/plapi call getValidToken instead of getToken. Tests and mocks updated to exercise session persistence and refresh flows; token-exchange gains refreshAccessToken.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 6.98% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Title check✅ PassedThe title accurately describes the main change: adding OAuth refresh token session handling to automatically refresh expired access tokens.
Description check✅ PassedThe description comprehensively explains the OAuth refresh token feature, the problem it solves, implementation details, affected call sites, and test coverage.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

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


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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/cli-core/src/commands/auth/login.test.ts (3)

521-521: ⚠️ Potential issue | 🔴 Critical

Build failure: mockGetToken is undefined.

The pipeline reports TS2304: Cannot find name 'mockGetToken'. This should be mockGetValidToken to match the mock defined at line 7.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 521, The test
references an undefined variable `mockGetToken`; replace that usage with the
correctly defined mock `mockGetValidToken` in the failing test (the call at the
line with mockGetToken.mockResolvedValue(null)) so the test uses the existing
mock variable `mockGetValidToken` instead of the non-existent `mockGetToken`.

553-553: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 553, The failing
test reuses the same mockGetToken reference across test cases which causes value
bleed and unpredictable behavior; update the tests to either reset/replace
mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.

582-582: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue("existing-token");+ mockGetValidToken.mockResolvedValue("existing-token");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 582, The test is
reusing the same mock reference mockGetToken which causes cross-test leakage;
change the setup to create an isolated mock or set a one-time resolution so
other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/commands/init/heuristics.ts`:
- Around line 6-7: The isAuthenticated check currently relies on
getStoredSession()/getValidToken deserialization and can misclassify legacy
stored credentials; change isAuthenticated to perform a credential-presence
check instead (e.g., verify existence of any stored credential/token rather than
successful session deserialization). Update the logic in heuristics.ts where
isAuthenticated is implemented/used (referencing getStoredSession, getValidToken
and the isAuthenticated call) to detect presence of credentials in the store and
return true for legacy tokens, ensuring keyless init isn't incorrectly chosen;
keep existing validation flows for full session usage separate from this
presence check.
In `@packages/cli-core/src/lib/plapi.ts`:
- Around line 60-64: The API command tests are failing because getValidToken()
now throws an AuthError with reason "not_logged_in"; update the api command test
mocks in index.test.ts to either mock getValidToken() to throw an AuthError
instance with the same reason/message/docsUrl and assert that the command
surface handles/propagates that error, or change the mock to return a valid
token for tests that expect authenticated behavior; specifically adjust the mock
setup and assertions to reference AuthError and getValidToken() so the tests
reflect the new unauthenticated PLAPI path.
---
Outside diff comments:
In `@packages/cli-core/src/commands/auth/login.test.ts`:
- Line 521: The test references an undefined variable `mockGetToken`; replace
that usage with the correctly defined mock `mockGetValidToken` in the failing
test (the call at the line with mockGetToken.mockResolvedValue(null)) so the
test uses the existing mock variable `mockGetValidToken` instead of the
non-existent `mockGetToken`.
- Line 553: The failing test reuses the same mockGetToken reference across test
cases which causes value bleed and unpredictable behavior; update the tests to
either reset/replace mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.
- Line 582: The test is reusing the same mock reference mockGetToken which
causes cross-test leakage; change the setup to create an isolated mock or set a
one-time resolution so other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b17f3a36-f5cd-4db0-a653-43dfc0f9b368

📥 Commits

Reviewing files that changed from the base of the PR and between ef06e2c and b1ea0f7.

📒 Files selected for processing (18)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment threadpackages/cli-core/src/commands/init/heuristics.ts Outdated
Comment threadpackages/cli-core/src/lib/plapi.ts
@kylemac
kylemac requested a review from jfosheeApril 22, 2026 16:08
Align the implementation with the documented "pure credential-presence
check" intent. The previous code deserialized via getStoredSession() and
returned false for legacy raw-string credentials that don't match the
OAuthSession shape, incorrectly sending those users to the keyless init
flow.
@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch from 6009648 to 026c76cCompareApril 22, 2026 17:26

@rafa-thaytorafa-thayto 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.

LGTM

const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

If two parallel CLI calls hit getValidToken() while the token is expired, both will race into refreshStoredSession with the same refresh token. If the server rotates refresh tokens on use, the second call gets invalid_grant and nukes the credentials the first call just wrote.

Not likely in typical CLI usage, but could bite in CI scripts running clerk commands in parallel. A module-level promise guard would deduplicate:

Suggested change
}
letrefreshInFlight: Promise<string>|undefined;
asyncfunctionrefreshStoredSession(session: OAuthSession): Promise<string>{
if(refreshInFlight)returnrefreshInFlight;
refreshInFlight=doRefreshStoredSession(session).finally(()=>{
refreshInFlight=undefined;
});
returnrefreshInFlight;
}
asyncfunctiondoRefreshStoredSession(session: OAuthSession): Promise<string>{

Non-blocking, happy to merge as-is and handle this as a follow-up.

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

I got a version that's resilient to this change when more than one cli is operating at once. Don't think we needed the in-process protections as much as the cross-process ones.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/lib/credential-store.ts`:
- Around line 324-340: getValidToken treats any non-JSON legacy stored value as
an expired session because getStoredSession only handles the new JSON shape; to
fix this, update the flow to accept legacy raw tokens: in getStoredSession (or
in parseStoredSession) detect if readStoredValue() returns a plain string
(legacy raw token) and return an OAuthSession-like object (or at least an object
with accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2b91a154-39a2-4ecc-9516-cdbcd12329a3

📥 Commits

Reviewing files that changed from the base of the PR and between 6009648 and 026c76c.

📒 Files selected for processing (21)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/api/index.test.ts
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/lib/credential-store.test.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/api/index.test.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment on lines +324 to +340
export async function getStoredSession(): Promise<OAuthSession | null> {
const value = await readStoredValue();
if (!value) return null;
return parseStoredSession(value);
}

return fileGet();
export async function hasStoredCredentials(): Promise<boolean> {
return (await readStoredValue()) !== null;
}

export async function getValidToken(): Promise<string | null> {
const session = await getStoredSession();
if (!session) {
if (await hasStoredCredentials()) {
throw sessionExpiredError();
}
return null;

@coderabbitaicoderabbitaiBotApr 22, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Legacy raw credentials are treated as expired immediately.

getStoredSession() only recognizes the new JSON shape, so any pre-upgrade raw access token falls into this branch and becomes session_expired. Since authenticated commands now go through getValidToken(), upgrading will force every previously logged-in user to re-authenticate even when their stored token is still valid.

Suggested fix
 export async function getValidToken(): Promise<string | null> {
- const session = await getStoredSession();- if (!session) {- if (await hasStoredCredentials()) {- throw sessionExpiredError();- }- return null;- }+ const value = await readStoredValue();+ if (!value) return null;++ const session = parseStoredSession(value);+ if (!session) {+ const expiresAt = getJwtExpiryMs(value);+ if (expiresAt !== null && expiresAt <= Date.now() + JWT_EXPIRY_LEEWAY_MS) {+ throw sessionExpiredError();+ }+ return value;+ }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/lib/credential-store.ts` around lines 324 - 340,
getValidToken treats any non-JSON legacy stored value as an expired session
because getStoredSession only handles the new JSON shape; to fix this, update
the flow to accept legacy raw tokens: in getStoredSession (or in
parseStoredSession) detect if readStoredValue() returns a plain string (legacy
raw token) and return an OAuthSession-like object (or at least an object with
accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This is intentional

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@wyattjoh, understood — forcing a one-time re-authentication for users with a legacy raw token on upgrade is an intentional migration cut-over. I'll note this for future reviews.


✏️ Learnings added
Learnt from: wyattjoh
Repo: clerk/cli PR: 205
File: packages/cli-core/src/lib/credential-store.ts:324-340
Timestamp: 2026-04-22T17:39:54.554Z
Learning: In clerk/cli credential-store (`packages/cli-core/src/lib/credential-store.ts`), `getValidToken()` intentionally treats any stored credential that cannot be parsed as a valid `OAuthSession` JSON (i.e. a legacy raw access token string) as a `session_expired` error, forcing a one-time re-authentication on upgrade. Do not flag this as a bug — it is a deliberate migration design decision by the author.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: wyattjoh
Repo: clerk/cli PR: 118
File: packages/cli-core/src/commands/init/skills.ts:117-124
Timestamp: 2026-04-07T22:06:40.516Z
Learning: In clerk/cli, cancellation from inquirer/prompts (e.g., Ctrl+C resulting in UserAbortError / ExitPromptError) is handled globally in cli-program.ts (around the existing global catch). Therefore, command-level prompt call sites (e.g., confirm(), select()) in packages/cli-core/src should not wrap these prompt calls in local try/catch for UserAbortError/ExitPromptError cancellations—such local handling would be dead code and should remain consistent with the shared cancellation behavior.

Learnt from: wyattjoh
Repo: clerk/cli PR: 153
File: .claude/rules/scripts.md:36-36
Timestamp: 2026-04-13T23:09:41.178Z
Learning: In the clerk/cli repository, do not treat `Bun.$` (Bun Shell API) as experimental/unstable during code review. `Bun.$` is a stable, documented core Bun runtime feature (similar in status to `Bun.spawn` and `Bun.file`), so reviewers should not raise warnings that it relies on experimental APIs.

@jfosheejfoshee 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.

Some initial comments. I am still reviewing. :-)

Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
Comment threadpackages/cli-core/src/lib/credential-store.ts
Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

@wyattjoh
wyattjoh requested a review from jfosheeApril 22, 2026 18:05

@jfosheejfoshee 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.

Looks good. I did a manual test locally w/ a 5 min access token. Worked fine. It would just be nice to see something in the trace log that it was doing a refresh.

Another nice-to-have would be a manual refresh? like clerk auth refresh? wdyt? could be an internal only testing command.

async function refreshStoredSession(session: OAuthSession): Promise<string> {
let tokenResponse: TokenResponse;
try {
tokenResponse = await refreshAccessToken(session.refreshToken);

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.

I would like to see in the debug trace that we are doing a refresh. Is this the place to log it?

@wyattjoh
wyattjoh merged commit 23a3089 into mainApr 22, 2026
10 checks passed
@wyattjoh
wyattjoh deleted the wyattjoh/oauth-refresh-token-support branch April 22, 2026 18:39
@github-actionsgithub-actionsBot mentioned this pull request Apr 22, 2026
Sign up for freeto 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.

3 participants

@wyattjoh@jfoshee@rafa-thayto
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(auth): add OAuth refresh token session handling - #205

Merged
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support
Apr 22, 2026
Merged

feat(auth): add OAuth refresh token session handling#205
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support

Conversation

@wyattjoh

@wyattjohwyattjoh commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Summary

OAuth access tokens issued to the CLI are now short-lived JWTs. The credential store previously persisted only the raw access token, so once the token's exp passed every authenticated command failed with a 401 and forced the user back through clerk auth login. This change persists the full OAuth session, refreshes the access token transparently from the stored refresh token, and routes every auth failure through a single typed error so downstream code can react without string-matching.

What changed

  • Credential store now holds a session, not a bare token.storeToken accepts either a legacy access-token string or an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and persists it as JSON to the same keyring/file slot. getToken() stays backwards-compatible for readers that only want the string, so a session written by an older build is still readable.
  • New getValidToken() decodes the access-token JWT exp, and if it is within a 30s leeway of expiry calls the OAuth token endpoint with the stored refresh token, writes the new session back, and returns the fresh access token. invalid_grant responses wipe the stored session and raise AUTH_REQUIRED so the user is told to re-login rather than hitting a silent 401 loop.
  • All authenticated call sites route through getValidToken(): login, whoami, plapi requests, init heuristics, and every doctor check that needs a live session. Presence-only probes (is the user logged in at all?) use the new hasStoredCredentials() so we don't refresh as a side effect of non-auth flows.
  • Doctor validates the refresh path. The auth-related checks now pull the session through getValidToken() so clerk doctor surfaces refresh failures (expired refresh token, server-side revoke) the same way it surfaces other auth breakage, instead of reporting a healthy session while the next real call 401s.
  • Centralized auth error handling. New AuthError subclass of CliError carries a reason discriminator (not_logged_in / session_expired) with default per-reason messages, always codes to AUTH_REQUIRED, and replaces the hand-rolled CliError throws in whoami, plapi.getAuthToken, and credential-store. Doctor's token check now uses a new isAuthError() type guard covering both AuthError and ApiError(401|403) instead of regex-matching (401|403) substrings in error messages, so message-copy changes can't silently break the check.

Test plan

  • bun run format:check, bun run lint, bun run typecheck, bun run test
  • Unit coverage for getValidToken(): valid JWT returns unchanged, near-expiry JWT triggers a refresh and rewrites the session, invalid_grant clears credentials and throws AUTH_REQUIRED.
  • Doctor test covers the refresh-failure path by injecting an AuthError({ reason: "session_expired" }) into getValidToken() and asserting the check fails with the re-login remedy.
  • Manual: log in, force the access token past exp, run clerk whoami and confirm a refresh request fires and the session is rewritten transparently.
  • Manual: revoke the refresh token server-side, rerun a command, confirm the CLI reports session expired and clears the stored credentials.
  • Full E2E CI run on the PR.

@changeset-bot

changeset-botBot commented Apr 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9991c0c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
clerkMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch 2 times, most recently from dbb4068 to b1ea0f7CompareApril 22, 2026 15:36
@wyattjoh
wyattjoh marked this pull request as ready for review April 22, 2026 15:37
@coderabbitai

coderabbitaiBot commented Apr 22, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds OAuth refresh-token support across the CLI: credential storage now persists an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and exposes createOAuthSession, getStoredSession, hasStoredCredentials, and getValidToken. getValidToken validates expiry and attempts refresh via refreshAccessToken, deleting credentials and throwing AuthError(reason: "session_expired") on invalid_grant. Introduces AuthError and isAuthError. Commands and doctor/init/whoami/plapi call getValidToken instead of getToken. Tests and mocks updated to exercise session persistence and refresh flows; token-exchange gains refreshAccessToken.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 6.98% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Title check✅ PassedThe title accurately describes the main change: adding OAuth refresh token session handling to automatically refresh expired access tokens.
Description check✅ PassedThe description comprehensively explains the OAuth refresh token feature, the problem it solves, implementation details, affected call sites, and test coverage.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

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


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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/cli-core/src/commands/auth/login.test.ts (3)

521-521: ⚠️ Potential issue | 🔴 Critical

Build failure: mockGetToken is undefined.

The pipeline reports TS2304: Cannot find name 'mockGetToken'. This should be mockGetValidToken to match the mock defined at line 7.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 521, The test
references an undefined variable `mockGetToken`; replace that usage with the
correctly defined mock `mockGetValidToken` in the failing test (the call at the
line with mockGetToken.mockResolvedValue(null)) so the test uses the existing
mock variable `mockGetValidToken` instead of the non-existent `mockGetToken`.

553-553: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 553, The failing
test reuses the same mockGetToken reference across test cases which causes value
bleed and unpredictable behavior; update the tests to either reset/replace
mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.

582-582: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue("existing-token");+ mockGetValidToken.mockResolvedValue("existing-token");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 582, The test is
reusing the same mock reference mockGetToken which causes cross-test leakage;
change the setup to create an isolated mock or set a one-time resolution so
other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/commands/init/heuristics.ts`:
- Around line 6-7: The isAuthenticated check currently relies on
getStoredSession()/getValidToken deserialization and can misclassify legacy
stored credentials; change isAuthenticated to perform a credential-presence
check instead (e.g., verify existence of any stored credential/token rather than
successful session deserialization). Update the logic in heuristics.ts where
isAuthenticated is implemented/used (referencing getStoredSession, getValidToken
and the isAuthenticated call) to detect presence of credentials in the store and
return true for legacy tokens, ensuring keyless init isn't incorrectly chosen;
keep existing validation flows for full session usage separate from this
presence check.
In `@packages/cli-core/src/lib/plapi.ts`:
- Around line 60-64: The API command tests are failing because getValidToken()
now throws an AuthError with reason "not_logged_in"; update the api command test
mocks in index.test.ts to either mock getValidToken() to throw an AuthError
instance with the same reason/message/docsUrl and assert that the command
surface handles/propagates that error, or change the mock to return a valid
token for tests that expect authenticated behavior; specifically adjust the mock
setup and assertions to reference AuthError and getValidToken() so the tests
reflect the new unauthenticated PLAPI path.
---
Outside diff comments:
In `@packages/cli-core/src/commands/auth/login.test.ts`:
- Line 521: The test references an undefined variable `mockGetToken`; replace
that usage with the correctly defined mock `mockGetValidToken` in the failing
test (the call at the line with mockGetToken.mockResolvedValue(null)) so the
test uses the existing mock variable `mockGetValidToken` instead of the
non-existent `mockGetToken`.
- Line 553: The failing test reuses the same mockGetToken reference across test
cases which causes value bleed and unpredictable behavior; update the tests to
either reset/replace mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.
- Line 582: The test is reusing the same mock reference mockGetToken which
causes cross-test leakage; change the setup to create an isolated mock or set a
one-time resolution so other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b17f3a36-f5cd-4db0-a653-43dfc0f9b368

📥 Commits

Reviewing files that changed from the base of the PR and between ef06e2c and b1ea0f7.

📒 Files selected for processing (18)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment threadpackages/cli-core/src/commands/init/heuristics.ts Outdated
Comment threadpackages/cli-core/src/lib/plapi.ts
@kylemac
kylemac requested a review from jfosheeApril 22, 2026 16:08
Align the implementation with the documented "pure credential-presence
check" intent. The previous code deserialized via getStoredSession() and
returned false for legacy raw-string credentials that don't match the
OAuthSession shape, incorrectly sending those users to the keyless init
flow.
@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch from 6009648 to 026c76cCompareApril 22, 2026 17:26

@rafa-thaytorafa-thayto 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.

LGTM

const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

If two parallel CLI calls hit getValidToken() while the token is expired, both will race into refreshStoredSession with the same refresh token. If the server rotates refresh tokens on use, the second call gets invalid_grant and nukes the credentials the first call just wrote.

Not likely in typical CLI usage, but could bite in CI scripts running clerk commands in parallel. A module-level promise guard would deduplicate:

Suggested change
}
letrefreshInFlight: Promise<string>|undefined;
asyncfunctionrefreshStoredSession(session: OAuthSession): Promise<string>{
if(refreshInFlight)returnrefreshInFlight;
refreshInFlight=doRefreshStoredSession(session).finally(()=>{
refreshInFlight=undefined;
});
returnrefreshInFlight;
}
asyncfunctiondoRefreshStoredSession(session: OAuthSession): Promise<string>{

Non-blocking, happy to merge as-is and handle this as a follow-up.

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

I got a version that's resilient to this change when more than one cli is operating at once. Don't think we needed the in-process protections as much as the cross-process ones.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/lib/credential-store.ts`:
- Around line 324-340: getValidToken treats any non-JSON legacy stored value as
an expired session because getStoredSession only handles the new JSON shape; to
fix this, update the flow to accept legacy raw tokens: in getStoredSession (or
in parseStoredSession) detect if readStoredValue() returns a plain string
(legacy raw token) and return an OAuthSession-like object (or at least an object
with accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2b91a154-39a2-4ecc-9516-cdbcd12329a3

📥 Commits

Reviewing files that changed from the base of the PR and between 6009648 and 026c76c.

📒 Files selected for processing (21)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/api/index.test.ts
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/lib/credential-store.test.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/api/index.test.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment on lines +324 to +340
export async function getStoredSession(): Promise<OAuthSession | null> {
const value = await readStoredValue();
if (!value) return null;
return parseStoredSession(value);
}

return fileGet();
export async function hasStoredCredentials(): Promise<boolean> {
return (await readStoredValue()) !== null;
}

export async function getValidToken(): Promise<string | null> {
const session = await getStoredSession();
if (!session) {
if (await hasStoredCredentials()) {
throw sessionExpiredError();
}
return null;

@coderabbitaicoderabbitaiBotApr 22, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Legacy raw credentials are treated as expired immediately.

getStoredSession() only recognizes the new JSON shape, so any pre-upgrade raw access token falls into this branch and becomes session_expired. Since authenticated commands now go through getValidToken(), upgrading will force every previously logged-in user to re-authenticate even when their stored token is still valid.

Suggested fix
 export async function getValidToken(): Promise<string | null> {
- const session = await getStoredSession();- if (!session) {- if (await hasStoredCredentials()) {- throw sessionExpiredError();- }- return null;- }+ const value = await readStoredValue();+ if (!value) return null;++ const session = parseStoredSession(value);+ if (!session) {+ const expiresAt = getJwtExpiryMs(value);+ if (expiresAt !== null && expiresAt <= Date.now() + JWT_EXPIRY_LEEWAY_MS) {+ throw sessionExpiredError();+ }+ return value;+ }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/lib/credential-store.ts` around lines 324 - 340,
getValidToken treats any non-JSON legacy stored value as an expired session
because getStoredSession only handles the new JSON shape; to fix this, update
the flow to accept legacy raw tokens: in getStoredSession (or in
parseStoredSession) detect if readStoredValue() returns a plain string (legacy
raw token) and return an OAuthSession-like object (or at least an object with
accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This is intentional

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@wyattjoh, understood — forcing a one-time re-authentication for users with a legacy raw token on upgrade is an intentional migration cut-over. I'll note this for future reviews.


✏️ Learnings added
Learnt from: wyattjoh
Repo: clerk/cli PR: 205
File: packages/cli-core/src/lib/credential-store.ts:324-340
Timestamp: 2026-04-22T17:39:54.554Z
Learning: In clerk/cli credential-store (`packages/cli-core/src/lib/credential-store.ts`), `getValidToken()` intentionally treats any stored credential that cannot be parsed as a valid `OAuthSession` JSON (i.e. a legacy raw access token string) as a `session_expired` error, forcing a one-time re-authentication on upgrade. Do not flag this as a bug — it is a deliberate migration design decision by the author.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: wyattjoh
Repo: clerk/cli PR: 118
File: packages/cli-core/src/commands/init/skills.ts:117-124
Timestamp: 2026-04-07T22:06:40.516Z
Learning: In clerk/cli, cancellation from inquirer/prompts (e.g., Ctrl+C resulting in UserAbortError / ExitPromptError) is handled globally in cli-program.ts (around the existing global catch). Therefore, command-level prompt call sites (e.g., confirm(), select()) in packages/cli-core/src should not wrap these prompt calls in local try/catch for UserAbortError/ExitPromptError cancellations—such local handling would be dead code and should remain consistent with the shared cancellation behavior.

Learnt from: wyattjoh
Repo: clerk/cli PR: 153
File: .claude/rules/scripts.md:36-36
Timestamp: 2026-04-13T23:09:41.178Z
Learning: In the clerk/cli repository, do not treat `Bun.$` (Bun Shell API) as experimental/unstable during code review. `Bun.$` is a stable, documented core Bun runtime feature (similar in status to `Bun.spawn` and `Bun.file`), so reviewers should not raise warnings that it relies on experimental APIs.

@jfosheejfoshee 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.

Some initial comments. I am still reviewing. :-)

Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
Comment threadpackages/cli-core/src/lib/credential-store.ts
Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

@wyattjoh
wyattjoh requested a review from jfosheeApril 22, 2026 18:05

@jfosheejfoshee 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.

Looks good. I did a manual test locally w/ a 5 min access token. Worked fine. It would just be nice to see something in the trace log that it was doing a refresh.

Another nice-to-have would be a manual refresh? like clerk auth refresh? wdyt? could be an internal only testing command.

async function refreshStoredSession(session: OAuthSession): Promise<string> {
let tokenResponse: TokenResponse;
try {
tokenResponse = await refreshAccessToken(session.refreshToken);

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.

I would like to see in the debug trace that we are doing a refresh. Is this the place to log it?

@wyattjoh
wyattjoh merged commit 23a3089 into mainApr 22, 2026
10 checks passed
@wyattjoh
wyattjoh deleted the wyattjoh/oauth-refresh-token-support branch April 22, 2026 18:39
@github-actionsgithub-actionsBot mentioned this pull request Apr 22, 2026
Sign up for freeto 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.

3 participants

@wyattjoh@jfoshee@rafa-thayto
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

feat(auth): add OAuth refresh token session handling - #205

Merged
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support
Apr 22, 2026
Merged

feat(auth): add OAuth refresh token session handling#205
wyattjoh merged 9 commits into
mainfrom
wyattjoh/oauth-refresh-token-support

Conversation

@wyattjoh

@wyattjohwyattjoh commented Apr 22, 2026

Copy link
Copy Markdown
Contributor

Summary

OAuth access tokens issued to the CLI are now short-lived JWTs. The credential store previously persisted only the raw access token, so once the token's exp passed every authenticated command failed with a 401 and forced the user back through clerk auth login. This change persists the full OAuth session, refreshes the access token transparently from the stored refresh token, and routes every auth failure through a single typed error so downstream code can react without string-matching.

What changed

  • Credential store now holds a session, not a bare token.storeToken accepts either a legacy access-token string or an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and persists it as JSON to the same keyring/file slot. getToken() stays backwards-compatible for readers that only want the string, so a session written by an older build is still readable.
  • New getValidToken() decodes the access-token JWT exp, and if it is within a 30s leeway of expiry calls the OAuth token endpoint with the stored refresh token, writes the new session back, and returns the fresh access token. invalid_grant responses wipe the stored session and raise AUTH_REQUIRED so the user is told to re-login rather than hitting a silent 401 loop.
  • All authenticated call sites route through getValidToken(): login, whoami, plapi requests, init heuristics, and every doctor check that needs a live session. Presence-only probes (is the user logged in at all?) use the new hasStoredCredentials() so we don't refresh as a side effect of non-auth flows.
  • Doctor validates the refresh path. The auth-related checks now pull the session through getValidToken() so clerk doctor surfaces refresh failures (expired refresh token, server-side revoke) the same way it surfaces other auth breakage, instead of reporting a healthy session while the next real call 401s.
  • Centralized auth error handling. New AuthError subclass of CliError carries a reason discriminator (not_logged_in / session_expired) with default per-reason messages, always codes to AUTH_REQUIRED, and replaces the hand-rolled CliError throws in whoami, plapi.getAuthToken, and credential-store. Doctor's token check now uses a new isAuthError() type guard covering both AuthError and ApiError(401|403) instead of regex-matching (401|403) substrings in error messages, so message-copy changes can't silently break the check.

Test plan

  • bun run format:check, bun run lint, bun run typecheck, bun run test
  • Unit coverage for getValidToken(): valid JWT returns unchanged, near-expiry JWT triggers a refresh and rewrites the session, invalid_grant clears credentials and throws AUTH_REQUIRED.
  • Doctor test covers the refresh-failure path by injecting an AuthError({ reason: "session_expired" }) into getValidToken() and asserting the check fails with the re-login remedy.
  • Manual: log in, force the access token past exp, run clerk whoami and confirm a refresh request fires and the session is rewritten transparently.
  • Manual: revoke the refresh token server-side, rerun a command, confirm the CLI reports session expired and clears the stored credentials.
  • Full E2E CI run on the PR.

@changeset-bot

changeset-botBot commented Apr 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9991c0c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
clerkMinor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch 2 times, most recently from dbb4068 to b1ea0f7CompareApril 22, 2026 15:36
@wyattjoh
wyattjoh marked this pull request as ready for review April 22, 2026 15:37
@coderabbitai

coderabbitaiBot commented Apr 22, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds OAuth refresh-token support across the CLI: credential storage now persists an OAuthSession (accessToken, refreshToken, expiresAt, tokenType) and exposes createOAuthSession, getStoredSession, hasStoredCredentials, and getValidToken. getValidToken validates expiry and attempts refresh via refreshAccessToken, deleting credentials and throwing AuthError(reason: "session_expired") on invalid_grant. Introduces AuthError and isAuthError. Commands and doctor/init/whoami/plapi call getValidToken instead of getToken. Tests and mocks updated to exercise session persistence and refresh flows; token-exchange gains refreshAccessToken.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 6.98% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check nameStatusExplanation
Title check✅ PassedThe title accurately describes the main change: adding OAuth refresh token session handling to automatically refresh expired access tokens.
Description check✅ PassedThe description comprehensively explains the OAuth refresh token feature, the problem it solves, implementation details, affected call sites, and test coverage.
Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.

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


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

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/cli-core/src/commands/auth/login.test.ts (3)

521-521: ⚠️ Potential issue | 🔴 Critical

Build failure: mockGetToken is undefined.

The pipeline reports TS2304: Cannot find name 'mockGetToken'. This should be mockGetValidToken to match the mock defined at line 7.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 521, The test
references an undefined variable `mockGetToken`; replace that usage with the
correctly defined mock `mockGetValidToken` in the failing test (the call at the
line with mockGetToken.mockResolvedValue(null)) so the test uses the existing
mock variable `mockGetValidToken` instead of the non-existent `mockGetToken`.

553-553: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue(null);+ mockGetValidToken.mockResolvedValue(null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 553, The failing
test reuses the same mockGetToken reference across test cases which causes value
bleed and unpredictable behavior; update the tests to either reset/replace
mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.

582-582: ⚠️ Potential issue | 🔴 Critical

Build failure: same mockGetToken reference.

🐛 Fix
- mockGetToken.mockResolvedValue("existing-token");+ mockGetValidToken.mockResolvedValue("existing-token");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/commands/auth/login.test.ts` at line 582, The test is
reusing the same mock reference mockGetToken which causes cross-test leakage;
change the setup to create an isolated mock or set a one-time resolution so
other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/commands/init/heuristics.ts`:
- Around line 6-7: The isAuthenticated check currently relies on
getStoredSession()/getValidToken deserialization and can misclassify legacy
stored credentials; change isAuthenticated to perform a credential-presence
check instead (e.g., verify existence of any stored credential/token rather than
successful session deserialization). Update the logic in heuristics.ts where
isAuthenticated is implemented/used (referencing getStoredSession, getValidToken
and the isAuthenticated call) to detect presence of credentials in the store and
return true for legacy tokens, ensuring keyless init isn't incorrectly chosen;
keep existing validation flows for full session usage separate from this
presence check.
In `@packages/cli-core/src/lib/plapi.ts`:
- Around line 60-64: The API command tests are failing because getValidToken()
now throws an AuthError with reason "not_logged_in"; update the api command test
mocks in index.test.ts to either mock getValidToken() to throw an AuthError
instance with the same reason/message/docsUrl and assert that the command
surface handles/propagates that error, or change the mock to return a valid
token for tests that expect authenticated behavior; specifically adjust the mock
setup and assertions to reference AuthError and getValidToken() so the tests
reflect the new unauthenticated PLAPI path.
---
Outside diff comments:
In `@packages/cli-core/src/commands/auth/login.test.ts`:
- Line 521: The test references an undefined variable `mockGetToken`; replace
that usage with the correctly defined mock `mockGetValidToken` in the failing
test (the call at the line with mockGetToken.mockResolvedValue(null)) so the
test uses the existing mock variable `mockGetValidToken` instead of the
non-existent `mockGetToken`.
- Line 553: The failing test reuses the same mockGetToken reference across test
cases which causes value bleed and unpredictable behavior; update the tests to
either reset/replace mockGetToken between tests (call mockGetToken.mockReset() /
mockGetToken.mockClear() in beforeEach or reassign mockGetToken = jest.fn() per
test) or use mockGetToken.mockResolvedValueOnce(...) when setting per-test
return values so each test gets an isolated mock value; locate usages of
mockGetToken in the login.test.ts file and apply one of these fixes to ensure
each test configures its own mock behavior.
- Line 582: The test is reusing the same mock reference mockGetToken which
causes cross-test leakage; change the setup to create an isolated mock or set a
one-time resolution so other tests aren't affected—for example replace
mockGetToken.mockResolvedValue("existing-token") with a one-off behavior
(mockGetToken.mockResolvedValueOnce("existing-token")) or recreate/reset
mockGetToken before this test (via jest.fn() or jest.resetAllMocks()) so the
mock is unique to this test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b17f3a36-f5cd-4db0-a653-43dfc0f9b368

📥 Commits

Reviewing files that changed from the base of the PR and between ef06e2c and b1ea0f7.

📒 Files selected for processing (18)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment threadpackages/cli-core/src/commands/init/heuristics.ts Outdated
Comment threadpackages/cli-core/src/lib/plapi.ts
@kylemac
kylemac requested a review from jfosheeApril 22, 2026 16:08
Align the implementation with the documented "pure credential-presence
check" intent. The previous code deserialized via getStoredSession() and
returned false for legacy raw-string credentials that don't match the
OAuthSession shape, incorrectly sending those users to the keyless init
flow.
@wyattjoh
wyattjohforce-pushed the wyattjoh/oauth-refresh-token-support branch from 6009648 to 026c76cCompareApril 22, 2026 17:26

@rafa-thaytorafa-thayto 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.

LGTM

const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

If two parallel CLI calls hit getValidToken() while the token is expired, both will race into refreshStoredSession with the same refresh token. If the server rotates refresh tokens on use, the second call gets invalid_grant and nukes the credentials the first call just wrote.

Not likely in typical CLI usage, but could bite in CI scripts running clerk commands in parallel. A module-level promise guard would deduplicate:

Suggested change
}
letrefreshInFlight: Promise<string>|undefined;
asyncfunctionrefreshStoredSession(session: OAuthSession): Promise<string>{
if(refreshInFlight)returnrefreshInFlight;
refreshInFlight=doRefreshStoredSession(session).finally(()=>{
refreshInFlight=undefined;
});
returnrefreshInFlight;
}
asyncfunctiondoRefreshStoredSession(session: OAuthSession): Promise<string>{

Non-blocking, happy to merge as-is and handle this as a follow-up.

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

I got a version that's resilient to this change when more than one cli is operating at once. Don't think we needed the in-process protections as much as the cross-process ones.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli-core/src/lib/credential-store.ts`:
- Around line 324-340: getValidToken treats any non-JSON legacy stored value as
an expired session because getStoredSession only handles the new JSON shape; to
fix this, update the flow to accept legacy raw tokens: in getStoredSession (or
in parseStoredSession) detect if readStoredValue() returns a plain string
(legacy raw token) and return an OAuthSession-like object (or at least an object
with accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2b91a154-39a2-4ecc-9516-cdbcd12329a3

📥 Commits

Reviewing files that changed from the base of the PR and between 6009648 and 026c76c.

📒 Files selected for processing (21)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/api/index.test.ts
  • packages/cli-core/src/commands/auth/login.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/commands/doctor/checks.ts
  • packages/cli-core/src/commands/doctor/context.ts
  • packages/cli-core/src/commands/doctor/doctor.test.ts
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/lib/credential-store.test.ts
  • packages/cli-core/src/lib/credential-store.ts
  • packages/cli-core/src/lib/errors.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/lib/token-exchange.ts
  • packages/cli-core/src/test/integration/lib/harness.ts
  • packages/cli-core/src/test/lib/stubs.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/cli-core/src/lib/autolink.test.ts
  • packages/cli-core/src/commands/whoami/index.test.ts
  • packages/cli-core/src/commands/api/index.test.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • .changeset/oauth-refresh-token-support.md
  • packages/cli-core/src/commands/doctor/types.ts
  • packages/cli-core/src/commands/init/heuristics.ts
  • packages/cli-core/src/lib/plapi.ts
  • packages/cli-core/src/commands/whoami/index.ts
  • packages/cli-core/src/lib/plapi.test.ts
  • packages/cli-core/src/commands/auth/login.ts
  • packages/cli-core/src/lib/token-exchange.test.ts
  • packages/cli-core/src/test/lib/stubs.ts

Comment on lines +324 to +340
export async function getStoredSession(): Promise<OAuthSession | null> {
const value = await readStoredValue();
if (!value) return null;
return parseStoredSession(value);
}

return fileGet();
export async function hasStoredCredentials(): Promise<boolean> {
return (await readStoredValue()) !== null;
}

export async function getValidToken(): Promise<string | null> {
const session = await getStoredSession();
if (!session) {
if (await hasStoredCredentials()) {
throw sessionExpiredError();
}
return null;

@coderabbitaicoderabbitaiBotApr 22, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Legacy raw credentials are treated as expired immediately.

getStoredSession() only recognizes the new JSON shape, so any pre-upgrade raw access token falls into this branch and becomes session_expired. Since authenticated commands now go through getValidToken(), upgrading will force every previously logged-in user to re-authenticate even when their stored token is still valid.

Suggested fix
 export async function getValidToken(): Promise<string | null> {
- const session = await getStoredSession();- if (!session) {- if (await hasStoredCredentials()) {- throw sessionExpiredError();- }- return null;- }+ const value = await readStoredValue();+ if (!value) return null;++ const session = parseStoredSession(value);+ if (!session) {+ const expiresAt = getJwtExpiryMs(value);+ if (expiresAt !== null && expiresAt <= Date.now() + JWT_EXPIRY_LEEWAY_MS) {+ throw sessionExpiredError();+ }+ return value;+ }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli-core/src/lib/credential-store.ts` around lines 324 - 340,
getValidToken treats any non-JSON legacy stored value as an expired session
because getStoredSession only handles the new JSON shape; to fix this, update
the flow to accept legacy raw tokens: in getStoredSession (or in
parseStoredSession) detect if readStoredValue() returns a plain string (legacy
raw token) and return an OAuthSession-like object (or at least an object with
accessToken populated) so callers like getValidToken can use it, or
alternatively modify getValidToken to call readStoredValue() directly when
getStoredSession() is null and hasStoredCredentials() is true and treat a plain
string value as a valid access token; reference functions: getStoredSession,
getValidToken, readStoredValue, parseStoredSession.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

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

This is intentional

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@wyattjoh, understood — forcing a one-time re-authentication for users with a legacy raw token on upgrade is an intentional migration cut-over. I'll note this for future reviews.


✏️ Learnings added
Learnt from: wyattjoh
Repo: clerk/cli PR: 205
File: packages/cli-core/src/lib/credential-store.ts:324-340
Timestamp: 2026-04-22T17:39:54.554Z
Learning: In clerk/cli credential-store (`packages/cli-core/src/lib/credential-store.ts`), `getValidToken()` intentionally treats any stored credential that cannot be parsed as a valid `OAuthSession` JSON (i.e. a legacy raw access token string) as a `session_expired` error, forcing a one-time re-authentication on upgrade. Do not flag this as a bug — it is a deliberate migration design decision by the author.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: wyattjoh
Repo: clerk/cli PR: 118
File: packages/cli-core/src/commands/init/skills.ts:117-124
Timestamp: 2026-04-07T22:06:40.516Z
Learning: In clerk/cli, cancellation from inquirer/prompts (e.g., Ctrl+C resulting in UserAbortError / ExitPromptError) is handled globally in cli-program.ts (around the existing global catch). Therefore, command-level prompt call sites (e.g., confirm(), select()) in packages/cli-core/src should not wrap these prompt calls in local try/catch for UserAbortError/ExitPromptError cancellations—such local handling would be dead code and should remain consistent with the shared cancellation behavior.

Learnt from: wyattjoh
Repo: clerk/cli PR: 153
File: .claude/rules/scripts.md:36-36
Timestamp: 2026-04-13T23:09:41.178Z
Learning: In the clerk/cli repository, do not treat `Bun.$` (Bun Shell API) as experimental/unstable during code review. `Bun.$` is a stable, documented core Bun runtime feature (similar in status to `Bun.spawn` and `Bun.file`), so reviewers should not raise warnings that it relies on experimental APIs.

@jfosheejfoshee 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.

Some initial comments. I am still reviewing. :-)

Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
Comment threadpackages/cli-core/src/lib/credential-store.ts
Comment threadpackages/cli-core/src/lib/credential-store.ts Outdated
const nextSession = createOAuthSession(tokenResponse, session.refreshToken);
await storeToken(nextSession);
return nextSession.accessToken;
}

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.

Yeah it can happen. Not sure about how to address it. I don't think I want to add system or user locks at this point, so let's wait for another PR?

@wyattjoh
wyattjoh requested a review from jfosheeApril 22, 2026 18:05

@jfosheejfoshee 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.

Looks good. I did a manual test locally w/ a 5 min access token. Worked fine. It would just be nice to see something in the trace log that it was doing a refresh.

Another nice-to-have would be a manual refresh? like clerk auth refresh? wdyt? could be an internal only testing command.

async function refreshStoredSession(session: OAuthSession): Promise<string> {
let tokenResponse: TokenResponse;
try {
tokenResponse = await refreshAccessToken(session.refreshToken);

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.

I would like to see in the debug trace that we are doing a refresh. Is this the place to log it?

@wyattjoh
wyattjoh merged commit 23a3089 into mainApr 22, 2026
10 checks passed
@wyattjoh
wyattjoh deleted the wyattjoh/oauth-refresh-token-support branch April 22, 2026 18:39
@github-actionsgithub-actionsBot mentioned this pull request Apr 22, 2026
Sign up for freeto 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.

3 participants

@wyattjoh@jfoshee@rafa-thayto