Document 03 / 03

Authentication Guide

Version 2.0August 14, 20265 min readSource on GitHub

This guide documents how authentication currently works in Tunnel, based on a line-by-line read of the frontend and backend auth code. It also flags the security defect in the custom middleware and the exact fix to apply.


1. How auth works today (verified)#

1.1 Frontend#

  • Provider: Frontend/src/main.jsx wraps the app in ClerkProvider (from @clerk/react, v6) with VITE_CLERK_PUBLISHABLE_KEY.
  • Token plumbing: a ClerkTokenInit component calls useAuth() and registers the Clerk getToken function with the API layer via setClerkTokenProvider(getToken) (defined in Frontend/src/services/apiClient.js).
  • Request interceptor: apiClient (axios, baseURL VITE_API_URL) attaches Authorization: Bearer <token> on every request. It caches the token and refreshes it when it expires within 30s.
  • Auth context: Frontend/src/context/auth_context.jsx uses Clerk's useAuth(); isAuthenticated = valid Clerk session. Profile loading is non-blocking.
  • Route guarding: ProtectedRoute (components/common/protectedroute.jsx) blocks routes until Clerk isLoaded and user is signed in, then redirects to /login.

So the primary path is fully wired: Clerk session → Bearer token → Express.

1.2 Backend#

Two different, coexisting auth middlewares are in use — this is the core problem.

MiddlewareWhere usedVerification level
clerkMiddleware() from @clerk/express (app.js:45)global, populates req.auth for every requestReal — validates JWT signature against Clerk keys
requireAuth() from @clerk/expressstream.route.js, Social.controller.jsReal — same as above
custom require-Auth.js (middleware/require-Auth.js)user.route.js, profile.route.js, payment.route.js, analytics.route.js, chat.route.js, follower.route.jsWEAK — decodes JWT only, does NOT verify signature

1.3 The custom require-Auth.js weakness#

const token = authHeader.slice(7);
const decoded = jwtDecode(token);           // no signature check!
if (decoded.exp && decoded.exp * 1000 < Date.now()) return 401;
if (!decoded.iss || !decoded.iss.includes("clerk")) return 401;
req.auth = { userId: decoded.sub };

It checks only expiry and that the issuer string contains "clerk". Any JWT — including one hand-crafted without a valid signature, with iss: "https://xclerk.example" and any sub — passes. That means every route protected by the custom middleware can be impersonated by simply pasting a forged token.

Fix (recommended): delete middleware/require-Auth.js and use requireAuth() from @clerk/express in all route files. Example:

import { requireAuth } from "@clerk/express";
route.get("/profile", requireAuth(), getProfile);   // note: requireAuth() returns middleware

The existing user.route.js/profile.route.js currently import requireAuth from ../middleware/require-Auth.js. Change the import to @clerk/express. Also remove the jwt-decode dependency if nothing else uses it.


2. User identity: Clerk ID vs MongoDB _id#

Clerk supplies req.auth.userId like user_2abc.... The Mongo User document is keyed by clerkId (unique, indexed) and has its own _id (ObjectId).

  • getProfile (user.controller.js) auto-creates the user when missing: User.findOne({ clerkId }) → else new User({ clerkId, email, ... }).
  • Many controllers mistakenly pass the Clerk string into User.findById(...) or Stream.find({ creator: clerkString }), causing CastError. These are the broken spots to fix with a single helper:
// utils/auth-utils.js (add this)
export const resolveMongoUserId = async (clerkId) => {
  const user = await User.findOne({ clerkId }).select("_id").lean();
  return user?._id;
};

Wherever a controller stores a reference, use the resolved _id; wherever it just needs the current user's profile, query by clerkId instead of findById.

Affected files (all need the fix):

  • stream.controller.js createStream — stores Clerk string into Stream.creator (ObjectId) → CastError, stream can't be created.
  • follow.controller.js getFollow/getUnfollow — User.findById(followId) with Clerk strings → CastError.
  • profile.controller.js getUserProfile/getUserSettings/updateUserProfile/updateUserSettings — User.findById(userId) where the URL param is a Clerk ID → CastError. (The analytics.controller.js handlers already solve this correctly with a clerkId → _id lookup — copy that pattern.)

3. Environment variables#

Frontend (Frontend/.env)#

Actual vars used by code:

  • VITE_API_URL — base URL for axios (currently http://localhost:5000/api/v1)
  • VITE_CLERK_PUBLISHABLE_KEY — Clerk publishable key (pk_test_...)

Note: Frontend/.env is tracked in git. The publishable key is public by design (safe), but the localhost API URL breaks any non-local deployment. Create Frontend/.env.example and stop tracking .env (the root .gitignore currently does not ignore Frontend/.env).

Backend (backend/src/.env)#

Variables actually consumed by code (from the config files, not just the README):

  • MONGO_URI (db/dbconnect.js)
  • PORT, RTMP_PORT, HLS_PORT (server.js)
  • CORS_ORIGIN (app.js — comma-separated origins)
  • CLERK_SECRET_KEY (@clerk/express)
  • GEMINI_API_KEY (gemini.config.js — returns null/false if absent or "xxxxx")
  • RAZORPAY_KEY_ID, RAZORPAY_SECRET, RAZORPAY_WEBHOOK_SECRET (payment flow)

Note: backend/src/.env exists on disk with real secrets but is not committed (it shows as untracked in git). Add .env.example and confirm .gitignore covers backend/src/.env (the current entry backend/.env does not match backend/src/.env).


4. RBAC / roles#

  • Roles: viewer (default), creator, moderator, admin — stored on User.role.
  • middleware/rbac.js provides requireRole(...roles), requireMinRole(...), requireOwnership(...), loadUserRole (all look users up by req.auth.userId = clerkId — this part is correct).
  • upgradeToCreator (user.controller.js) promotes a viewer → creator; used before POST /streams/create (which requires role creator or admin).
  • Gap: role enforcement exists on routes but user onboarding never prompts role selection, and loadUserRole swallows DB errors silently (proceeds as viewer).

#ProblemFix
1Custom require-Auth.js doesn't verify JWT signatureUse requireAuth() from @clerk/express everywhere; delete custom middleware
2stream.creator gets a Clerk string → CastErrorResolve clerkId → User._id before Stream.create
3Follow/profile controllers findById with Clerk string → CastErrorUse findOne({ clerkId }) or the shared resolver
4GET /auth/settings missing (frontend settingsAPI.getSettings → 404)Add route.get("/settings", requireAuth(), getUserSettings)
5Chat widget (useChatbot.js/useStreamAssistant.js) reads localStorage.getItem("token") which is never set in Clerk flowSwitch to apiClient (which attaches the Clerk Bearer token), or import geminiAPI.chat
6PaymentForm.jsx imports useAuth from @clerk/clerk-react (v5) while the app uses @clerk/react (v6) — both packages installedUninstall one, standardize on @clerk/react
7Socket.IO connections are unauthenticated; send-message trusts client-supplied userIdPass auth: { token } in io(..., { auth }), verify with Clerk in io.use(...); drop the client-supplied userId server-side

6. Diagnostic endpoints (useful for verifying auth)#

  • GET /api/health — backend + MongoDB status
  • GET /api/auth/debug/setup — shows whether Clerk validated the token and what req.auth contains
  • GET /api/v1/analytics/debug/auth — inspects the Authorization header + parsed Clerk auth
  • GET /api/v1/profile/debug — DB connectivity + user count

Example verification flow:

1. Run backend (cd backend/src && npm run dev)
2. Run frontend (cd Frontend && npm run dev), sign in via Clerk
3. Open browser devtools → Network → find a /api/v1/auth/profile request
   → confirm Authorization: Bearer eyJ... present
4. GET http://localhost:5000/api/auth/debug/setup with that token
   → expect tokenValidated: true, clerkUserId: "user_..."

Frontend
  ClerkProvider (@clerk/react) ──getToken()──> apiClient interceptor
      │                                            │
      │ Authorization: Bearer <Clerk JWT>          │
      ▼                                            ▼
Express ──clerkMiddleware()──> req.auth.userId (verified)
  └─ all routes: requireAuth() (@clerk/express)
  └─ RBAC: loadUserRole → requireRole/requireMinRole/requireOwnership
  └─ controllers resolve Clerk ID → Mongo _id via helper
Socket.IO ──io.use(clerkAuth)──> socket.data.userId (verified) → use in send-message

Next: see STREAMING_IMPLEMENTATION.md for the media pipeline that sits behind the auth-protected stream routes.