fix(api): jwtProcedure accepts x-api-key sessions, not just Bearer

Merged
SA
6mo ago
+23-26

Summary

jwtProcedure was rejecting any request without an Authorization: Bearer … header before reaching its session fallback. Better-auth's apiKey plugin (enableSessionForAPIKeys: true) populates ctx.session for x-api-key requests, so they're session-equivalent — but they couldn't reach that branch because the upfront throw fired first.

Concretely, the CLI's `--api-key sk_live_…` flag round-tripped through better-auth (returns 200 against `protectedProcedure` like `user.me`), but every `jwtProcedure`-gated procedure (`host.list`, `v2-workspace.list`, etc.) returned 401. `superset hosts list` and `superset workspaces list` were unusable with API keys.

This PR rewrites the procedure to accept any of:

  1. A verifiable Bearer JWT (CLI OAuth flow)
  2. A live `ctx.session` (web cookie OR x-api-key-derived session)

Bot-fix from #3889 preserved: TRPCError instances from `verifyJWT` (revoked/forged tokens) still re-throw rather than silently falling through.

Test plan

  • `bun run typecheck` clean
  • `bun run lint` clean
  • CLI with `SUPERSET_API_KEY=sk_live_…` succeeds on `superset hosts list`, `superset workspaces list`
  • CLI with OAuth JWT still works (no regression)
  • Desktop session-cookie path still works (no regression)
  • Revoked JWT still surfaces UNAUTHORIZED instead of silently using session

Summary by cubic

Allow jwtProcedure to authenticate with a Bearer JWT or any live session (cookie or x-api-key), fixing CLI API key flows that were returning 401. CLI commands like superset hosts list and superset workspaces list now work with --api-key or SUPERSET_API_KEY.

  • Bug Fixes
    • Removed the Bearer-only guard; verify JWT if present, otherwise use ctx.session (includes x-api-key sessions from better-auth).
    • Preserved re-throw of TRPCError from verifyJWT for explicit JWT rejection.
    • Updated unauthorized message to list accepted auth methods.

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Improved authentication flow to support multiple credential types: bearer JWT, x-api-key, or session authentication
    • Enhanced error messages to reflect all available authentication methods
    • Fixed authentication handling to allow graceful fallback between credential types