Bug fixes (real breakage):

Newsletter nudge — was calling /api/study-account/profile (wrong endpoint, ignored subscription). Now correctly calls /api/study-account/preferences with PATCH.
Security:

Email regex — replaced the permissive [^\s@]+@[^\s@]+ pattern with a proper RFC-compliant regex in contact.js and downloads.js
Avatar magic bytes — server now checks actual PNG/JPEG/GIF/WEBP header bytes, not just the data URL prefix
Certificate rate limit — public /api/public/certificate/:token now has a 30 req/15min limiter
Session absolute TTL — admin sessions now have a 30-day hard cap; a stolen token can no longer be kept alive indefinitely by passive reads
Account lockout — 5 failed logins locks a study account for 1 hour
CSP headers — Content-Security-Policy, X-Frame-Options, X-Content-Type-Options, and Referrer-Policy headers added globally
Data integrity:

Cascade delete — deleting a study account now also removes their certificates, community posts, comments, and progress file
UX / reliability:

Escape key on modals — all 3 modal groups (study index, notes, account) now close on Escape
Display name min-length — empty spaces-only names rejected; if provided, must be ≥2 chars
Note save rate limit — 30 saves/minute per user max
Analytics fetch timeout — 5s AbortController so a hanging server doesn't block the browser indefinitely
Email validation on signup — frontend catches bad email formats before hitting the server
Cleanup:

Deduplicated download forms — StudyDownloadForm and ResourceDownloadForm now share a single DownloadForm base; both are now thin wrappers
This commit is contained in:
nmemmert
2026-06-18 09:35:44 -04:00
parent fda9fa27a6
commit 9174331d2d
10 changed files with 145 additions and 110 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
{
"users": {},
"updatedAt": "2026-06-17T16:26:39.085Z"
"updatedAt": "2026-06-18T11:26:38.001Z"
}
+20
View File
@@ -60,6 +60,26 @@ app.use(express.json({ limit: '10mb' }))
const trustProxyHops = Number(process.env.TRUST_PROXY_HOPS ?? 1)
app.set('trust proxy', Number.isFinite(trustProxyHops) && trustProxyHops >= 0 ? trustProxyHops : 1)
app.use((_req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff')
res.setHeader('X-Frame-Options', 'SAMEORIGIN')
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin')
res.setHeader(
'Content-Security-Policy',
[
"default-src 'self'",
"script-src 'self' 'unsafe-inline'",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src 'self' https://fonts.gstatic.com",
"img-src 'self' data: https:",
"media-src 'self' https:",
"frame-src https:",
"connect-src 'self' https:",
].join('; '),
)
next()
})
// Register API routes
registerAdminAuth(app)
registerAdminContent(app)
+13 -4
View File
@@ -15,6 +15,7 @@ const totpPendingSessions = new Map()
const ADMIN_SESSION_COOKIE = 'vbn_admin_session'
const ADMIN_SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000
const ADMIN_SESSION_ABSOLUTE_TTL_MS = 30 * 24 * 60 * 60 * 1000
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD
const adminSessions = new Map()
@@ -217,7 +218,8 @@ export function consumePendingSession(token) {
export function createAdminSession() {
const token = randomUUID()
adminSessions.set(token, Date.now() + ADMIN_SESSION_TTL_MS)
const now = Date.now()
adminSessions.set(token, { expiresAt: now + ADMIN_SESSION_TTL_MS, absoluteExpiresAt: now + ADMIN_SESSION_ABSOLUTE_TTL_MS })
return token
}
@@ -234,13 +236,20 @@ export function isValidAdminSession(req) {
const sessionToken = cookies[ADMIN_SESSION_COOKIE]
if (!sessionToken) return false
const expiresAt = adminSessions.get(sessionToken)
if (!expiresAt || expiresAt <= Date.now()) {
const now = Date.now()
const session = adminSessions.get(sessionToken)
if (!session) return false
// Support legacy sessions stored as a plain number (expiresAt)
const expiresAt = typeof session === 'object' ? session.expiresAt : session
const absoluteExpiresAt = typeof session === 'object' ? session.absoluteExpiresAt : Infinity
if (expiresAt <= now || absoluteExpiresAt <= now) {
adminSessions.delete(sessionToken)
return false
}
adminSessions.set(sessionToken, Date.now() + ADMIN_SESSION_TTL_MS)
adminSessions.set(sessionToken, { expiresAt: now + ADMIN_SESSION_TTL_MS, absoluteExpiresAt })
return true
}
+2 -2
View File
@@ -98,7 +98,7 @@ export function register(app) {
if (lastName !== undefined && lastName !== null && (typeof lastName !== 'string' || lastName.trim().length > 100)) {
res.status(400).json({ message: 'Last name is too long.' }); return
}
if (!email || typeof email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
if (!email || typeof email !== 'string' || !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(email.trim())) {
res.status(400).json({ message: 'A valid email address is required.' }); return
}
if (!message || typeof message !== 'string' || message.trim().length < 5 || message.trim().length > 3000) {
@@ -470,7 +470,7 @@ export function register(app) {
if (!submission) {
res.status(404).json({ message: 'Submission not found.' }); return
}
if (!submission.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(submission.email)) {
if (!submission.email || !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(submission.email)) {
res.status(400).json({ message: 'Submission does not have a valid email address.' }); return
}
+2 -2
View File
@@ -67,7 +67,7 @@ export function register(app) {
if (!lastName || typeof lastName !== 'string' || lastName.trim().length < 1 || lastName.trim().length > 100) {
res.status(400).json({ message: 'Last name is required.' }); return
}
if (!email || typeof email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
if (!email || typeof email !== 'string' || !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(email.trim())) {
res.status(400).json({ message: 'A valid email address is required.' }); return
}
@@ -175,7 +175,7 @@ export function register(app) {
if (!lastName || typeof lastName !== 'string' || lastName.trim().length < 1 || lastName.trim().length > 100) {
res.status(400).json({ message: 'Last name is required.' }); return
}
if (!email || typeof email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
if (!email || typeof email !== 'string' || !/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(email.trim())) {
res.status(400).json({ message: 'A valid email address is required.' }); return
}
+30
View File
@@ -8,11 +8,15 @@ import { UPLOADS_DIR, EMAIL_CHANGE_TOKEN_TTL_MS } from '../config.js'
import { state } from '../state.js'
import {
queueStudyUsersWrite,
queueStudyCommunityWrite,
queueStudyCommentsWrite,
queueStudyCertificatesWrite,
readUploadsMetadata,
writeUploadsMetadata,
loadUserNotes,
loadUserProgress,
getUserNotesFilePath,
getUserProgressFilePath,
} from '../data.js'
import {
requireStudyAuth,
@@ -259,6 +263,17 @@ export function register(app) {
return
}
const isValidImageBytes = (
(buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) || // JPEG
(buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47) || // PNG
(buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) || // GIF
(buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46) // WEBP (RIFF)
)
if (!isValidImageBytes) {
res.status(400).json({ message: 'Upload must be a valid PNG, JPG, WEBP, or GIF image.' })
return
}
const baseName = normalizeAssetBaseName(filename.replace(/\.[a-z0-9]+$/i, ''))
const finalName = `${baseName || 'avatar'}-${Date.now()}${ext}`
@@ -444,6 +459,21 @@ export function register(app) {
state.studyNotesCache.delete(user.id)
try { await unlink(getUserNotesFilePath(user.id)) } catch { /* no notes file is fine */ }
state.studyProgressCache.delete(user.id)
try { await unlink(getUserProgressFilePath(user.id)) } catch { /* no progress file is fine */ }
const beforeCerts = state.studyCertificates.length
state.studyCertificates = state.studyCertificates.filter(c => c.userId !== user.id)
if (state.studyCertificates.length !== beforeCerts) queueStudyCertificatesWrite()
const beforePosts = state.studyCommunityPosts.length
state.studyCommunityPosts = state.studyCommunityPosts.filter(p => p.authorUserId !== user.id)
if (state.studyCommunityPosts.length !== beforePosts) queueStudyCommunityWrite()
const beforeComments = state.studyComments.length
state.studyComments = state.studyComments.filter(c => c.userId !== user.id)
if (state.studyComments.length !== beforeComments) queueStudyCommentsWrite()
sendStudyAccountDeletedEmail(deletedEmail, deletedDisplayName).catch(err => {
console.error('[study-account] delete email error:', err)
})
+10 -1
View File
@@ -1,9 +1,18 @@
import { randomUUID } from 'node:crypto'
import rateLimit from 'express-rate-limit'
import { requireAdminAuth } from '../auth.js'
import { requireStudyAuth, normalizeStudySlug, isStudyUserEnrolled, getStudyTitleBySlug } from '../study-helpers.js'
import { state } from '../state.js'
import { loadUserProgress, queueStudyCertificatesWrite } from '../data.js'
const publicCertRateLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 30,
standardHeaders: true,
legacyHeaders: false,
message: { message: 'Too many certificate lookups. Please wait a moment.' },
})
/**
* Returns the list of required section IDs for a study (only released sections).
*/
@@ -92,7 +101,7 @@ export function register(app) {
})
// GET — public certificate page data (no auth, by token)
app.get('/api/public/certificate/:token', (req, res) => {
app.get('/api/public/certificate/:token', publicCertRateLimiter, (req, res) => {
const { token } = req.params
if (!token || typeof token !== 'string' || token.length > 100) {
res.status(400).json({ message: 'Invalid token.' }); return
+17
View File
@@ -23,6 +23,19 @@ import {
import { MAX_STUDY_NOTE_LENGTH, MAX_STUDY_NOTES_PER_USER, MAX_STUDY_ENROLLMENTS_PER_USER } from '../config.js'
import { randomUUID } from 'node:crypto'
const noteSaveHits = new Map() // userId -> { count, windowStart }
const NOTE_RATE_WINDOW_MS = 60 * 1000
const NOTE_RATE_MAX = 30
function checkNoteSaveRateLimit(userId) {
const now = Date.now()
const entry = noteSaveHits.get(userId) ?? { count: 0, windowStart: now }
if (now - entry.windowStart > NOTE_RATE_WINDOW_MS) { entry.count = 0; entry.windowStart = now }
entry.count += 1
noteSaveHits.set(userId, entry)
return entry.count <= NOTE_RATE_MAX
}
export function register(app) {
// ── Enrollment ────────────────────────────────────────────────────────────
@@ -112,6 +125,10 @@ export function register(app) {
return
}
const user = req.studyUser
if (!checkNoteSaveRateLimit(user.id)) {
res.status(429).json({ message: 'Too many note saves. Please slow down.' })
return
}
const noteStudySlug = getStudySlugFromNoteId(sectionId)
if (noteStudySlug && !isStudyUserEnrolled(user, noteStudySlug)) {
res.status(403).json({ message: 'Please enroll in this study to save notes.' })
+15 -98
View File
@@ -29,12 +29,15 @@ function usePageTracking() {
useEffect(() => {
if (localStorage.getItem(CONSENT_KEY) !== 'accepted') return
const referrer = document.referrer || ''
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 5000)
fetch('/api/analytics/pageview', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: location.pathname, referrer }),
keepalive: true,
}).catch(() => {})
signal: controller.signal,
}).catch(() => {}).finally(() => clearTimeout(timeout))
}, [location.pathname])
}
@@ -150,13 +153,12 @@ function HeadlinerWidget() {
)
}
function StudyDownloadForm({ buttonText = 'Download Guide' }: { buttonText?: string }) {
function DownloadForm({ endpoint, extraBody, buttonText }: { endpoint: string; extraBody?: Record<string, string>; buttonText: string }) {
const [fields, setFields] = useState({ firstName: '', lastName: '', email: '' })
const [subscribe, setSubscribe] = useState(true)
const [honey, setHoney] = useState('')
const [status, setStatus] = useState<'idle' | 'submitting' | 'error' | 'success'>('idle')
const [errorMsg, setErrorMsg] = useState('')
const [successMsg, setSuccessMsg] = useState('')
const [downloadUrl, setDownloadUrl] = useState('')
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
@@ -167,14 +169,13 @@ function StudyDownloadForm({ buttonText = 'Download Guide' }: { buttonText?: str
e.preventDefault()
setStatus('submitting')
setErrorMsg('')
setSuccessMsg('')
setDownloadUrl('')
try {
const res = await fetch('/api/study-downloads/titus', {
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...fields, subscribe, _honey: honey }),
body: JSON.stringify({ ...extraBody, ...fields, subscribe, _honey: honey }),
})
const data = await res.json().catch(() => ({})) as { message?: string; downloadUrl?: string }
@@ -185,7 +186,6 @@ function StudyDownloadForm({ buttonText = 'Download Guide' }: { buttonText?: str
}
setStatus('success')
setSuccessMsg('Your download should start now. If not, use the link below.')
setDownloadUrl(data.downloadUrl)
window.location.assign(data.downloadUrl)
} catch {
@@ -228,10 +228,10 @@ function StudyDownloadForm({ buttonText = 'Download Guide' }: { buttonText?: str
<span>Subscribe me to updates from Verse by Verse with Nate.</span>
</label>
{status === 'error' && <p className="contact-error">{errorMsg}</p>}
{status === 'success' && <p className="study-download-success">{successMsg}</p>}
{status === 'success' && downloadUrl && (
{status === 'success' && (
<p className="study-download-success">
<a href={downloadUrl}>Click here if your download does not start automatically.</a>
Your download should start now.{' '}
{downloadUrl && <a href={downloadUrl}>Click here if it does not start automatically.</a>}
</p>
)}
<button type="submit" className="btn-primary" disabled={status === 'submitting'}>
@@ -241,95 +241,12 @@ function StudyDownloadForm({ buttonText = 'Download Guide' }: { buttonText?: str
)
}
function StudyDownloadForm({ buttonText = 'Download Guide' }: { buttonText?: string }) {
return <DownloadForm endpoint="/api/study-downloads/titus" buttonText={buttonText} />
}
function ResourceDownloadForm({ resourceId, buttonText }: { resourceId: string; buttonText: string }) {
const [fields, setFields] = useState({ firstName: '', lastName: '', email: '' })
const [subscribe, setSubscribe] = useState(true)
const [honey, setHoney] = useState('')
const [status, setStatus] = useState<'idle' | 'submitting' | 'error' | 'success'>('idle')
const [errorMsg, setErrorMsg] = useState('')
const [successMsg, setSuccessMsg] = useState('')
const [downloadUrl, setDownloadUrl] = useState('')
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
setFields(f => ({ ...f, [e.target.name]: e.target.value }))
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setStatus('submitting')
setErrorMsg('')
setSuccessMsg('')
setDownloadUrl('')
try {
const res = await fetch('/api/resource-download', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ resourceId, ...fields, subscribe, _honey: honey }),
})
const data = await res.json().catch(() => ({})) as { message?: string; downloadUrl?: string }
if (!res.ok || !data.downloadUrl) {
setErrorMsg(data.message ?? 'Could not process your request. Please try again.')
setStatus('error')
return
}
setStatus('success')
setSuccessMsg('Your download should start now. If not, use the link below.')
setDownloadUrl(data.downloadUrl)
window.location.assign(data.downloadUrl)
} catch {
setErrorMsg('Could not connect. Please try again later.')
setStatus('error')
}
}
return (
<form className="study-download-form" onSubmit={handleSubmit} noValidate>
<input
type="text"
className="contact-honeypot"
tabIndex={-1}
autoComplete="off"
aria-hidden="true"
value={honey}
onChange={e => setHoney(e.target.value)}
/>
<div className="study-download-grid">
<label>
First Name
<input type="text" name="firstName" required autoComplete="given-name" value={fields.firstName} onChange={handleChange} />
</label>
<label>
Last Name
<input type="text" name="lastName" required autoComplete="family-name" value={fields.lastName} onChange={handleChange} />
</label>
<label>
Email
<input type="email" name="email" required autoComplete="email" value={fields.email} onChange={handleChange} />
</label>
</div>
<label className="contact-consent">
<input
type="checkbox"
checked={subscribe}
onChange={e => setSubscribe(e.target.checked)}
/>
<span>Subscribe me to updates from Verse by Verse with Nate.</span>
</label>
{status === 'error' && <p className="contact-error">{errorMsg}</p>}
{status === 'success' && <p className="study-download-success">{successMsg}</p>}
{status === 'success' && downloadUrl && (
<p className="study-download-success">
<a href={downloadUrl}>Click here if your download does not start automatically.</a>
</p>
)}
<button type="submit" className="btn-primary" disabled={status === 'submitting'}>
{status === 'submitting' ? 'Preparing Download...' : buttonText}
</button>
</form>
)
return <DownloadForm endpoint="/api/resource-download" extraBody={{ resourceId }} buttonText={buttonText} />
}
function buildCustomResourceDownloadId(id: string) {
+35 -2
View File
@@ -521,6 +521,15 @@ export function StudyLandingPage({ content }: Props) {
setEnrollMessage('')
}
useEffect(() => {
if (studyModal === 'none') return
function onKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') closeStudyModal()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [studyModal])
useEffect(() => {
let cancelled = false
@@ -697,9 +706,11 @@ export function StudyLandingPage({ content }: Props) {
<div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
<button type="button" className="btn-primary" style={{ fontSize: '0.85rem', padding: '0.4rem 1rem' }} onClick={async () => {
try {
await fetch('/api/study-account/profile', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ subscribeNewsletter: true }) })
await fetch('/api/study-account/preferences', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ subscribeNewsletter: true, studyRemindersEnabled: auth.studyRemindersEnabled === true }) })
setAuth(prev => ({ ...prev, subscribeNewsletter: true }))
} catch {}
} catch {
// Silently continue — preference will sync on next account load
}
setNewsletterNudgeDone(true)
setShowNewsletterNudge(false)
}}>Yes, subscribe me</button>
@@ -928,6 +939,10 @@ export function StudySignupPage() {
setMessage('Please enter your email and password.')
return
}
if (!/^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,253}\.[a-zA-Z]{2,}$/.test(email.trim())) {
setMessage('Please enter a valid email address.')
return
}
setBusy(true)
setMessage('')
try {
@@ -1523,6 +1538,15 @@ export function ColossiansStudySectionPage({ content }: Props) {
setNotesModalOpen(false)
}
useEffect(() => {
if (!notesModalOpen) return
function onKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') closeNotesModal()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [notesModalOpen])
function appendSelectedTextToNotes(selectedText: string) {
if (!selectedText.trim()) return
setNoteText(prev => prev ? `${prev.trim()}\n\n${selectedText.trim()}` : selectedText.trim())
@@ -2500,6 +2524,15 @@ export function StudyAccountPage() {
setEnrollMessage('')
}
useEffect(() => {
if (accountModal === 'none') return
function onKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') closeAccountModal()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [accountModal])
if (!auth.checked) {
return (
<main className="thanks-page" aria-label="Loading">