Opening AI Labs to the Public while Keeping the “Class” Test Secure
TL;DR: I refactored the AI Business Academy to expose all learning materials and labs publicly, and added a HMAC‑based “class” keyword to protect the AI test (ADR 0013). The change required a new DB migration, environment tweaks, and a handful of component updates to keep the UI consistent and the gate‑keeping logic safe.
The Problem
The platform originally kept labs behind a VIP‑only area (ADR 0012). When we announced the pilot course, the community asked for open access to the labs so anyone could experiment with the AI prompts. At the same time, the “Pruébala con IA” test inside each lab needed a single shared secret – the “class” keyword – that only instructors could distribute.
The symptom was two‑fold:
-
404/403 errors when a non‑VIP user navigated to
/laboratorios/[slug]. The router redirected to the VIP gate, which broke SEO and prevented public sharing. -
No place to store or validate the class keyword; attempts to read it from the environment caused a
ReferenceError: process.env.CLASS_KEY is undefinedduring server‑side rendering.
We needed a clean way to make the lab pages public without exposing the test‑gate logic.
What I Tried First
My first attempt was to flip the isVipOnly flag in src/app/laboratorios/_components/lab-campanas.tsx and rely on the existing role‑check middleware. I added:
// src/app/laboratorios/_components/lab-campanas.tsx
export const isPublic = true; // quick hack
This made the pages render, but the AI panel (ai-panel.tsx) still called the protected API endpoint, which returned 401 Unauthorized. The error bubbled up as:
Error: Request failed with status code 401
at fetchData (ai-panel.tsx:45)
I also tried pulling the keyword from .env directly in the client component, but Next.js’ server‑only environment variables are stripped out of the bundle, leading to the ReferenceError mentioned above. The approach was fragile and mixed concerns (routing vs. secret handling).
The Implementation
1. Architectural Decision (ADR 0013)
I documented the change in docs/decisions/0013-public-materials-and-labs.md. The core idea:
- Materials & labs become static public pages (Next.js App Router, static generation).
- The class keyword is stored as a single HMAC row in the DB, never in plain text.
- Instructors set the keyword via the admin UI; the backend verifies it on the AI test request.
2. Database Migration
Added db/migrations/0007_lab_class_key.sql:
-- 0007_lab_class_key: class keyword for "Pruébala con IA" once the labs are public (ADR 0013).
-- One row at most. Only an HMAC of the keyword is stored; the instructor sets it from the UI.
CREATE TABLE IF NOT EXISTS lab_class_key (
id SERIAL PRIMARY KEY,
hmac BYTEA NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
-- Ensure only a single row can exist
CREATE UNIQUE INDEX IF NOT EXISTS uq_lab_class_key ON lab_class_key (id);
Running the migration (npm run db:migrate) creates the table. The unique index guarantees we never accidentally store multiple keys.
3. Environment Adjustments
/.env.example now includes a placeholder for the secret used to generate the HMAC:
# HMAC secret for class keyword (must be 32+ chars)
CLASS_KEY_HMAC_SECRET=super-secret-32byte-string
The secret never leaves the server; it’s read only in API routes.
4. Backend – Generating & Verifying the HMAC
In src/app/instructor/actions.ts I added two helpers:
import crypto from 'crypto';
import { sql } from '@vercel/postgres';
// Generate HMAC from plain keyword
export async function setClassKey(keyword: string) {
const secret = process.env.CLASS_KEY_HMAC_SECRET!;
const hmac = crypto.createHmac('sha256', secret).update(keyword).digest();
await sql`INSERT INTO lab_class_key (hmac) VALUES (${hmac}) ON CONFLICT (id) DO UPDATE SET hmac = ${hmac}`;
}
// Verify incoming keyword
export async function verifyClassKey(candidate: string): Promise<boolean> {
const secret = process.env.CLASS_KEY_HMAC_SECRET!;
const candidateHmac = crypto.createHmac('sha256', secret).update(candidate).digest();
const result = await sql`SELECT hmac FROM lab_class_key LIMIT 1`;
if (!result.rowCount) return false;
return crypto.timingSafeEqual(candidateHmac, result.rows[0].hmac);
}
These functions live on the server side only, preventing the secret from leaking to the client bundle.
5. UI – Public Lab Pages
The route src/app/laboratorios/[slug]/page.tsx switched from getServerSideProps (auth‑dependent) to generateStaticParams and generateMetadata for static generation:
// src/app/laboratorios/[slug]/page.tsx
export async function generateStaticParams() {
const labs = await sql`SELECT slug FROM labs`;
return labs.map((lab) => ({ slug: lab.slug }));
}
Because the pages are now static, they load instantly and are crawlable.
6. AI Panel Guard
src/app/laboratorios/_components/ai-panel.tsx now prompts for the class keyword before calling the AI endpoint:
import { useState } from 'react';
import { verifyClassKey } from '@/app/instructor/actions';
export default function AIPanel({ labId }: { labId: string }) {
const [keyword, setKeyword] = useState('');
const [authorized, setAuthorized] = useState(false);
const [error, setError] = useState('');
const handleCheck = async () => {
const ok = await verifyClassKey(keyword);
setAuthorized(ok);
setError(ok ? '' : 'Invalid class keyword');
};
if (!authorized) {
return (
<div className="p-4 border rounded">
<p>Enter the class keyword to unlock the AI test:</p>
<input
className="border p-1 mr-2"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
/>
<button className="bg-blue-600 text-white p-1" onClick={handleCheck}>
Unlock
</button>
{error && <p className="text-red-500">{error}</p>}
</div>
);
}
// …rest of the AI UI
}
The verifyClassKey call runs on the server (via Next.js API route) so the secret never touches the
Part of my Build in Public series — sharing the real process of building SaaS projects from Playa del Carmen, México.
Repo: zaerohell/ai-business-academy · 2026-12-02
#playadev #buildinpublic
Top comments (0)