feat: add first-run admin setup

This commit is contained in:
i vib committed 2026-10-25 06:12:47 -07:00
1 parent dd2fc71867
commit 2aaa9335e3
16 files changed
+644 -152

No files matched your search

+5 -3
View File
@@ -2,12 +2,14 @@
GEMINI_API_KEY="MY_GEMINI_API_KEY"
APP_URL="MY_APP_URL"
# Coolify auto-generates these four secrets from docker-compose.yml magic variables:
# Coolify auto-generates these values from docker-compose.yml magic variables:
# SERVICE_HEX_32_DATABASENAME
# SERVICE_PASSWORD_64_POSTGRES
# SERVICE_REALBASE64_64_JWT
# SERVICE_REALBASE64_64_ADMINSESSION
# SERVICE_PASSWORDWITHSYMBOLS_64_ADMIN
# SERVICE_REALBASE64_64_ADMININSTALL
# They are not entered here. JWT/session/admin secrets can be rotated in Coolify.
# PostgreSQL password rotation also requires changing the DB role password in the running database.
# PostgreSQL name/password are generated once and persist. Password rotation also requires changing the DB role.
# The install key is required only for the first admin setup; setup closes after first account creation.
# The only required manual value for Coolify is the administrator's email:
DATASTACK_ADMIN_EMAIL=
+4 -2
View File
@@ -54,10 +54,12 @@ The repository includes a Docker Compose stack for a Coolify Git-based Docker Co
1. In Coolify, add a Docker Compose application from `https://gitlab.com/ivibtools/datastack.git`, branch `main`.
2. Set Base Directory to `/` and Docker Compose Location to `docker/docker-compose.yml`.
3. Set `DATASTACK_ADMIN_EMAIL` in the application's Environment Variables. Coolify auto-generates the PostgreSQL password, JWT secret, admin session secret, and admin password from the `SERVICE_*` variables in Compose. No secret value needs to be pasted into the Compose file. The database URL is assembled internally using the generated PostgreSQL password. JWT/session/admin secrets can be rotated in Coolify; rotating the PostgreSQL password also requires updating the database role in the already-initialized database volume.
3. Set `DATASTACK_ADMIN_EMAIL` in the application's Environment Variables. Coolify auto-generates the database name/password, JWT/session secrets, and one-time setup key from the `SERVICE_*` variables in Compose. `DATABASE_URL` is assembled internally from the generated database name/password. Do not override generated database identity values after first deployment.
4. In Domains, add the public HTTPS domain to service `proxy` on internal port `80`. Do not expose `web`, `ingestion`, Redis, or PostgreSQL directly. Coolify supplies proxy labels for the selected service.
5. Deploy and check service health and runtime logs in Coolify.
The proxy sends `/` to Next.js and `/socket.io/` to the Socket.IO service over the private Compose network. The Settings page uses the current origin for a deployed WebSocket URL; local development on port 3000 still displays port 4000.
After deployment, copy the generated `SERVICE_PASSWORDWITHSYMBOLS_64_ADMIN` value from Coolify's Environment Variables when signing into the admin console. The `datastack-data` named volume persists CSVs written by ingestion. The web process does not yet read that volume; Redis and Prisma/PostgreSQL are not yet used by application code. Cross-process event visibility/shared storage remains Phase P4 work and metadata persistence remains Phase P5 work. Coolify deployment does not resolve those production-readiness gaps, and this stack has not yet been built or deployed on a Coolify VPS from this environment.
After deployment, open the first-run setup page. Copy the generated `SERVICE_REALBASE64_64_ADMININSTALL` key from Coolify into the setup form, confirm the `DATASTACK_ADMIN_EMAIL` configured for this deployment, and choose a strong password. The server accepts only that configured email, and initial admin setup closes permanently after the first account is stored.
Compose mounts PostgreSQL's `pgdata` named volume, which is intended to survive normal rebuilds/redeploys; never remove the volume or change the generated database name to “reset” the app. Back up `pgdata` before database upgrades or maintenance. Changing the PostgreSQL password also requires updating the existing database role, not just its environment variable. The setup/login code uses PostgreSQL for the bootstrap admin credential only; Prisma-backed client/settings metadata remains P5 work. The `datastack-data` volume persists ingestion CSVs, but the web process does not yet read that volume; cross-process event visibility/shared storage remains P4. This stack has not yet been built or deployed on a Coolify VPS from this environment, so volume persistence still needs target-runtime verification.
+11 -2
View File
@@ -3,8 +3,17 @@ import { Features } from '@/components/sections/Features';
import { Hero } from '@/components/sections/Hero';
import { LandingAbout } from '@/components/sections/LandingAbout';
import { SdkSection } from '@/components/sections/SdkSection';
import { isAdminSetupComplete } from '@/core/auth/adminUsers';
import { redirect } from 'next/navigation';
export const dynamic = 'force-dynamic';
export default async function LandingPage() {
if (process.env.NODE_ENV === 'production' && process.env.DATABASE_URL) {
const isConfigured = await isAdminSetupComplete().catch(() => false);
if (!isConfigured) redirect('/vcon/setup');
}
export default function LandingPage() {
return (
<MainLayout>
<Hero />
@@ -13,4 +22,4 @@ export default function LandingPage() {
<LandingAbout />
</MainLayout>
);
}
}
+31 -14
View File
@@ -1,4 +1,5 @@
import { createAdminSessionToken } from "@/core/auth/adminSession";
import { verifyAdminCredentials } from "@/core/auth/adminUsers";
import { NextRequest, NextResponse } from "next/server";
import { createHash, timingSafeEqual } from "node:crypto";
@@ -13,20 +14,12 @@ function constantTimeEqual(left: string, right: string) {
}
export async function POST(request: NextRequest) {
const adminEmail = process.env.DATASTACK_ADMIN_EMAIL;
const adminPassword = process.env.DATASTACK_ADMIN_PASSWORD;
const sessionSecret = process.env.DATASTACK_ADMIN_SESSION_SECRET;
if (
!adminEmail ||
!adminPassword ||
!sessionSecret ||
sessionSecret.length < 32
) {
if (!sessionSecret || sessionSecret.length < 32) {
return NextResponse.json(
{
error:
"Admin login is not configured. Set the required server environment variables.",
error: "Admin authentication is not configured.",
},
{ status: 503 },
);
@@ -37,11 +30,35 @@ export async function POST(request: NextRequest) {
const email =
typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
const password = typeof body.password === "string" ? body.password : "";
if (!email || password.length === 0 || password.length > 1024) {
return NextResponse.json(
{ error: "Invalid email or password." },
{ status: 401 },
);
}
if (
!constantTimeEqual(email, adminEmail.trim().toLowerCase()) ||
!constantTimeEqual(password, adminPassword)
) {
let authenticated = false;
if (process.env.NODE_ENV !== "production" && !process.env.DATABASE_URL) {
const adminEmail = process.env.DATASTACK_ADMIN_EMAIL;
const adminPassword = process.env.DATASTACK_ADMIN_PASSWORD;
authenticated = Boolean(
adminEmail &&
adminPassword &&
constantTimeEqual(email, adminEmail.trim().toLowerCase()) &&
constantTimeEqual(password, adminPassword),
);
} else {
try {
authenticated = await verifyAdminCredentials(email, password);
} catch {
return NextResponse.json(
{ error: "Admin authentication is temporarily unavailable." },
{ status: 503 },
);
}
}
if (!authenticated) {
return NextResponse.json(
{ error: "Invalid email or password." },
{ status: 401 },
+104
View File
@@ -0,0 +1,104 @@
import { createAdminSessionToken } from "@/core/auth/adminSession";
import {
createInitialAdmin,
isAdminSetupComplete,
verifyAdminSetupKey,
} from "@/core/auth/adminUsers";
import { NextRequest, NextResponse } from "next/server";
const SESSION_COOKIE = "datastack_admin_session";
const SESSION_SECONDS = 8 * 60 * 60;
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
function validEmail(email: string) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
export async function POST(request: NextRequest) {
const sessionSecret = process.env.DATASTACK_ADMIN_SESSION_SECRET;
const configuredAdminEmail =
process.env.DATASTACK_ADMIN_EMAIL?.trim().toLowerCase();
if (!sessionSecret || sessionSecret.length < 32) {
return NextResponse.json(
{ error: "Admin session configuration is unavailable." },
{ status: 503 },
);
}
if (!configuredAdminEmail || !validEmail(configuredAdminEmail)) {
return NextResponse.json(
{ error: "Admin setup configuration is unavailable." },
{ status: 503 },
);
}
try {
const body = await request.json();
const email =
typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
const password = typeof body.password === "string" ? body.password : "";
const setupKey = typeof body.setupKey === "string" ? body.setupKey : "";
if (!validEmail(email)) {
return NextResponse.json(
{ error: "Enter a valid email address." },
{ status: 400 },
);
}
if (email !== configuredAdminEmail) {
return NextResponse.json(
{
error: "Use the administrator email configured for this deployment.",
},
{ status: 403 },
);
}
if (password.length < 12 || password.length > 256) {
return NextResponse.json(
{ error: "Choose a password between 12 and 256 characters." },
{ status: 400 },
);
}
if (!verifyAdminSetupKey(setupKey)) {
return NextResponse.json(
{ error: "The installation key is invalid." },
{ status: 403 },
);
}
if (await isAdminSetupComplete()) {
return NextResponse.json(
{ error: "Initial admin setup has already been completed." },
{ status: 409 },
);
}
const created = await createInitialAdmin(email, password);
if (!created) {
return NextResponse.json(
{ error: "Initial admin setup has already been completed." },
{ status: 409 },
);
}
const token = await createAdminSessionToken(
email,
sessionSecret,
Date.now() + SESSION_SECONDS * 1000,
);
const response = NextResponse.json({ success: true });
response.cookies.set(SESSION_COOKIE, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
path: "/",
maxAge: SESSION_SECONDS,
});
return response;
} catch {
return NextResponse.json(
{ error: "Admin setup is temporarily unavailable." },
{ status: 503 },
);
}
}
+19
View File
@@ -0,0 +1,19 @@
import { isAdminSetupComplete } from "@/core/auth/adminUsers";
import { NextResponse } from "next/server";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET() {
try {
return NextResponse.json(
{ setupComplete: await isAdminSetupComplete() },
{ headers: { "Cache-Control": "no-store" } },
);
} catch {
return NextResponse.json(
{ error: "Admin setup status is unavailable." },
{ status: 503, headers: { "Cache-Control": "no-store" } },
);
}
}
+11 -1
View File
@@ -1,5 +1,15 @@
import { AdminLogin } from '@/components/sections/AdminLogin';
import { isAdminSetupComplete } from '@/core/auth/adminUsers';
import { redirect } from 'next/navigation';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export default async function LoginPage() {
if (process.env.NODE_ENV === 'production' && process.env.DATABASE_URL) {
const isConfigured = await isAdminSetupComplete().catch(() => false);
if (!isConfigured) redirect('/vcon/setup');
}
export default function LoginPage() {
return <AdminLogin />;
}
+22
View File
@@ -0,0 +1,22 @@
import { AdminSetup } from '@/components/sections/AdminSetup';
import { isAdminSetupComplete } from '@/core/auth/adminUsers';
import { redirect } from 'next/navigation';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export default async function SetupPage() {
let databaseReady = true;
try {
if (await isAdminSetupComplete()) redirect('/vcon/login');
} catch {
databaseReady = false;
}
return (
<AdminSetup
databaseReady={databaseReady}
initialEmail={process.env.DATASTACK_ADMIN_EMAIL?.trim().toLowerCase() ?? ''}
/>
);
}
+148
View File
@@ -0,0 +1,148 @@
'use client';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { ArrowRight, ShieldCheck } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
export function AdminSetup({
databaseReady = true,
initialEmail = '',
}: {
databaseReady?: boolean;
initialEmail?: string;
}) {
const router = useRouter();
const [email, setEmail] = useState(initialEmail);
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [setupKey, setSetupKey] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [errorMessage, setErrorMessage] = useState(
databaseReady ? '' : 'The setup service is unavailable. Check the database connection and try again.',
);
const submit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setErrorMessage('');
if (password.length < 12) {
setErrorMessage('Choose a password with at least 12 characters.');
return;
}
if (password !== confirmPassword) {
setErrorMessage('The passwords do not match.');
return;
}
setIsSubmitting(true);
try {
const response = await fetch('/api/auth/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, setupKey }),
});
const body = await response.json();
if (!response.ok) throw new Error(body.error || 'Admin setup failed.');
router.replace('/vcon/dashboard');
router.refresh();
} catch (submitError) {
setErrorMessage(
submitError instanceof Error ? submitError.message : 'Admin setup failed.',
);
setIsSubmitting(false);
}
};
return (
<main className="relative grid min-h-dvh place-items-center bg-[var(--bg)] p-4 text-[var(--text)] sm:p-6">
<section className="w-full max-w-sm border border-[var(--border)] bg-[var(--surface)]">
<header className="flex flex-col gap-3.5 border-b border-[var(--border)] px-5 pb-4 pt-5">
<Link href="/" className="flex items-center gap-2 text-[13px] font-medium text-[var(--text)]">
<span className="grid h-3.5 w-3.5 place-items-center bg-[var(--accent)]" aria-hidden="true">
<span className="h-1.5 w-1.5 bg-[var(--bg)]" />
</span>
DataStack
<span className="ml-1 border border-[var(--border-strong)] px-1 py-px text-[9px] tracking-wider text-[var(--text-faint)]">INITIAL SETUP</span>
</Link>
<div>
<h1 className="text-[15px] font-medium text-[var(--text)]">Create the first admin</h1>
<p className="mt-1 text-xs leading-relaxed text-[var(--text-muted)]">
This one-time setup creates the admin account stored in your database.
</p>
</div>
</header>
<form onSubmit={submit} className="flex flex-col gap-3 px-5 py-4">
{errorMessage && (
<div role="alert" className="border border-[var(--border-strong)] bg-[var(--surface-2)] px-2.5 py-2 text-xs leading-relaxed text-[var(--text-muted)]">
{errorMessage}
</div>
)}
<Input
label="Admin email"
type="email"
autoComplete="username"
placeholder="admin@example.com"
value={email}
onChange={(event) => setEmail(event.target.value)}
compact
required
/>
<Input
label="Password"
type="password"
autoComplete="new-password"
value={password}
onChange={(event) => setPassword(event.target.value)}
compact
minLength={12}
required
/>
<Input
label="Confirm password"
type="password"
autoComplete="new-password"
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
compact
minLength={12}
required
/>
<Input
label="Installation key"
type="password"
autoComplete="off"
value={setupKey}
onChange={(event) => setSetupKey(event.target.value)}
compact
required
/>
<Button
type="submit"
variant="primary"
size="sm"
icon="ArrowRight"
iconPosition="right"
loading={isSubmitting}
disabled={isSubmitting || !databaseReady}
className="mt-1 h-[34px] w-full justify-center text-[12.5px]"
>
Create admin account
</Button>
</form>
<footer className="flex items-center justify-between border-t border-[var(--border)] px-5 py-2.5 text-[10.5px] text-[var(--text-faint)]">
<span className="inline-flex items-center gap-1.5"><ShieldCheck className="h-3 w-3" aria-hidden="true" />One-time installation</span>
<Link href="/vcon/login" className="inline-flex items-center gap-1 text-[var(--text-muted)] hover:text-[var(--text)]">
Sign in <ArrowRight className="h-3 w-3" aria-hidden="true" />
</Link>
</footer>
</section>
</main>
);
}
+141
View File
@@ -0,0 +1,141 @@
import {
createHash,
randomBytes,
scrypt as scryptCallback,
timingSafeEqual,
} from "node:crypto";
import { Pool } from "pg";
const PASSWORD_HASH_BYTES = 64;
const PASSWORD_SALT_BYTES = 16;
const DATABASE_LOCK_ID = "72025102501";
type AdminDatabaseGlobals = typeof globalThis & {
__dataStackAdminPool?: Pool;
__dataStackAdminSchema?: Promise<void>;
};
const globals = globalThis as AdminDatabaseGlobals;
function getPool() {
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error("DATABASE_URL is not configured.");
}
globals.__dataStackAdminPool ??= new Pool({
connectionString,
connectionTimeoutMillis: 3000,
idleTimeoutMillis: 30000,
max: 5,
});
return globals.__dataStackAdminPool;
}
async function ensureAdminTable() {
globals.__dataStackAdminSchema ??= getPool()
.query(
`
CREATE TABLE IF NOT EXISTS admin_users (
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
email TEXT NOT NULL UNIQUE,
password_salt BYTEA NOT NULL,
password_hash BYTEA NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`,
)
.then(() => undefined);
try {
await globals.__dataStackAdminSchema;
} catch (error) {
globals.__dataStackAdminSchema = undefined;
throw error;
}
}
function derivePasswordHash(password: string, salt: Buffer) {
return new Promise<Buffer>((resolve, reject) => {
scryptCallback(password, salt, PASSWORD_HASH_BYTES, (error, key) => {
if (error) reject(error);
else resolve(key as Buffer);
});
});
}
function matchesSecret(candidate: string, expected: string) {
const candidateHash = createHash("sha256").update(candidate).digest();
const expectedHash = createHash("sha256").update(expected).digest();
return timingSafeEqual(candidateHash, expectedHash);
}
export function verifyAdminSetupKey(candidate: string) {
const expected = process.env.DATASTACK_ADMIN_SETUP_KEY;
if (!expected || expected.length < 32) return false;
return matchesSecret(candidate, expected);
}
export async function isAdminSetupComplete() {
await ensureAdminTable();
const result = await getPool().query(
"SELECT 1 FROM admin_users WHERE id = 1",
);
return result.rowCount === 1;
}
export async function createInitialAdmin(email: string, password: string) {
await ensureAdminTable();
const client = await getPool().connect();
try {
await client.query("BEGIN");
await client.query("SELECT pg_advisory_xact_lock($1::bigint)", [
DATABASE_LOCK_ID,
]);
const existing = await client.query(
"SELECT 1 FROM admin_users WHERE id = 1",
);
if (existing.rowCount) {
await client.query("ROLLBACK");
return false;
}
const salt = randomBytes(PASSWORD_SALT_BYTES);
const passwordHash = await derivePasswordHash(password, salt);
await client.query(
`INSERT INTO admin_users (id, email, password_salt, password_hash)
VALUES (1, $1, $2, $3)`,
[email, salt, passwordHash],
);
await client.query("COMMIT");
return true;
} catch (error) {
await client.query("ROLLBACK").catch(() => undefined);
throw error;
} finally {
client.release();
}
}
export async function verifyAdminCredentials(email: string, password: string) {
await ensureAdminTable();
const result = await getPool().query(
`SELECT email, password_salt, password_hash
FROM admin_users
WHERE email = $1`,
[email],
);
const admin = result.rows[0] as
| { email: string; password_salt: Buffer; password_hash: Buffer }
| undefined;
const salt = admin?.password_salt ?? Buffer.alloc(PASSWORD_SALT_BYTES);
const expectedHash =
admin?.password_hash ?? Buffer.alloc(PASSWORD_HASH_BYTES);
const actualHash = await derivePasswordHash(password, salt);
const passwordMatches = timingSafeEqual(actualHash, expectedHash);
return Boolean(admin && passwordMatches);
}
+4 -4
View File
@@ -11,9 +11,9 @@ services:
PORT: "3000"
DATASTACK_JWT_SECRET: "${SERVICE_REALBASE64_64_JWT:?Coolify must generate SERVICE_REALBASE64_64_JWT}"
DATASTACK_ADMIN_EMAIL: "${DATASTACK_ADMIN_EMAIL:?Set DATASTACK_ADMIN_EMAIL in .env}"
DATASTACK_ADMIN_PASSWORD: "${SERVICE_PASSWORDWITHSYMBOLS_64_ADMIN:?Coolify must generate SERVICE_PASSWORDWITHSYMBOLS_64_ADMIN}"
DATASTACK_ADMIN_SESSION_SECRET: "${SERVICE_REALBASE64_64_ADMINSESSION:?Coolify must generate SERVICE_REALBASE64_64_ADMINSESSION}"
DATABASE_URL: "postgresql://datastack:${SERVICE_PASSWORD_64_POSTGRES:?Coolify must generate SERVICE_PASSWORD_64_POSTGRES}@postgres:5432/datastack_db"
DATASTACK_ADMIN_SETUP_KEY: "${SERVICE_REALBASE64_64_ADMININSTALL:?Coolify must generate SERVICE_REALBASE64_64_ADMININSTALL}"
DATABASE_URL: "postgresql://datastack:${SERVICE_PASSWORD_64_POSTGRES:?Coolify must generate SERVICE_PASSWORD_64_POSTGRES}@postgres:5432/${SERVICE_HEX_32_DATABASENAME:?Coolify must generate SERVICE_HEX_32_DATABASENAME}"
restart: unless-stopped
healthcheck:
test:
@@ -91,12 +91,12 @@ services:
environment:
POSTGRES_USER: datastack
POSTGRES_PASSWORD: "${SERVICE_PASSWORD_64_POSTGRES:?Coolify must generate SERVICE_PASSWORD_64_POSTGRES}"
POSTGRES_DB: datastack_db
POSTGRES_DB: "${SERVICE_HEX_32_DATABASENAME:?Coolify must generate SERVICE_HEX_32_DATABASENAME}"
volumes:
- pgdata:/var/lib/postgresql/data
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U datastack -d datastack_db"]
test: ["CMD-SHELL", 'pg_isready -U datastack -d "$$POSTGRES_DB"']
interval: 10s
timeout: 5s
retries: 5
+6 -6
View File
@@ -8,16 +8,16 @@ Production container definitions for the split architecture:
- `ingestion`: Express + Socket.IO process on port 4000, running as a non-root user.
- `proxy`: Nginx reverse proxy on internal port 80. Coolify routes the public domain to this service; `/socket.io/` is forwarded to ingestion and other paths to web.
- `redis`: private Compose service reserved for the planned shared-buffer integration; current application code does not consume it.
- `postgres`: private Compose service reserved for metadata integration; current application code does not use Prisma at runtime. Collected events must remain in CSV files.
- `postgres`: private Compose service; the first-run admin setup/login helper stores the single bootstrap admin credential in `admin_users` using `pg`. Prisma-backed client/settings/audit metadata is not wired yet. Collected events must remain in CSV files.
## Coolify Compose Deployment
- Create a Git-based Docker Compose application from branch `main`.
- Set Base Directory to repository root `/` and Compose Location to `docker/docker-compose.yml`.
- Set `DATASTACK_ADMIN_EMAIL` in Coolify. The Compose definition uses Coolify-generated `SERVICE_PASSWORD_64_POSTGRES`, `SERVICE_REALBASE64_64_JWT`, `SERVICE_REALBASE64_64_ADMINSESSION`, and `SERVICE_PASSWORDWITHSYMBOLS_64_ADMIN`; it builds `DATABASE_URL` from the generated PostgreSQL password.
- Retrieve the generated `SERVICE_PASSWORDWITHSYMBOLS_64_ADMIN` from Coolify Environment Variables for the initial admin sign-in. JWT/session/admin secrets can be rotated in Coolify. A PostgreSQL password change also requires updating the database role in the existing persistent volume; never paste secrets into Git-tracked files.
- Set `DATASTACK_ADMIN_EMAIL` in Coolify. Compose uses generated `SERVICE_HEX_32_DATABASENAME`, `SERVICE_PASSWORD_64_POSTGRES`, `SERVICE_REALBASE64_64_JWT`, `SERVICE_REALBASE64_64_ADMINSESSION`, and `SERVICE_REALBASE64_64_ADMININSTALL`; `DATABASE_URL` is assembled from the generated DB name/password.
- On first visit, copy `SERVICE_REALBASE64_64_ADMININSTALL` from Coolify into `/vcon/setup`, confirm the `DATASTACK_ADMIN_EMAIL` configured in Coolify, choose the first admin password, and keep generated secrets in Coolify. The API enforces the configured email and setup closes after the first account is persisted.
- Add the public domain to service `proxy` at internal port `80`. Coolify manages proxy labels in its normal Compose mode; do not enable Raw Compose mode or add direct host port mappings.
- The `web`, `ingestion`, Redis, and PostgreSQL services are private on the Compose network. Only the proxy is exposed to Coolify's domain proxy.
- The `datastack-data` named volume persists ingestion CSVs; `pgdata` persists PostgreSQL files.
- The web container does not yet share/read `datastack-data`, and neither Redis nor PostgreSQL is wired into runtime code. Those are later roadmap phases, so cross-process reads and metadata durability are not established by these images.
- Health checks probe the web landing route, ingestion `/health`, proxy route, Redis ping, and PostgreSQL readiness. These checks do not establish application-level shared-storage readiness.
- The `datastack-data` named volume stores ingestion CSVs; `pgdata` stores PostgreSQL files and the bootstrap admin credential. Compose configures these named volumes for persistence; verify restart/redeploy behavior in the target Coolify runtime before relying on it. Do not delete the volumes or regenerate the DB name for an existing deployment. Back up before DB upgrades. DB password rotation requires changing the DB role as well as the Coolify value.
- The web container does not yet share/read `datastack-data`, and Redis is not wired into runtime code. Prisma-backed client/settings metadata remains future work; cross-process reads and general metadata durability are not established by these images.
- Health checks probe the web landing route, ingestion `/health`, proxy route, Redis ping, and PostgreSQL readiness using the generated `POSTGRES_DB` name. These checks do not establish application-level shared-storage readiness.
+7 -1
View File
@@ -5,6 +5,8 @@ const SESSION_COOKIE = "datastack_admin_session";
function isProtectedApi(pathname: string, method: string) {
if (pathname === "/api/auth/login") return false;
if (pathname === "/api/auth/setup/status" && method === "GET") return false;
if (pathname === "/api/auth/setup" && method === "POST") return false;
if (pathname === "/api/events" && method === "POST") return false;
return pathname.startsWith("/api/");
}
@@ -12,10 +14,14 @@ function isProtectedApi(pathname: string, method: string) {
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const isLoginPage = pathname === "/vcon/login";
const isSetupPage = pathname === "/vcon/setup";
const isConsolePage =
(pathname === "/vcon" || pathname.startsWith("/vcon/")) && !isLoginPage;
(pathname === "/vcon" || pathname.startsWith("/vcon/")) &&
!isLoginPage &&
!isSetupPage;
const isAdminApi = isProtectedApi(pathname, request.method);
if (isSetupPage) return NextResponse.next();
if (!isConsolePage && !isAdminApi && !isLoginPage) return NextResponse.next();
const sessionSecret = process.env.DATASTACK_ADMIN_SESSION_SECRET;
+119 -119
View File
@@ -21,6 +21,7 @@
"lucide-react": "^0.553.0",
"motion": "^12.23.24",
"next": "^15.4.9",
"pg": "^8.23.1",
"postcss": "^8.5.6",
"react": "^19.2.1",
"react-dom": "^19.2.1",
@@ -35,6 +36,7 @@
"@types/express": "^5.0.6",
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^20",
"@types/pg": "^8.23.1",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "9.39.1",
@@ -1584,6 +1586,111 @@
"fast-glob": "3.3.1"
}
},
"node_modules/@next/swc-darwin-arm64": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.5.28.tgz",
"integrity": "sha512-dPoQYXcfSIqx5o+TOXVXO7kONK5qbtNRDeiTfII0bT3puGIT6VF5e0QwmxNZfEZ5Zety5f3m9P/p4xqwfiLlPg==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.5.28.tgz",
"integrity": "sha512-RgCJ7buBivTH+6sddqaVm+/v8kwMHlFkobvdt3DfETutws5HrxnToMIWSN9X3MZ3aAi7BbKrGZZWUDQLEycXqw==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.5.28.tgz",
"integrity": "sha512-OHXQe13olE59aKe++zHavGcJPh5SLHXi6Anret3BBeq1+qhSuOJDNAli/EDDfxs6UTqA4Qddo4uyYry2slyjiQ==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.5.28.tgz",
"integrity": "sha512-nTB7bB6vfn4ezCJNYP43ukt2o8L3+WxKF/sTcTxepdXsJh3SM9RhlU7wrZYbH7L4HO5M87dqDTwm8587vAkCiw==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.5.28.tgz",
"integrity": "sha512-WXCfVI32rW3xCusoUX1RpZKtyChWU2Zwe27JUDmM3KrXwcDNc9vV4zEq0GKFAURnuQ/Ouo/XqPvB0yh445XZCg==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.5.28.tgz",
"integrity": "sha512-Miq+NDb/HWsXuxseYxMM6fuEOQXgTziarkKIRpVKCn8W69cEfhQaQr+90pO+u4q2CbJR2wzXmUuCFyZaJs/Nng==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.5.28.tgz",
"integrity": "sha512-5LR79lemgDlgxvG7MQJ+zHCkVcrUoQuO7CiIvq3I58vNW4goSOE2b+19Z6FujRWMouvni4gvudYFuFuNxolGWA==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.28.tgz",
@@ -2064,6 +2171,18 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/pg": {
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz",
"integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"pg-protocol": "*",
"pg-types": "^2.2.0"
}
},
"node_modules/@types/qs": {
"version": "6.15.1",
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",
@@ -10206,7 +10325,6 @@
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
"integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"pg-connection-string": "^2.14.1",
@@ -10234,7 +10352,6 @@
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
"integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
"dev": true,
"license": "MIT",
"optional": true
},
@@ -10242,7 +10359,6 @@
"version": "2.14.1",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
"integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
"dev": true,
"license": "MIT"
},
"node_modules/pg-gateway": {
@@ -10256,7 +10372,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=4.0.0"
@@ -10266,7 +10381,6 @@
"version": "3.14.0",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
@@ -10276,14 +10390,12 @@
"version": "1.16.1",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
"integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
"dev": true,
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"dev": true,
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
@@ -10308,7 +10420,6 @@
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"dev": true,
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
@@ -10419,7 +10530,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=4"
@@ -10429,7 +10539,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -10439,7 +10548,6 @@
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -10449,7 +10557,6 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
@@ -11677,7 +11784,6 @@
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">= 10.x"
@@ -13440,7 +13546,6 @@
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.4"
@@ -13581,111 +13686,6 @@
"peerDependencies": {
"zod": "^3.25.0 || ^4.0.0"
}
},
"node_modules/@next/swc-darwin-arm64": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.5.28.tgz",
"integrity": "sha512-dPoQYXcfSIqx5o+TOXVXO7kONK5qbtNRDeiTfII0bT3puGIT6VF5e0QwmxNZfEZ5Zety5f3m9P/p4xqwfiLlPg==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.5.28.tgz",
"integrity": "sha512-RgCJ7buBivTH+6sddqaVm+/v8kwMHlFkobvdt3DfETutws5HrxnToMIWSN9X3MZ3aAi7BbKrGZZWUDQLEycXqw==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.5.28.tgz",
"integrity": "sha512-OHXQe13olE59aKe++zHavGcJPh5SLHXi6Anret3BBeq1+qhSuOJDNAli/EDDfxs6UTqA4Qddo4uyYry2slyjiQ==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.5.28.tgz",
"integrity": "sha512-nTB7bB6vfn4ezCJNYP43ukt2o8L3+WxKF/sTcTxepdXsJh3SM9RhlU7wrZYbH7L4HO5M87dqDTwm8587vAkCiw==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.5.28.tgz",
"integrity": "sha512-WXCfVI32rW3xCusoUX1RpZKtyChWU2Zwe27JUDmM3KrXwcDNc9vV4zEq0GKFAURnuQ/Ouo/XqPvB0yh445XZCg==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.5.28.tgz",
"integrity": "sha512-Miq+NDb/HWsXuxseYxMM6fuEOQXgTziarkKIRpVKCn8W69cEfhQaQr+90pO+u4q2CbJR2wzXmUuCFyZaJs/Nng==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "15.5.28",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.5.28.tgz",
"integrity": "sha512-5LR79lemgDlgxvG7MQJ+zHCkVcrUoQuO7CiIvq3I58vNW4goSOE2b+19Z6FujRWMouvni4gvudYFuFuNxolGWA==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
}
}
}
+2
View File
@@ -24,6 +24,7 @@
"lucide-react": "^0.553.0",
"motion": "^12.23.24",
"next": "^15.4.9",
"pg": "^8.23.1",
"postcss": "^8.5.6",
"react": "^19.2.1",
"react-dom": "^19.2.1",
@@ -38,6 +39,7 @@
"@types/express": "^5.0.6",
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^20",
"@types/pg": "^8.23.1",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "9.39.1",
+10
View File
@@ -41,6 +41,16 @@ model ApiKey {
@@map("api_keys")
}
model AdminUser {
id Int @id @default(1) @db.SmallInt
email String @unique
passwordSalt Bytes @map("password_salt")
passwordHash Bytes @map("password_hash")
createdAt DateTime @default(now()) @map("created_at")
@@map("admin_users")
}
model AdminSettings {
id String @id @default("default")
serverPort Int @default(4000)