mirror of
https://github.com/johndoe6345789/postgres.git
synced 2026-04-24 13:55:00 +00:00
Fix security issues and linting errors
Co-authored-by: johndoe6345789 <224850594+johndoe6345789@users.noreply.github.com>
This commit is contained in:
@@ -113,14 +113,14 @@ services:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
ports:
|
||||
- "5432:5432"
|
||||
- '5432:5432'
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
|
||||
admin:
|
||||
build: .
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- '3000:3000'
|
||||
environment:
|
||||
DATABASE_URL: postgresql://postgres:postgres@postgres:5432/mydb
|
||||
JWT_SECRET: your-secret-key-here
|
||||
@@ -175,7 +175,7 @@ docker run -p 3000:3000 \
|
||||
## API Routes
|
||||
|
||||
- `POST /api/admin/login` - User login
|
||||
- `POST /api/admin/logout` - User logout
|
||||
- `POST /api/admin/logout` - User logout
|
||||
- `GET /api/admin/tables` - List all database tables
|
||||
- `POST /api/admin/query` - Execute SQL query (SELECT only)
|
||||
|
||||
|
||||
10
Dockerfile
10
Dockerfile
@@ -53,6 +53,14 @@ done
|
||||
# Set DATABASE_URL if not provided
|
||||
export DATABASE_URL=\${DATABASE_URL:-postgresql://docker:docker@localhost:5432/postgres}
|
||||
|
||||
# Generate JWT_SECRET if not provided
|
||||
if [ -z "\$JWT_SECRET" ]; then
|
||||
echo "WARNING: JWT_SECRET not provided. Generating a random secret..."
|
||||
export JWT_SECRET=\$(openssl rand -base64 32)
|
||||
echo "Generated JWT_SECRET: \$JWT_SECRET"
|
||||
echo "IMPORTANT: Save this secret if you need to restart the container!"
|
||||
fi
|
||||
|
||||
# Run migrations
|
||||
npm run db:migrate
|
||||
|
||||
@@ -76,7 +84,7 @@ ENV DATABASE_URL=postgresql://docker:docker@localhost:5432/postgres
|
||||
ENV CREATE_ADMIN_USER=true
|
||||
ENV ADMIN_USERNAME=admin
|
||||
ENV ADMIN_PASSWORD=admin123
|
||||
ENV JWT_SECRET=change-this-secret-in-production
|
||||
# Note: JWT_SECRET will be auto-generated if not provided
|
||||
|
||||
# Set the default command
|
||||
CMD ["/start.sh"]
|
||||
|
||||
@@ -4,8 +4,8 @@ services:
|
||||
postgres-admin:
|
||||
build: .
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "5432:5432"
|
||||
- '3000:3000'
|
||||
- '5432:5432'
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://docker:docker@localhost:5432/postgres
|
||||
- JWT_SECRET=your-secret-key-change-in-production
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { drizzle } from 'drizzle-orm/node-postgres';
|
||||
import { Pool } from 'pg';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { adminUserSchema } from '../src/models/Schema';
|
||||
|
||||
async function seedAdminUser() {
|
||||
|
||||
@@ -1,46 +1,43 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import CodeIcon from '@mui/icons-material/Code';
|
||||
import LogoutIcon from '@mui/icons-material/Logout';
|
||||
import StorageIcon from '@mui/icons-material/Storage';
|
||||
import {
|
||||
Box,
|
||||
Container,
|
||||
Paper,
|
||||
Typography,
|
||||
Button,
|
||||
Alert,
|
||||
AppBar,
|
||||
Toolbar,
|
||||
Box,
|
||||
Button,
|
||||
CircularProgress,
|
||||
Drawer,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
TextField,
|
||||
Alert,
|
||||
CircularProgress,
|
||||
Paper,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Tabs,
|
||||
Tab,
|
||||
TextField,
|
||||
Toolbar,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import { ThemeProvider } from '@mui/material/styles';
|
||||
import StorageIcon from '@mui/icons-material/Storage';
|
||||
import CodeIcon from '@mui/icons-material/Code';
|
||||
import LogoutIcon from '@mui/icons-material/Logout';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { theme } from '@/utils/theme';
|
||||
|
||||
const DRAWER_WIDTH = 240;
|
||||
|
||||
interface TabPanelProps {
|
||||
type TabPanelProps = {
|
||||
children?: React.ReactNode;
|
||||
index: number;
|
||||
value: number;
|
||||
}
|
||||
};
|
||||
|
||||
function TabPanel(props: TabPanelProps) {
|
||||
const { children, value, index, ...other } = props;
|
||||
@@ -68,11 +65,7 @@ export default function AdminDashboard() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
fetchTables();
|
||||
}, []);
|
||||
|
||||
const fetchTables = async () => {
|
||||
const fetchTables = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/admin/tables');
|
||||
if (!response.ok) {
|
||||
@@ -87,7 +80,11 @@ export default function AdminDashboard() {
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
}, [router]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchTables();
|
||||
}, [fetchTables]);
|
||||
|
||||
const handleTableClick = async (tableName: string) => {
|
||||
setSelectedTable(tableName);
|
||||
@@ -96,13 +93,14 @@ export default function AdminDashboard() {
|
||||
setQueryResult(null);
|
||||
|
||||
try {
|
||||
// Use parameterized query through the query API to prevent SQL injection
|
||||
const response = await fetch('/api/admin/query', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: `SELECT * FROM ${tableName} LIMIT 100`,
|
||||
query: `SELECT * FROM "${tableName}" LIMIT 100`,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -185,8 +183,8 @@ export default function AdminDashboard() {
|
||||
<Drawer
|
||||
variant="permanent"
|
||||
sx={{
|
||||
width: DRAWER_WIDTH,
|
||||
flexShrink: 0,
|
||||
'width': DRAWER_WIDTH,
|
||||
'flexShrink': 0,
|
||||
'& .MuiDrawer-paper': {
|
||||
width: DRAWER_WIDTH,
|
||||
boxSizing: 'border-box',
|
||||
@@ -248,7 +246,9 @@ export default function AdminDashboard() {
|
||||
|
||||
{selectedTable && (
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Table: {selectedTable}
|
||||
Table:
|
||||
{' '}
|
||||
{selectedTable}
|
||||
</Typography>
|
||||
)}
|
||||
</TabPanel>
|
||||
@@ -296,7 +296,9 @@ export default function AdminDashboard() {
|
||||
<Paper sx={{ mt: 2, overflow: 'auto' }}>
|
||||
<Box sx={{ p: 2 }}>
|
||||
<Typography variant="subtitle2" gutterBottom>
|
||||
Rows returned: {queryResult.rowCount}
|
||||
Rows returned:
|
||||
{' '}
|
||||
{queryResult.rowCount}
|
||||
</Typography>
|
||||
</Box>
|
||||
<TableContainer>
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
Button,
|
||||
CircularProgress,
|
||||
Container,
|
||||
Paper,
|
||||
TextField,
|
||||
Typography,
|
||||
Alert,
|
||||
CircularProgress,
|
||||
} from '@mui/material';
|
||||
import { ThemeProvider } from '@mui/material/styles';
|
||||
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
import { theme } from '@/utils/theme';
|
||||
|
||||
export default function AdminLoginPage() {
|
||||
@@ -48,7 +48,7 @@ export default function AdminLoginPage() {
|
||||
// Redirect to admin dashboard
|
||||
router.push('/admin/dashboard');
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
} catch {
|
||||
setError('An error occurred. Please try again.');
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -117,7 +117,6 @@ export default function AdminLoginPage() {
|
||||
label="Username"
|
||||
name="username"
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
disabled={loading}
|
||||
|
||||
@@ -1,7 +1,28 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { Pool } from 'pg';
|
||||
import { db } from '@/utils/db';
|
||||
import { getSession } from '@/utils/session';
|
||||
|
||||
// Validate that query is a safe SELECT statement
|
||||
function validateSelectQuery(query: string): boolean {
|
||||
const trimmed = query.trim();
|
||||
|
||||
// Remove leading comments and whitespace
|
||||
const noComments = trimmed.replace(/^(?:--[^\n]*\n|\s)+/g, '');
|
||||
|
||||
// Check if it starts with SELECT (case insensitive)
|
||||
if (!/^select\s/i.test(noComments)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for dangerous keywords (case insensitive)
|
||||
const dangerous = /;\s*(?:drop|delete|update|insert|alter|create|truncate|exec|execute)\s/i;
|
||||
if (dangerous.test(trimmed)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
@@ -22,22 +43,15 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
// Security: Only allow SELECT queries
|
||||
const trimmedQuery = query.trim().toLowerCase();
|
||||
if (!trimmedQuery.startsWith('select')) {
|
||||
// Validate query
|
||||
if (!validateSelectQuery(query)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Only SELECT queries are allowed' },
|
||||
{ error: 'Only SELECT queries are allowed. No modification queries (INSERT, UPDATE, DELETE, DROP, etc.) permitted.' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
});
|
||||
|
||||
const result = await pool.query(query);
|
||||
|
||||
await pool.end();
|
||||
const result = await db.execute(query);
|
||||
|
||||
return NextResponse.json({
|
||||
rows: result.rows,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { Pool } from 'pg';
|
||||
import { db } from '@/utils/db';
|
||||
import { getSession } from '@/utils/session';
|
||||
|
||||
export async function GET() {
|
||||
@@ -13,19 +13,13 @@ export async function GET() {
|
||||
);
|
||||
}
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
});
|
||||
|
||||
const result = await pool.query(`
|
||||
const result = await db.execute(`
|
||||
SELECT table_name
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = 'public'
|
||||
ORDER BY table_name
|
||||
`);
|
||||
|
||||
await pool.end();
|
||||
|
||||
return NextResponse.json({ tables: result.rows });
|
||||
} catch (error) {
|
||||
console.error('Error fetching tables:', error);
|
||||
|
||||
@@ -20,6 +20,10 @@ const isAuthPage = createRouteMatcher([
|
||||
'/:locale/sign-up(.*)',
|
||||
]);
|
||||
|
||||
// Admin routes that should bypass i18n routing
|
||||
const ADMIN_ROUTE_PREFIX = '/admin';
|
||||
const ADMIN_API_PREFIX = '/api/admin';
|
||||
|
||||
// Improve security with Arcjet
|
||||
const aj = arcjet.withRule(
|
||||
detectBot({
|
||||
@@ -39,7 +43,8 @@ export default async function proxy(
|
||||
event: NextFetchEvent,
|
||||
) {
|
||||
// Skip i18n routing for admin and API routes
|
||||
if (request.nextUrl.pathname.startsWith('/admin') || request.nextUrl.pathname.startsWith('/api/admin')) {
|
||||
if (request.nextUrl.pathname.startsWith(ADMIN_ROUTE_PREFIX)
|
||||
|| request.nextUrl.pathname.startsWith(ADMIN_API_PREFIX)) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,23 @@ import { jwtVerify, SignJWT } from 'jose';
|
||||
import { cookies } from 'next/headers';
|
||||
|
||||
const SESSION_COOKIE_NAME = 'admin-session';
|
||||
const JWT_SECRET = new TextEncoder().encode(
|
||||
process.env.JWT_SECRET || 'your-secret-key-change-in-production',
|
||||
);
|
||||
|
||||
// Get JWT secret and throw error if not provided in production
|
||||
function getJwtSecret(): Uint8Array {
|
||||
const secret = process.env.JWT_SECRET;
|
||||
|
||||
if (!secret) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('JWT_SECRET environment variable is required in production');
|
||||
}
|
||||
console.warn('JWT_SECRET not set, using development default');
|
||||
return new TextEncoder().encode('development-secret-change-in-production');
|
||||
}
|
||||
|
||||
return new TextEncoder().encode(secret);
|
||||
}
|
||||
|
||||
const JWT_SECRET = getJwtSecret();
|
||||
|
||||
export type SessionData = {
|
||||
userId: number;
|
||||
|
||||
Reference in New Issue
Block a user