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
4 changes: 4 additions & 0 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ RUN mkdir -p /app/uploads/documents
# Make startup script executable
RUN chmod +x /app/scripts/start.sh

# Run as non-root user (node user already exists in node:20-alpine)
RUN chown -R node:node /app
USER node

# Expose port
EXPOSE 4000

Expand Down
12 changes: 11 additions & 1 deletion backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"nodemailer": "^6.9.7",
"openai": "^6.15.0",
"pdfkit": "^0.15.0",
"resend": "^3.5.0"
"resend": "^3.5.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/cors": "^2.8.17",
Expand Down
22 changes: 22 additions & 0 deletions backend/src/middleware/validate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Request, Response, NextFunction } from 'express';
import { ZodSchema, ZodError } from 'zod';

/**
* Express middleware that validates req.body against a Zod schema.
* On success, replaces req.body with the parsed (and stripped) data.
* On failure, returns 400 with structured validation errors.
*/
export function validate(schema: ZodSchema) {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req.body);
if (!result.success) {
const formatted = (result.error as ZodError).flatten();
return res.status(400).json({
error: 'Validation failed',
details: formatted.fieldErrors,
});
}
req.body = result.data;
next();
};
}
16 changes: 8 additions & 8 deletions backend/src/routes/access.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import express from 'express';
import { supabase } from '../server';
import fs from 'fs';
import path from 'path';
import { logActivity } from '../utils/activityLogger';

const UPLOADS_DIR = process.env.UPLOADS_DIR || '/app/uploads';
import { resolveUploadPath } from '../utils/safePath';

const router = express.Router();

Expand Down Expand Up @@ -36,7 +34,7 @@
}

// Fetch the documents separately using the document_ids array
let documents: any[] = [];

Check warning on line 37 in backend/src/routes/access.ts

View workflow job for this annotation

GitHub Actions / Backend Build & Test

Unexpected any. Specify a different type
if (request.document_ids && request.document_ids.length > 0) {
const { data: docs, error: docsError } = await supabase
.from('documents')
Expand Down Expand Up @@ -65,7 +63,8 @@
});
} catch (error: any) {
console.error('Access route error:', error.message);
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down Expand Up @@ -112,8 +111,7 @@
// agreed to NDA terms when submitting the document request form

// Serve from local storage (consistent with documents.ts)
// Adjust path if file_url is relative
const filePath = path.join(UPLOADS_DIR, document.file_url);
const filePath = resolveUploadPath(document.file_url);

if (!fs.existsSync(filePath)) {
// In demo mode, generate a placeholder file since Railway's filesystem is ephemeral
Expand Down Expand Up @@ -161,7 +159,8 @@

return res.sendFile(filePath);
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down Expand Up @@ -202,7 +201,8 @@
res.json({ message: 'NDA Accepted successfully' });

} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down
31 changes: 16 additions & 15 deletions backend/src/routes/admin/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,23 @@ router.get('/', requireAdmin, async (req, res) => {
throw error;
}

// Fetch document details for each request separately
const requestsWithDocs = await Promise.all(
(data || []).map(async (request) => {
let documents: { id: string; title: string }[] = [];

if (request.document_ids && request.document_ids.length > 0) {
const { data: docs } = await supabase
.from('documents')
.select('id, title')
.in('id', request.document_ids);
documents = docs || [];
}
// Batch-fetch all referenced documents in a single query
const allDocIds = [...new Set((data || []).flatMap(r => r.document_ids || []))];
let docMap = new Map<string, { id: string; title: string }>();
if (allDocIds.length > 0) {
const { data: allDocs } = await supabase
.from('documents')
.select('id, title')
.in('id', allDocIds);
docMap = new Map((allDocs || []).map(d => [d.id, d]));
}

return { ...request, documents };
})
);
const requestsWithDocs = (data || []).map(request => ({
...request,
documents: (request.document_ids || [])
.map((id: string) => docMap.get(id))
.filter(Boolean),
}));

res.json(requestsWithDocs);
} catch (error: any) {
Expand Down
21 changes: 14 additions & 7 deletions backend/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import { supabase } from '../server';
import { requireAdmin, AuthRequest } from '../middleware/auth';
import { logActivity } from '../utils/activityLogger';
import { emailRateLimit } from '../middleware/rateLimit';
import { validate } from '../middleware/validate';
import { loginSchema, signupSchema } from '../schemas/auth';

const router = express.Router();

// Admin signup (for initial setup)
router.post('/signup', emailRateLimit, async (req, res) => {
router.post('/signup', emailRateLimit, validate(signupSchema), async (req, res) => {
try {
const { email, password, full_name } = req.body;
const allowAdminSignup = process.env.ALLOW_ADMIN_SIGNUP === 'true';
Expand Down Expand Up @@ -81,12 +83,13 @@ router.post('/signup', emailRateLimit, async (req, res) => {
message: 'Admin user created successfully',
});
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

// Admin login
router.post('/login', emailRateLimit, async (req, res) => {
router.post('/login', emailRateLimit, validate(loginSchema), async (req, res) => {
try {
const { email, password } = req.body;

Expand Down Expand Up @@ -173,7 +176,8 @@ router.post('/login', emailRateLimit, async (req, res) => {
session: data.session,
});
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand All @@ -194,7 +198,8 @@ router.post('/logout', requireAdmin, async (req: AuthRequest, res) => {
await supabase.auth.signOut();
res.json({ message: 'Logged out successfully' });
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand All @@ -215,7 +220,8 @@ router.post('/logout/auto', requireAdmin, async (req: AuthRequest, res) => {
await supabase.auth.signOut();
res.json({ message: 'Auto-logged out due to inactivity' });
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand All @@ -224,7 +230,8 @@ router.get('/session', requireAdmin, async (req: AuthRequest, res) => {
try {
res.json({ authenticated: true, admin: req.admin });
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down
12 changes: 8 additions & 4 deletions backend/src/routes/categories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ router.get('/', async (req, res) => {

res.json(categoriesWithCount);
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down Expand Up @@ -78,7 +79,8 @@ router.post('/', requireAdmin, async (req: AuthRequest, res) => {

res.status(201).json(data);
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down Expand Up @@ -120,7 +122,8 @@ router.patch('/:id', requireAdmin, async (req: AuthRequest, res) => {

res.json(data);
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down Expand Up @@ -157,7 +160,8 @@ router.delete('/:id', requireAdmin, async (req: AuthRequest, res) => {

res.json({ message: 'Category deleted successfully' });
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down
15 changes: 10 additions & 5 deletions backend/src/routes/certifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ router.get('/', async (req, res) => {

res.json(data);
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down Expand Up @@ -56,7 +57,8 @@ router.post('/', requireAdmin, async (req: AuthRequest, res) => {

res.status(201).json(data);
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand All @@ -79,7 +81,8 @@ router.patch('/reorder', requireAdmin, async (req: AuthRequest, res) => {

res.json({ message: 'Reordered successfully' });
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down Expand Up @@ -121,7 +124,8 @@ router.patch('/:id', requireAdmin, async (req: AuthRequest, res) => {

res.json(data);
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down Expand Up @@ -158,7 +162,8 @@ router.delete('/:id', requireAdmin, async (req: AuthRequest, res) => {

res.json({ message: 'Certification deleted successfully' });
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down
12 changes: 11 additions & 1 deletion backend/src/routes/contact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import express from 'express';
import { supabase } from '../server';
import { emailRateLimit } from '../middleware/rateLimit';
import { validateEmailAddress } from '../utils/emailValidation';
import { notifyAdminsOfNewTicket } from '../utils/adminNotifications';

const router = express.Router();

Expand Down Expand Up @@ -55,9 +56,18 @@ router.post('/', emailRateLimit, async (req, res) => {

if (error) throw error;

// Notify admins of new support ticket (if tickets enabled)
notifyAdminsOfNewTicket({
name: trimmedName,
email: trimmedEmail,
organization: trimmedOrganization,
subject: trimmedSubject,
}).catch(err => console.error('Failed to send ticket notification:', err));

res.status(201).json({ success: true, message: 'Contact form submitted successfully' });
} catch (error: any) {
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down
6 changes: 4 additions & 2 deletions backend/src/routes/controls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ router.get('/control-categories', async (req, res) => {
res.json(data || []);
} catch (error: any) {
console.error('Get control categories error:', error);
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand All @@ -31,7 +32,8 @@ router.get('/controls', async (req, res) => {
res.json(data || []);
} catch (error: any) {
console.error('Get controls error:', error);
res.status(500).json({ error: error.message });
console.error('Route error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

Expand Down
Loading
Loading