This document outlines the security features, best practices, and recommendations for Quark applications.
Quark includes several security features out of the box:
X-RateLimit-* headers for client feedbackREDIS_URL is set (shared budget across instances), in-memory when it is unset (single instance). apps/web/src/proxy.js reads REDIS_URL and builds the limiter from the core building block (createRateLimiter({ type: "redis", redisClient }) in packages/core/src/rate-limiter.js), failing closed by default. See Redis-based Rate Limiting below.proxy.js and next.config.js headers(), which acts as the fallback for routes the proxy does not match): X-XSS-Protection is not set; the CSP directive above is what ships.X-Frame-Options: SAMEORIGIN - Prevent clickjackingX-Content-Type-Options: nosniff - Prevent MIME sniffingReferrer-Policy: strict-origin-when-cross-originPermissions-Policy - Restrict browser featuresX-DNS-Prefetch-Control: on - Performance optimizationContent-Security-Policy - Built by apps/web/src/lib/analytics/umami-csp.js; Turbopack's unsafe-eval is added only outside productionStrict-Transport-Security - proxy.js only: next.config.js headers() omits it, so a route the proxy does not match (its matcher excludes _next/static, _next/image, favicon.ico, and image files) gets no HSTS from configAPP_URL; ALLOWED_ORIGINS (comma-separated, production) and NEXT_DEV_ALLOWED_ORIGINS / ALLOWED_DEV_ORIGINS (development hosts) add extras. Resolved in packages/config/src/app-url.jsAPP_URL + http://localhost:3000,http://localhost:3001 in developmenthashPassword(), verifyPassword()prisma.$queryRaw\SELECT 1\` health probes in apps/worker/src/index.js`UnsupportedStrategy when strategy: "database" is set and every provider is credentialsjwt callback re-validates the token against the database on every request (apps/web/src/lib/auth.js). A deleted user's token is rejected and the cookie cleared; the role is refreshed from the row, so demoting an admin takes effect immediately; and any token issued before User.passwordChangedAt is rejected, so changing a password kills every session the old password created. An unreachable database fails closed (session rejected), never open.NEXTAUTH_SECRETThe following environment variables contain sensitive data and must be kept secure:
openssl rand -base64 32POSTGRES_PASSWORDGITHUB_SECRET, GOOGLE_CLIENT_SECRET# ✅ DO: Keep .env files local and gitignored
.env
.env.local
.env.production
# ✅ DO: Use .env.example as template (no secrets)
.env.example
# ❌ DON'T: Commit .env files to git
# ❌ DON'T: Share .env files via chat/email
# ❌ DON'T: Use production secrets in development.env files are gitignoredAll high-priority security tasks have been completed!
/api/csrf to get tokensX-CSRF-Token header in state-changing requests/api/auth/* routesAPI_BODY_SIZE_LIMIT)UPLOAD_SIZE_LIMIT, read by apps/web/src/proxy.js)UPLOAD_MAX_SIZE, read by packages/core/src/file-validation.js). Separate knob from the request-body limit; both default to 10MBapps/web/src/proxy.js reads REDIS_URL: set it and the limiter is Redis-backed (shared budget across instances); leave it unset and it uses in-memory counters (single instance)createRateLimiter({ type: "redis", failOpen: true }) if outage-driven 429s are the bigger risk for you.github/dependabot.yml for this monorepo. Scaffolded projects get their own copy at .github/dependabot.yml plus .github/workflows/dependabot-auto-merge.ymldocs/dependency-audit.mdpnpm-lock.yaml overrides in pnpm-workspace.yaml are audited there and must stay in sync.env files on all environments# Generate new secret
openssl rand -base64 32
# Update .env
NEXTAUTH_SECRET=<new_value>
# Restart application
# All users will be logged out (expected)# 1. Generate new password
# 2. Update database user password
# 3. Update .env with new password
# 4. Restart all servicesIf you discover a security vulnerability, follow the disclosure process in the repository's SECURITY.md. Do not open a public issue.
REDIS_URL now does double duty: it feeds the worker's BullMQ connections and selects the web middleware's rate-limit backend. Set it and apps/web/src/proxy.js builds a shared Redis-backed limiter; leave it unset and the limiter is in-memory, which is correct for a single-instance deployment.
# Set in production .env - consumed by the worker/BullMQ and the web rate limiter
REDIS_URL=redis://your-redis-host:6379
# or for Redis with password
REDIS_URL=redis://:password@your-redis-host:6379No code changes are required. If you need the web layer to talk to Redis through a custom client (TLS, a sentinel topology, an in-process mock), build it and pass it to createRateLimiter directly:
import { createRateLimiter } from "@usequark/quark-core/core";
import { resolveRedisConnection } from "@usequark/quark-core/redis";
import { Redis } from "ioredis";
const limiter = createRateLimiter({
type: "redis",
redisClient: new Redis(resolveRedisConnection()),
});Testing Redis Rate Limiting:
# Start Redis locally
docker run -d -p 6379:6379 redis:7-alpine
# Set environment variable (now also switches the web middleware's limiter)
export REDIS_URL=redis://localhost:6379
# Restart your application
pnpm devWith REDIS_URL set, repeated hits to an API route are counted in Redis rather than in the process, so two instances of the app share one budget.
CSRF tokens are automatically available via the /api/csrf endpoint.
The endpoint mints a token, sets it as an httpOnly SameSite=Strict cookie, and returns the same value in the body. It does not require a session — registration is pre-authentication, so a visitor with no account has to be able to obtain a token before they can register. Because the token in the body is a write credential, every response carries Cache-Control: no-store and Vary: Cookie.
Wrap each mutating route in withCsrfProtection; it compares the x-csrf-token header against the cookie and rejects the request before your handler runs.
Use the bundled helper rather than rolling your own. It fetches the token, caches it, dedupes concurrent callers, and refetches before the cookie's one-hour lifetime runs out:
// components/CreatePost.js
"use client";
import { getCsrfToken } from '@usequark/quark-core/csrf-client';
export function CreatePost() {
const handleSubmit = async (data) => {
const csrfToken = await getCsrfToken();
await fetch('/api/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken
},
body: JSON.stringify(data)
});
};
return <form onSubmit={handleSubmit}>...</form>;
}Import from @usequark/quark-core/csrf-client, not the package root. The root barrel re-exports the server-side csrf.js, which imports node:crypto; reaching the helper through it pulls a Node builtin into the browser bundle and fails the build.
If you keep your own cache, match the cookie's lifetime. A cached token that outlives the one-hour cookie produces Invalid CSRF token, which reads like a header bug rather than staleness. clearCsrfToken() is exported for the other case — the server rotating the cookie underneath the client, e.g. after sign-out.
API client wrapper:
// lib/api-client.js
import { getCsrfToken } from '@usequark/quark-core/csrf-client';
export async function apiPost(url, data) {
const token = await getCsrfToken();
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': token
},
body: JSON.stringify(data)
});
}# Production .env template
NODE_ENV=production
# Database (use managed service credentials)
POSTGRES_HOST=<managed-db-host>
POSTGRES_PASSWORD=<strong-password-from-secret-manager>
DATABASE_URL=<connection-string-with-ssl>
# Redis (use managed service)
# Consumed by the worker/BullMQ connections and by the web middleware's
# rate limiter - setting it makes the limiter Redis-backed (shared budget
# across instances). Leave it unset for in-memory, per-instance counters.
REDIS_URL=<redis-connection-string-with-password>
# Application URL (derives NEXTAUTH_URL and CORS origins)
APP_URL=https://yourdomain.com
# NextAuth
NEXTAUTH_SECRET=<strong-secret-from-vault>
# OAuth (optional - from provider consoles)
# Each provider is enabled by its client id alone. Google also needs the secret
# for the NextAuth sign-in button; the mobile routes need only the client id.
# GITHUB_ID=<production-oauth-id>
# GITHUB_SECRET=<production-oauth-secret>
# GOOGLE_CLIENT_ID=<production-google-client-id>
# GOOGLE_CLIENT_SECRET=<production-google-secret>
# APPLE_CLIENT_ID=com.example.yourapp
# Additional CORS origins (optional - APP_URL is always included)
# ALLOWED_ORIGINS=https://admin.yourdomain.com,https://app.yourdomain.com
# Monitoring
SENTRY_DSN=<sentry-dsn>Last Updated: 13 February 2026