Document 03 / 03
Authentication Guide
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.jsxwraps the app inClerkProvider(from@clerk/react, v6) withVITE_CLERK_PUBLISHABLE_KEY. - Token plumbing: a
ClerkTokenInitcomponent callsuseAuth()and registers the ClerkgetTokenfunction with the API layer viasetClerkTokenProvider(getToken)(defined inFrontend/src/services/apiClient.js). - Request interceptor:
apiClient(axios, baseURLVITE_API_URL) attachesAuthorization: Bearer <token>on every request. It caches the token and refreshes it when it expires within 30s. - Auth context:
Frontend/src/context/auth_context.jsxuses Clerk'suseAuth();isAuthenticated= valid Clerk session. Profile loading is non-blocking. - Route guarding:
ProtectedRoute(components/common/protectedroute.jsx) blocks routes until ClerkisLoadedand 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.
| Middleware | Where used | Verification level |
|---|---|---|
clerkMiddleware() from @clerk/express (app.js:45) | global, populates req.auth for every request | Real — validates JWT signature against Clerk keys |
requireAuth() from @clerk/express | stream.route.js, Social.controller.js | Real — 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.js | WEAK — 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.jscurrently importrequireAuthfrom../middleware/require-Auth.js. Change the import to@clerk/express. Also remove thejwt-decodedependency 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 })→ elsenew User({ clerkId, email, ... }).- Many controllers mistakenly pass the Clerk string into
User.findById(...)orStream.find({ creator: clerkString }), causingCastError. 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.jscreateStream— stores Clerk string intoStream.creator(ObjectId) → CastError, stream can't be created.follow.controller.jsgetFollow/getUnfollow—User.findById(followId)with Clerk strings → CastError.profile.controller.jsgetUserProfile/getUserSettings/updateUserProfile/updateUserSettings—User.findById(userId)where the URL param is a Clerk ID → CastError. (Theanalytics.controller.jshandlers already solve this correctly with aclerkId → _idlookup — copy that pattern.)
3. Environment variables#
Frontend (Frontend/.env)#
Actual vars used by code:
VITE_API_URL— base URL for axios (currentlyhttp://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 onUser.role. middleware/rbac.jsprovidesrequireRole(...roles),requireMinRole(...),requireOwnership(...),loadUserRole(all look users up byreq.auth.userId= clerkId — this part is correct).upgradeToCreator(user.controller.js) promotes a viewer → creator; used beforePOST /streams/create(which requires rolecreatororadmin).- Gap: role enforcement exists on routes but user onboarding never prompts role selection, and
loadUserRoleswallows DB errors silently (proceeds as viewer).
5. Known auth-related bugs & fixes#
| # | Problem | Fix |
|---|---|---|
| 1 | Custom require-Auth.js doesn't verify JWT signature | Use requireAuth() from @clerk/express everywhere; delete custom middleware |
| 2 | stream.creator gets a Clerk string → CastError | Resolve clerkId → User._id before Stream.create |
| 3 | Follow/profile controllers findById with Clerk string → CastError | Use findOne({ clerkId }) or the shared resolver |
| 4 | GET /auth/settings missing (frontend settingsAPI.getSettings → 404) | Add route.get("/settings", requireAuth(), getUserSettings) |
| 5 | Chat widget (useChatbot.js/useStreamAssistant.js) reads localStorage.getItem("token") which is never set in Clerk flow | Switch to apiClient (which attaches the Clerk Bearer token), or import geminiAPI.chat |
| 6 | PaymentForm.jsx imports useAuth from @clerk/clerk-react (v5) while the app uses @clerk/react (v6) — both packages installed | Uninstall one, standardize on @clerk/react |
| 7 | Socket.IO connections are unauthenticated; send-message trusts client-supplied userId | Pass 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 statusGET /api/auth/debug/setup— shows whether Clerk validated the token and whatreq.authcontainsGET /api/v1/analytics/debug/auth— inspects theAuthorizationheader + parsed Clerk authGET /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_..."
7. Recommended auth architecture (target)#
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.