Skip to content

Commit eda5225

Browse files
Merge pull request #21 from muhammadali-imran/main
Fixed for deployment
2 parents 4069017 + 6ff41a0 commit eda5225

16 files changed

Lines changed: 406 additions & 107 deletions

File tree

‎.vercelignore‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
node_modules
22
dist
33
coverage
4-
backend
54
uploads
65
*.log
76
.env

‎backend/.env.example‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ JWT_EXPIRES_DAYS=7
1717
# Defaults to true in production, false otherwise. Must be true when COOKIE_SAMESITE=none.
1818
# COOKIE_SECURE=false
1919
# lax works when the app and API share a site (localhost, or a Vite proxy in dev).
20-
# Use none (with COOKIE_SECURE=true) only if they live on different sites.
20+
# Use none (with COOKIE_SECURE=true) only if they live on different sites (e.g. two
21+
# separate Vercel/Railway domains without a shared parent domain).
2122
COOKIE_SAMESITE=lax
2223
BCRYPT_ROUNDS=12
2324

@@ -50,9 +51,15 @@ UPLOAD_DIR=uploads
5051
# Required when STORAGE_DRIVER=gdrive. Store the whole service-account JSON as one environment value.
5152
# GOOGLE_SERVICE_ACCOUNT_JSON={"type":"service_account",...}
5253
# GOOGLE_DRIVE_FOLDER_ID=your-shared-drive-folder-id
54+
55+
# Optional: use a SECOND Google account/folder for archived recordings, kept separate from
56+
# the base-video account above (different service account and/or different Drive account).
57+
# When unset, ARCHIVE_STORAGE_DRIVER=gdrive falls back to the shared credentials above.
58+
# GOOGLE_ARCHIVE_SERVICE_ACCOUNT_JSON={"type":"service_account",...}
59+
# GOOGLE_ARCHIVE_DRIVE_FOLDER_ID=the-second-account-folder-id
60+
5361
MAX_VIDEO_UPLOAD_MB=300
5462
MAX_RECORDING_UPLOAD_MB=100
55-
SUBMISSION_COOLDOWN_MS=30000
5663

5764
RATE_LIMIT_ENABLED=true
5865

‎backend/package.json‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,29 +16,20 @@
1616
},
1717
"dependencies": {
1818
"@getbrevo/brevo": "^6.0.3",
19-
"axios": "^1.20.0",
2019
"bcrypt": "^6.0.0",
21-
"bcryptjs": "^2.4.3",
2220
"compression": "^1.8.2",
2321
"cookie-parser": "^1.4.7",
2422
"cors": "^2.8.6",
2523
"dotenv": "^16.6.1",
2624
"express": "^4.22.3",
2725
"express-rate-limit": "^8.7.0",
28-
"express-validator": "^7.2.1",
29-
"fs-extra": "^11.4.1",
3026
"googleapis": "^182.0.0",
3127
"helmet": "^8.3.0",
3228
"jsonwebtoken": "^9.0.3",
3329
"mongoose": "^7.8.12",
34-
"morgan": "^1.10.0",
3530
"multer": "^2.4.0",
36-
"openapi-client-axios": "^7.9.0",
37-
"pg": "^8.13.1",
38-
"pg-hstore": "^2.3.4",
3931
"pino": "^10.3.1",
4032
"pino-http": "^11.0.0",
41-
"sequelize": "^6.37.5",
4233
"swagger-ui-express": "^5.0.1",
4334
"zod": "^4.6.5"
4435
},

‎backend/server.js‎

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,26 @@
11
import app from './src/app.js'
2-
import { connectDb, disconnectDb } from './src/config/db.js'
32
import { env } from './src/config/env.js'
4-
import { authService } from './src/services/authService.js'
5-
import { storageService } from './src/services/storage/index.js'
3+
import { initServices } from './src/services/initialization.js'
64
import { logger } from './src/utils/logger.js'
75

8-
async function start() {
9-
await connectDb()
10-
await storageService.init()
11-
await authService.ensureAdminFromEnv()
6+
// Vercel serverless handler export
7+
async function handler(req, res) {
8+
return app(req, res)
9+
}
1210

13-
const server = app.listen(env.PORT, () => logger.info(`API listening on http://localhost:${env.PORT}`))
11+
// Standalone execution (Railway / Docker / Local Node)
12+
// Ignore process.env.VERCEL if running via direct `node server.js` command
13+
const PORT = env.PORT || process.env.PORT || 5000
1414

15-
let closing = false
16-
const shutdown = async (signal) => {
17-
if (closing) return
18-
closing = true
19-
logger.info({ signal }, 'Shutting down')
20-
server.close(async () => {
21-
await disconnectDb()
22-
process.exit(0)
23-
})
24-
setTimeout(() => process.exit(1), 10_000).unref() // do not hang forever on open connections
25-
}
26-
process.on('SIGINT', () => shutdown('SIGINT'))
27-
process.on('SIGTERM', () => shutdown('SIGTERM'))
28-
}
15+
const server = app.listen(PORT, '0.0.0.0', () => {
16+
console.log(`==================================================`)
17+
console.log(`API SERVER LISTENING ON http://0.0.0.0:${PORT}`)
18+
console.log(`==================================================`)
19+
})
2920

30-
process.on('unhandledRejection', (reason) => { logger.fatal({ err: reason }, 'Unhandled rejection'); process.exit(1) })
21+
// Trigger background initialization immediately after port binding
22+
initServices().catch((error) => {
23+
console.error('[BOOT ERROR] Service initialization failed on boot:', error.message)
24+
})
3125

32-
start().catch((error) => { logger.fatal({ err: error }, 'Failed to start'); process.exit(1) })
26+
export default handler

‎backend/src/app.js‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { env } from './config/env.js'
1010
import { openapi } from './docs/openapi.js'
1111
import { errorHandler, notFoundHandler } from './middlewares/errorHandler.js'
1212
import { enforceAccessRestrictions } from './middlewares/enforceAccessRestrictions.js'
13+
import { ensureServicesInitialized } from './services/initialization.js'
1314
import { apiLimiter } from './middlewares/rateLimiter.js'
1415
import { verifyOrigin } from './middlewares/verifyOrigin.js'
1516
import routes from './routes/index.js'
@@ -19,7 +20,9 @@ import swaggerUi from 'swagger-ui-express'
1920
const app = express()
2021

2122
app.disable('x-powered-by')
22-
if (env.TRUST_PROXY) app.set('trust proxy', 1) // needed behind nginx/Render/Heroku so rate limits see real IPs
23+
if (env.TRUST_PROXY) app.set('trust proxy', 1) // needed behind nginx/Render/Railway so rate limits see real IPs
24+
25+
app.use(ensureServicesInitialized)
2326

2427
// Request logging with an id that is also sent back, so a support report can be matched to a log line.
2528
app.use(pinoHttp({
@@ -40,13 +43,17 @@ app.get('/', (req, res) => res.json({ data: {
4043
name: 'SignPak Commons API',
4144
api: API_PREFIX,
4245
health: `${API_PREFIX}/health`,
43-
docs: '/docs',
46+
docs: env.isProduction ? `${API_PREFIX}/docs.json` : '/docs',
4447
} }))
4548
app.get('/favicon.ico', (req, res) => res.status(204).end())
49+
// The raw OpenAPI JSON has no filesystem dependency, so it stays available in every
50+
// environment; only the interactive Swagger UI (below) is gated out of production.
4651
app.get('/docs.json', (req, res) => res.json(openapi))
4752
app.get('/api-docs.json', (req, res) => res.json(openapi))
48-
app.use('/docs', swaggerUi.serve, swaggerUi.setup(openapi, { explorer: true }))
49-
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(openapi, { explorer: true }))
53+
if (!env.isProduction) {
54+
app.use('/docs', swaggerUi.serve, swaggerUi.setup(openapi, { explorer: true }))
55+
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(openapi, { explorer: true }))
56+
}
5057

5158
app.use(API_PREFIX, apiLimiter, verifyOrigin, enforceAccessRestrictions, routes)
5259

‎backend/src/config/env.js‎

Lines changed: 60 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,64 @@
1-
import 'dotenv/config'
1+
import fs from 'node:fs'
2+
import path from 'node:path'
3+
import { config } from 'dotenv'
24
import { z } from 'zod'
35

4-
const bool = z.union([z.boolean(), z.enum(['true', 'false']).transform((value) => value === 'true')])
6+
const bool = z.union([
7+
z.boolean(),
8+
z.enum(['true', 'false']).transform((value) => value === 'true'),
9+
])
10+
11+
const explicitEnv = { ...process.env }
12+
const dotEnvPath = path.resolve(process.cwd(), '.env')
13+
const dotEnv = fs.existsSync(dotEnvPath)
14+
? config({ path: dotEnvPath, override: false }).parsed ?? {}
15+
: {}
16+
17+
const mergedEnv = { ...dotEnv, ...explicitEnv }
18+
const isTest = (explicitEnv.NODE_ENV ?? dotEnv.NODE_ENV ?? 'development') === 'test'
19+
20+
const testSafeEnv = isTest
21+
? {
22+
...mergedEnv,
23+
COOKIE_SECURE: explicitEnv.COOKIE_SECURE ?? 'false',
24+
COOKIE_SAMESITE: explicitEnv.COOKIE_SAMESITE ?? 'lax',
25+
STORAGE_DRIVER: explicitEnv.STORAGE_DRIVER ?? 'local',
26+
ARCHIVE_STORAGE_DRIVER: explicitEnv.ARCHIVE_STORAGE_DRIVER ?? 'local',
27+
RATE_LIMIT_ENABLED: explicitEnv.RATE_LIMIT_ENABLED ?? 'false',
28+
}
29+
: mergedEnv
530

631
const schema = z.object({
732
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
833
PORT: z.coerce.number().int().positive().default(5000),
934
LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'),
1035
TRUST_PROXY: bool.default(false),
1136

12-
MONGODB_URI: z.string({ error: 'MONGODB_URI is required (for example mongodb://127.0.0.1:27017/signpakcommons)' }).min(1, 'MONGODB_URI is required'),
37+
MONGODB_URI: z.string().min(1, 'MONGODB_URI is required'),
1338

1439
// Comma-separated list of browser origins allowed to call the API with cookies.
1540
CLIENT_ORIGIN: z.string().default('http://localhost:5173'),
1641

17-
JWT_SECRET: z.string({ error: 'JWT_SECRET is required. Generate one with: node -e "console.log(require(\'crypto\').randomBytes(48).toString(\'hex\'))"' }).min(32, 'JWT_SECRET must be at least 32 characters. Generate one with: node -e "console.log(require(\'crypto\').randomBytes(48).toString(\'hex\'))"'),
42+
JWT_SECRET: z.string().min(32, 'JWT_SECRET must be at least 32 characters.'),
1843
JWT_EXPIRES_DAYS: z.coerce.number().positive().default(7),
1944
COOKIE_SECURE: bool.optional(),
2045
COOKIE_SAMESITE: z.enum(['lax', 'strict', 'none']).default('lax'),
2146
BCRYPT_ROUNDS: z.coerce.number().int().min(4).max(15).default(12),
47+
2248
BREVO_API_KEY: z.string().optional(),
23-
BREVO_SENDER_EMAIL: z.email().optional(),
49+
BREVO_SENDER_EMAIL: z.string().email('BREVO_SENDER_EMAIL must be a valid email').optional().or(z.literal('')),
2450
BREVO_SENDER_NAME: z.string().min(1).default('SignPak Commons'),
2551
AUTH_OTP_TTL_MINUTES: z.coerce.number().int().min(1).max(30).default(5),
2652
AUTH_OTP_RESEND_SECONDS: z.coerce.number().int().min(0).max(3600).default(60),
2753
AUTH_OTP_MAX_ATTEMPTS: z.coerce.number().int().min(1).max(10).default(5),
54+
2855
WEB3FORMS_ACCESS_KEY: z.string().optional(),
2956
CONTACT_DAILY_LIMIT: z.coerce.number().int().min(1).default(25),
3057
CONTACT_USER_DAILY_LIMIT: z.coerce.number().int().min(1).default(1),
3158
CONTACT_ABUSE_BLOCK_MINUTES: z.coerce.number().int().min(1).max(1440).default(10),
3259

33-
ADMIN_EMAIL: z.email({ error: 'ADMIN_EMAIL is required and must be a valid email' }),
34-
ADMIN_PASSWORD: z.string({ error: 'ADMIN_PASSWORD is required (at least 8 characters)' }).min(8, 'ADMIN_PASSWORD must be at least 8 characters').max(72),
60+
ADMIN_EMAIL: z.string().email('ADMIN_EMAIL must be a valid email'),
61+
ADMIN_PASSWORD: z.string().min(8, 'ADMIN_PASSWORD must be at least 8 characters').max(72),
3562
ADMIN_FIRST_NAME: z.string().min(1).default('Admin'),
3663
ADMIN_SURNAME: z.string().min(1).default('Signpak'),
3764

@@ -40,47 +67,53 @@ const schema = z.object({
4067
UPLOAD_DIR: z.string().default('uploads'),
4168
GOOGLE_SERVICE_ACCOUNT_JSON: z.string().optional(),
4269
GOOGLE_DRIVE_FOLDER_ID: z.string().optional(),
70+
GOOGLE_ARCHIVE_SERVICE_ACCOUNT_JSON: z.string().optional(),
71+
GOOGLE_ARCHIVE_DRIVE_FOLDER_ID: z.string().optional(),
4372
MAX_VIDEO_UPLOAD_MB: z.coerce.number().positive().default(300),
4473
MAX_RECORDING_UPLOAD_MB: z.coerce.number().positive().default(100),
4574

4675
RATE_LIMIT_ENABLED: bool.default(true),
47-
48-
// A contributor can submit a video more than once, but not back to back: this is the
49-
// minimum gap enforced between two submissions for the same (user, video). Overridable
50-
// (like BCRYPT_ROUNDS) so tests do not have to wait 30 real seconds.
5176
SUBMISSION_COOLDOWN_MS: z.coerce.number().int().positive().default(30_000),
5277
}).superRefine((data, context) => {
53-
if (data.NODE_ENV === 'production' && !data.BREVO_API_KEY) {
54-
context.addIssue({ code: 'custom', path: ['BREVO_API_KEY'], message: 'Required in production for email verification and password reset.' })
55-
}
56-
if (data.NODE_ENV === 'production' && !data.BREVO_SENDER_EMAIL) {
57-
context.addIssue({ code: 'custom', path: ['BREVO_SENDER_EMAIL'], message: 'Required in production; use a verified Brevo sender address.' })
58-
}
59-
if (data.NODE_ENV === 'production' && !data.WEB3FORMS_ACCESS_KEY) {
60-
context.addIssue({ code: 'custom', path: ['WEB3FORMS_ACCESS_KEY'], message: 'Required in production to deliver contact messages.' })
78+
if (data.NODE_ENV === 'production') {
79+
if (!data.BREVO_API_KEY) {
80+
context.addIssue({ code: 'custom', path: ['BREVO_API_KEY'], message: 'Required in production for email verification and password reset.' })
81+
}
82+
if (!data.BREVO_SENDER_EMAIL) {
83+
context.addIssue({ code: 'custom', path: ['BREVO_SENDER_EMAIL'], message: 'Required in production; use a verified Brevo sender address.' })
84+
}
85+
if (!data.WEB3FORMS_ACCESS_KEY) {
86+
context.addIssue({ code: 'custom', path: ['WEB3FORMS_ACCESS_KEY'], message: 'Required in production to deliver contact messages.' })
87+
}
6188
}
6289
const needsGoogle = data.STORAGE_DRIVER === 'gdrive' || data.ARCHIVE_STORAGE_DRIVER === 'gdrive'
63-
if (needsGoogle && !data.GOOGLE_SERVICE_ACCOUNT_JSON) {
64-
context.addIssue({ code: 'custom', path: ['GOOGLE_SERVICE_ACCOUNT_JSON'], message: 'Required when STORAGE_DRIVER=gdrive.' })
65-
}
66-
if (needsGoogle && !data.GOOGLE_DRIVE_FOLDER_ID) {
67-
context.addIssue({ code: 'custom', path: ['GOOGLE_DRIVE_FOLDER_ID'], message: 'Required when STORAGE_DRIVER=gdrive.' })
90+
if (needsGoogle) {
91+
if (!data.GOOGLE_SERVICE_ACCOUNT_JSON) {
92+
context.addIssue({ code: 'custom', path: ['GOOGLE_SERVICE_ACCOUNT_JSON'], message: 'Required when STORAGE_DRIVER=gdrive.' })
93+
}
94+
if (!data.GOOGLE_DRIVE_FOLDER_ID) {
95+
context.addIssue({ code: 'custom', path: ['GOOGLE_DRIVE_FOLDER_ID'], message: 'Required when STORAGE_DRIVER=gdrive.' })
96+
}
6897
}
6998
})
7099

71-
const parsed = schema.safeParse(process.env)
100+
const parsed = schema.safeParse(testSafeEnv)
101+
72102
if (!parsed.success) {
73103
const lines = parsed.error.issues.map((issue) => ` - ${issue.path.join('.') || 'env'}: ${issue.message}`)
74-
console.error(`\nInvalid environment configuration:\n${lines.join('\n')}\n\nCopy .env.example to .env and fill in the values.\n`)
104+
console.error('\n==================================================')
105+
console.error('FATAL ENVIRONMENT CONFIGURATION ERROR:')
106+
console.error(lines.join('\n'))
107+
console.error('==================================================\n')
75108
process.exit(1)
76109
}
77110

78111
const data = parsed.data
112+
79113
export const env = Object.freeze({
80114
...data,
81115
isProduction: data.NODE_ENV === 'production',
82116
isTest: data.NODE_ENV === 'test',
83-
// Secure cookies by default in production; override for local HTTPS-less setups.
84117
COOKIE_SECURE: data.COOKIE_SECURE ?? data.NODE_ENV === 'production',
85118
clientOrigins: data.CLIENT_ORIGIN.split(',').map((item) => item.trim().replace(/\/$/, '')).filter(Boolean),
86119
})

‎backend/src/routes/index.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Router } from 'express'
22
import swaggerUi from 'swagger-ui-express'
33
import { isDbReady } from '../config/db.js'
4+
import { env } from '../config/env.js'
45
import { openapi } from '../docs/openapi.js'
56
import adminRoutes from './adminRoutes.js'
67
import authRoutes from './authRoutes.js'
@@ -19,7 +20,12 @@ router.get('/health', (req, res) => {
1920
})
2021

2122
router.get('/docs.json', (req, res) => res.json(openapi))
22-
router.use('/docs', swaggerUi.serve, swaggerUi.setup(openapi, { explorer: true }))
23+
// Kept out of production: swagger-ui-express serves bundled static assets from disk, and
24+
// exposing the full interactive API surface publicly isn't worth it once this is live.
25+
// /docs.json above still works everywhere for tooling that needs the raw spec.
26+
if (!env.isProduction) {
27+
router.use('/docs', swaggerUi.serve, swaggerUi.setup(openapi, { explorer: true }))
28+
}
2329

2430
router.use('/auth', authRoutes)
2531
router.use('/users', userRoutes)

‎backend/src/routes/videoRoutes.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@ router.get('/', optionalAuthenticate, videoController.list)
1717
router.get('/:id', optionalAuthenticate, validate({ params: idParams }), videoController.get)
1818
router.get('/:id/poster', optionalAuthenticate, validate({ params: idParams }), videoController.poster)
1919

20-
// Published video files are public reference media; unpublished/admin media still requires visibility checks in the service.
20+
// Published video files are public reference media; unpublished/admin media still requires
21+
// visibility checks in the service, which optionalAuthenticate + findVisible() already cover
22+
// for both anonymous and logged-in requesters, so a single route handles every case.
2123
router.get('/:id/file', optionalAuthenticate, validate({ params: idParams }), videoController.file)
22-
router.get('/:id/file', authenticate, validate({ params: idParams }), videoController.file)
2324

2425
// Order matters: log in, check role, then accept the upload, then validate the text fields that came with it.
2526
router.post('/', ...adminOnly, uploadLimiter, videoUpload, validate({ body: createVideoSchema }), videoController.create)

‎backend/src/services/accessRestrictionService.js‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@ import { createHash } from 'node:crypto'
22
import { AccessRestriction } from '../models/AccessRestriction.js'
33
import { conflict, notFound } from '../utils/AppError.js'
44

5-
const hash = (value) => createHash('sha256').update(value.trim().toLowerCase()).digest('hex')
5+
// Guarded against undefined/empty input: req.ip can be undefined if TRUST_PROXY is ever
6+
// misconfigured behind a host's proxy, and this used to throw (value.trim() on undefined),
7+
// turning every /api/v1/* request into a 500. An empty value still hashes safely; it just
8+
// means "no IP could be determined" shares one bucket, which is a fine degraded fallback
9+
// as long as TRUST_PROXY is set correctly in normal operation.
10+
const hash = (value) => createHash('sha256').update(String(value || '').trim().toLowerCase()).digest('hex')
611

712
function hint(type, value) {
813
if (type === 'ip') {
@@ -69,4 +74,4 @@ export const accessRestrictionService = {
6974
}
7075
}
7176
},
72-
}
77+
}

‎backend/src/services/authService.js‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,20 +85,30 @@ export const authService = {
8585
return { user, token: signToken(user.id, user.authVersion || 0) }
8686
},
8787

88+
/**
89+
* Resend and password-reset both used to `await issueOtp(...)`, which calls out to Brevo.
90+
* An unknown email returned instantly (no user, nothing to await); a known email waited on
91+
* the network call. That timing gap let someone enumerate registered emails just by timing
92+
* the response, even though the response body is identical either way (see authController,
93+
* which always returns the same generic message). Firing the OTP issuance in the background
94+
* closes that gap: both cases now return at roughly the same speed.
95+
*/
8896
async resendVerification(email) {
8997
const user = await userRepo.findByEmail(email, { withOtp: true })
9098
if (!user || user.emailVerified) return false
9199
const sentAt = user.emailVerificationSentAt?.getTime() || 0
92100
if (Date.now() - sentAt < env.AUTH_OTP_RESEND_SECONDS * 1000) return false
93-
return this.issueOtp(user, 'email-verification')
101+
void this.issueOtp(user, 'email-verification').catch((error) => logger.error({ err: error }, 'Could not issue verification OTP'))
102+
return true
94103
},
95104

96105
async requestPasswordReset(email) {
97106
const user = await userRepo.findByEmail(email, { withOtp: true })
98107
if (!user) return false
99108
const sentAt = user.passwordResetSentAt?.getTime() || 0
100109
if (Date.now() - sentAt < env.AUTH_OTP_RESEND_SECONDS * 1000) return false
101-
return this.issueOtp(user, 'password-reset')
110+
void this.issueOtp(user, 'password-reset').catch((error) => logger.error({ err: error }, 'Could not issue password reset OTP'))
111+
return true
102112
},
103113

104114
async resetPassword({ email, code, password }) {

0 commit comments

Comments
 (0)