Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ jobs:

dashboard-api-tests:
runs-on: ubuntu-latest
services:
redis:
image: redis:7-alpine
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 5
permissions:
contents: read
steps:
Expand All @@ -44,6 +54,8 @@ jobs:

- name: Run Dashboard API Tests
run: npm run test --workspace=dashboard-api
env:
REDIS_URL: redis://localhost:6379
Comment thread
coderabbitai[bot] marked this conversation as resolved.

public-api-tests:
runs-on: ubuntu-latest
Expand Down
19 changes: 19 additions & 0 deletions apps/dashboard-api/src/__tests__/routes.user.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,25 @@ jest.mock('../controllers/pat.controller', () => ({
revokePAT: jest.fn((_req, res) => res.json({ success: true }))
}));

jest.mock('../middlewares/authenticateCLI', () =>
jest.fn((req, _res, next) => {
req.user = { _id: 'mock_user_id', id: 'mock_user_id' };
req.cliScopes = ['read', 'write'];
next();
})
);

jest.mock('../middlewares/authFlexible', () =>
jest.fn((req, _res, next) => {
req.user = { _id: 'mock_user_id', id: 'mock_user_id' };
next();
})
);

jest.mock('../controllers/cli.controller', () => ({
getCLIProfile: jest.fn((_req, res) => res.json({ success: true, data: {} }))
}));

const express = require('express');
const request = require('supertest');
const userRouter = require('../routes/user');
Expand Down
7 changes: 5 additions & 2 deletions apps/dashboard-api/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,18 @@ const csrfProtection = csurf({
}
});

// AFTER
app.use((req, res, next) => {
// Exclude Razorpay webhook from CSRF protection since it's an external POST request
if (req.path === '/api/billing/webhook') {
// Exclude CLI routes — CLI authenticates via Bearer PAT, not cookies
const isCliRoute =
req.path === '/api/user/cli' || req.path.startsWith('/api/user/cli/');
if (req.path === '/api/billing/webhook' || isCliRoute) {
return next();
}
csrfProtection(req, res, next);
});


if (process.env.NODE_ENV !== 'test') {
garbageCollect();
storageGarbageCollect();
Expand Down
28 changes: 28 additions & 0 deletions apps/dashboard-api/src/controllers/cli.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { Developer, ApiResponse, AppError } = require("@urbackend/common");

module.exports.getCLIProfile = async (req, res, next) => {
try {
const developer = await Developer.findById(req.user._id)
.select("email plan githubUsername avatarUrl");

if (!developer) {
return next(new AppError(404, "Developer not found"));
}

return new ApiResponse({
developer: {
id: developer._id,
email: developer.email,
plan: developer.plan,
githubUsername: developer.githubUsername,
avatarUrl: developer.avatarUrl,
},
auth: {
scopes: req.cliScopes,
tokenType: req.cliTokenType,
},
}).send(res);
} catch (err) {
next(err);
}
};
1 change: 1 addition & 0 deletions apps/dashboard-api/src/controllers/pat.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,4 @@ exports.revokePAT = async (req, res, next) => {
return next(new AppError(500, "An error occurred while revoking the token"));
}
};

19 changes: 19 additions & 0 deletions apps/dashboard-api/src/middlewares/authFlexible.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const authMiddleware = require('./authMiddleware');
const authenticateCLI = require('./authenticateCLI');

/**
* Flexible auth middleware — accepts either:
* - Session cookie (browser dashboard)
* - Bearer PAT token (CLI)
*/
const authFlexible = (req, res, next) => {
const authHeader = req.headers.authorization;

if (authHeader && authHeader.startsWith('Bearer ubpat_')) {
return authenticateCLI(req, res, next);
}

return authMiddleware(req, res, next);
};

module.exports = authFlexible;
Comment thread
yash-pouranik marked this conversation as resolved.
11 changes: 5 additions & 6 deletions apps/dashboard-api/src/middlewares/authMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,10 @@ module.exports = function (req, res, next) {

// Proceed to the next middleware or route handler
next();
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
Comment thread
yash-pouranik marked this conversation as resolved.

return next(new AppError(401, 'Invalid Token'));
} catch (err) {
if (process.env.NODE_ENV !== 'test') {
console.error(err);
}
return next(new AppError(401, "Invalid Token"));
}
};
2 changes: 1 addition & 1 deletion apps/dashboard-api/src/middlewares/authenticateCLI.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ const authenticateCLI = async (req, res, next) => {
).catch(err => console.error("Failed to update PAT metadata:", err));

// Attach developer and PAT scopes for downstream controllers
req.user = { id: developer._id.toString() }; // Maintain compatibility with dashboard controllers
req.user = { _id: developer._id.toString(), id: developer._id.toString() }; // Maintain compatibility with dashboard controllers
req.developer = developer;
req.cliScopes = matchedPat.scopes;
req.cliTokenType = matchedPat.type;
Expand Down
5 changes: 3 additions & 2 deletions apps/dashboard-api/src/routes/analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ const express = require("express");
const router = express.Router();
const analyticsController = require("../controllers/analytics.controller");
const authMiddleware = require("../middlewares/authMiddleware");
const authFlexible = require("../middlewares/authFlexible");

router.get("/stats", authMiddleware, analyticsController.getGlobalStats);
router.get("/activity", authMiddleware, analyticsController.getRecentActivity);
router.get("/stats", authFlexible, analyticsController.getGlobalStats);
router.get("/activity", authFlexible, analyticsController.getRecentActivity);
Comment thread
yash-pouranik marked this conversation as resolved.

// --- Metrics Stack ---
router.get("/funnel", authMiddleware, analyticsController.getActivationFunnel);
Expand Down
Empty file.
7 changes: 4 additions & 3 deletions apps/dashboard-api/src/routes/projects.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const authorizeProject = require('../middlewares/authorizeProject');
const { verifyEmail, checkAuthEnabled, loadProjectForAdmin } = require('@urbackend/common');
const multer = require('multer');
const storage = multer.memoryStorage();
const authFlexible = require('../middlewares/authFlexible');

const {
createProject,
Expand Down Expand Up @@ -61,15 +62,15 @@ const exportController = require('../controllers/dbExport.controller');

// POST REQ FOR CREATE PROJECT
router.post('/', authMiddleware, planEnforcement.attachDeveloper, planEnforcement.checkProjectLimit, planEnforcement.checkDeveloperCapability('createProject'), createProject);
router.get('/', authMiddleware, getAllProject);
router.get('/:projectId', authMiddleware, authorizeProject(), getSingleProject);
router.get('/', authFlexible, getAllProject);
router.get('/:projectId', authFlexible, authorizeProject(), getSingleProject);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
router.post('/:projectId/api-key', authMiddleware, authorizeProject('admin'), verifyEmail, regenerateApiKey);
router.post('/:projectId/reveal-secret-key', authMiddleware, authorizeProject('admin'), verifyEmail, revealSecretKey);

router.post('/:projectId/collections', authMiddleware, authorizeProject('admin'), planEnforcement.attachDeveloper, planEnforcement.checkCollectionLimit, createCollection);

// DELETE REQ FOR COLLECTION
router.delete('/:projectId/collections/:collectionName', authMiddleware, authorizeProject('admin'), verifyEmail, deleteCollection);
router.delete('/:projectId/collections/:collectionName', authFlexible, authorizeProject('admin'), verifyEmail, deleteCollection);

// GET REQ FOR DATA
router.get('/:projectId/collections/:collectionName/data', authMiddleware, authorizeProject(), getData);
Expand Down
3 changes: 3 additions & 0 deletions apps/dashboard-api/src/routes/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ const router = express.Router();
const authorization = require('../middlewares/authMiddleware');
const { getMe, updateOnboarding } = require('../controllers/auth.controller');
const { createPAT, listPATs, revokePAT } = require('../controllers/pat.controller');
const authenticateCLI = require("../middlewares/authenticateCLI");
const {getCLIProfile,} = require("../controllers/cli.controller");

router.get("/cli/me", authenticateCLI, getCLIProfile);
router.get('/me', authorization, getMe);
router.patch('/onboarding', authorization, updateOnboarding);

Expand Down
Loading
Loading