Skip to content

fix(auth): use standalone PKCE for Vercel compatibility#72

Merged
acald-creator merged 4 commits into
mainfrom
fix/vercel-build
Apr 14, 2026
Merged

fix(auth): use standalone PKCE for Vercel compatibility#72
acald-creator merged 4 commits into
mainfrom
fix/vercel-build

Conversation

@acald-creator
Copy link
Copy Markdown
Owner

@acald-creator acald-creator commented Apr 14, 2026

Summary

  • Remove @cosmonexus/oauth-* packages (require local Verdaccio, unavailable on Vercel)
  • Remove .npmrc and package-lock.json
  • Revert OAuthPkce.res to standalone PKCE implementation
  • Comment out @cosmonexus bindings in OAuthPkce.res and OAuthReact.res for future swap-in
  • Simplify AuthContext.res to use standalone flow directly
  • Remove UserProvider wrapper from App.res (no longer needed)

The @cosmonexus bindings are preserved as comments — uncomment when the packages are published to npm.

Test plan

  • bun run res:build — 112 modules, zero warnings
  • bun run build — production build succeeds (no external registry needed)
  • bun run test — all 18 tests pass

Summary by CodeRabbit

  • Refactor

    • Refactored the authentication system and component tree structure for improved organization.
    • Replaced external OAuth integration with an internal authentication mechanism.
  • Chores

    • Removed multiple external OAuth-related package dependencies from the application.
    • Updated npm package registry configuration accordingly.

Remove @cosmonexus/oauth-* packages and .npmrc (requires local
Verdaccio). Revert to standalone PKCE implementation in OAuthPkce.res.
Comment out @CosmoNexus bindings in OAuthPkce.res and OAuthReact.res
for future swap-in when packages are published to npm.
@vercel
Copy link
Copy Markdown

vercel Bot commented Apr 14, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
rspack-rescript Ready Ready Preview, Comment Apr 14, 2026 2:47am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 14, 2026

Warning

Rate limit exceeded

@acald-creator has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 52 minutes and 25 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 52 minutes and 25 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6c1fa004-0cbc-4c95-a899-14c8e497a4e0

📥 Commits

Reviewing files that changed from the base of the PR and between 17a72f5 and 203b403.

📒 Files selected for processing (3)
  • src/bindings/OAuthPkce.res
  • src/context/AuthContext.res
  • src/pages/LoginPage.res
📝 Walkthrough

Walkthrough

This PR removes the @cosmonexus OAuth library and replaces it with a custom OAuth 2.0 PKCE implementation using native WebCrypto and Fetch APIs. Dependencies are removed, bindings rewritten, and the auth context refactored to use the new custom flow.

Changes

Cohort / File(s) Summary
Dependency Removal
.npmrc, package.json
Removed the @cosmonexus npm scope redirect and all four @cosmonexus/oauth-* package dependencies.
Custom PKCE Implementation
src/bindings/OAuthPkce.res
Replaced @cosmonexus/oauth-client bindings with standalone OAuth 2.0 PKCE implementation. Added config and tokenSet types; new functions generateRandomString, generateCodeChallenge (WebCrypto), startAuth (builds auth URL, stores PKCE values in sessionStorage), and exchangeCode (exchanges code for tokens via fetch).
OAuth React Bindings
src/bindings/OAuthReact.res
Fully commented out all previously exported types (tokenSet, logoutOptions, authContextValue, useOAuthCallbackResult), component modules (AuthProvider, LoginButton), and hook externals (useAuth, useOAuthCallback).
Auth Context Refactoring
src/context/AuthContext.res
Replaced OAuthReact.AuthProvider with internal React context (ContextProvider). Updated login to use OAuthPkce.startAuth() and browser redirect, handleCallback to extract code from URL and exchange via OAuthPkce.exchangeCode(), and logout to clear local state only. Changed oauth config type from oauthClientConfig to config.
Component Tree Simplification
src/App.res
Removed nested AuthContext.UserProvider wrapper; app layout now rendered directly within AuthContext.Provider.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant Browser
    participant App as App/AuthContext
    participant OAuthPkce
    participant AuthServer as Auth Server
    participant TokenServer as Token Server

    User->>Browser: Click Login
    Browser->>App: Trigger login()
    App->>OAuthPkce: startAuth(config)
    OAuthPkce->>OAuthPkce: generateRandomString() → state
    OAuthPkce->>OAuthPkce: generateRandomString() → code_verifier
    OAuthPkce->>OAuthPkce: generateCodeChallenge(code_verifier)
    OAuthPkce->>OAuthPkce: Store state, code_verifier in sessionStorage
    OAuthPkce-->>App: Return authorize URL
    App->>Browser: Redirect to authorize URL
    Browser->>AuthServer: GET /authorize?code_challenge=...&state=...
    AuthServer->>Browser: Show login/consent screen
    User->>AuthServer: Authenticate & consent
    AuthServer->>Browser: Redirect to callback?code=AUTH_CODE&state=STATE
    Browser->>App: Load callback page with code & state
    App->>OAuthPkce: exchangeCode(config, code)
    OAuthPkce->>OAuthPkce: Retrieve code_verifier from sessionStorage
    OAuthPkce->>TokenServer: POST /token (code, code_verifier, client_id)
    TokenServer-->>OAuthPkce: Return accessToken, tokenType, expiresIn
    OAuthPkce->>OAuthPkce: Clear sessionStorage (code_verifier, state)
    OAuthPkce-->>App: Return tokenSet
    App->>App: Update state: LoggedIn(tokenSet)
    Browser->>User: Redirect to authenticated app
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • feat: add OAuth 2.0 PKCE authentication flow #70: Directly reversed by this PR; both modify the same OAuth integration files (OAuthPkce.res, OAuthReact.res, AuthContext.res, App.res, package.json, .npmrc), replacing @cosmonexus bindings with a custom PKCE implementation and internal auth context.

Poem

🐰 Hops with glee — The oauth chains now cast away,
A custom PKCE blooms in code today!
WebCrypto whispers secrets to sessionStorage's keep,
No vendor bindings needed — just a bundle lean and cheap! 🔐

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main objective: replacing external OAuth dependencies with a standalone PKCE implementation to resolve Vercel deployment compatibility.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/vercel-build

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Show a caption below the sign-in button explaining that the OAuth
flow requires the mock server running locally.
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/bindings/OAuthPkce.res`:
- Around line 73-107: exchangeCode currently always returns a tokenSet even when
the token endpoint fails; update exchangeCode to validate and throw on errors:
first read the codeVerifier from sessionStorage and if it's empty throw; after
fetchRaw check the response status (response.ok) and if not OK parse the
response body (json) and throw an Error including status and any
json.error/details; once OK parse json and validate required fields
json["access_token"], json["token_type"], and json["expires_in"] and throw if
any are missing; still remove sessionStorage pkce items
(sessionStorage.removeItem) before throwing or returning; finally return the
token shape only when all validations pass. Include references to exchangeCode,
fetchRaw, and the sessionStorage pkce keys so you edit the right code.

In `@src/context/AuthContext.res`:
- Around line 56-77: The callback currently only extracts `code` in
`parseCode`/`handleCallback` and immediately calls `OAuthPkce.exchangeCode`;
update `parseCode` to also read `state`, then in `handleCallback` compare the
returned `state` to the stored `pkce_state` (the value set by
`OAuthPkce.startAuth`) and abort (do not call `OAuthPkce.exchangeCode`) if they
do not match; ensure the mismatch path logs/handles the error and only proceeds
to call `OAuthPkce.exchangeCode(oauthConfig, c)` and setState when the `state`
check passes.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7193cb45-3f2b-4a10-87db-e9ecab2d7d66

📥 Commits

Reviewing files that changed from the base of the PR and between 93247f1 and 17a72f5.

⛔ Files ignored due to path filters (2)
  • bun.lockb is excluded by !**/bun.lockb
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • .npmrc
  • package.json
  • src/App.res
  • src/bindings/OAuthPkce.res
  • src/bindings/OAuthReact.res
  • src/context/AuthContext.res
💤 Files with no reviewable changes (2)
  • .npmrc
  • package.json

Comment thread src/bindings/OAuthPkce.res
Comment thread src/context/AuthContext.res Outdated
Validate code verifier exists before exchange, check response.ok
and throw with status on failure, validate required fields
(access_token, token_type, expires_in) in response. Always clean
up sessionStorage before throwing or returning.
Compare returned state from callback URL against stored pkce_state
in sessionStorage. Abort token exchange and log error on mismatch
to prevent CSRF attacks.
@acald-creator acald-creator merged commit 91ee02e into main Apr 14, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant