1. Findings
| # | Level | Problem | Where | How it could be abused | Fix |
|---|
| 1 | Fix before launch | Live Stripe secret key is in a public repo and named as a browser variable | .env.local line 2 (NEXT_PUBLIC_STRIPE_SECRET_KEY=sk_live_…), used in app/api/checkout/route.ts line 2 | Anyone who finds the key in your public GitHub repo can refund your payments, read every customer's email and payment history, and create charges on your account. | Roll the key in Stripe, rename it to STRIPE_SECRET_KEY, and remove .env.local from the repo |
| 2 | Fix before launch | Gemini API key is in a public repo | .env.local line 3 (GEMINI_API_KEY) | Anyone can copy the key and run their own AI workload on your Google bill. | Regenerate the key, restrict it to the Generative Language API, and keep it only in Vercel |
| 3 | Fix before launch | Firestore rules let any signed-in user read and write every document | firestore.rules, match /{document=**} | Anyone can sign up for free, then read every child's name, school and learning-needs notes, and edit or delete any slot or profile. | Write rules per collection based on ownership. Store the tutor role as a custom claim the client cannot write |
| 4 | Fix before launch | The browser marks a slot "paid" with no proof of payment | app/booked/page.tsx, updateDoc(... { status: "paid" }) | A signed-in user can open /booked?slot=<any id> and claim any slot as paid without paying. | Mark slots paid only from a verified Stripe webhook on the server, and remove the client write |
| 5 | Fix before launch | Checkout trusts the price and email sent by the browser, with no sign-in check | app/api/checkout/route.ts, const { slotId, price, parentEmail } = await req.json() and unit_amount: price * 100 | Anyone can POST {"price":1} and pay S$1 for an S$80 session, or create sessions under someone else's email. | Require a Firebase ID token, read the price from the slot document on the server, and take the email from the token |
| 6 | Fix before launch | Stored XSS through child notes | components/ChildCard.tsx, dangerouslySetInnerHTML={{ __html: child.notes }} | A parent can put <img src=x onerror=…> in the notes. It runs in the tutor's browser when they open the booking, and can steal the tutor's session and every booking they can see. | Render notes as plain text |
| 7 | Fix before launch | TutorBot has no sign-in check, rate limit or size cap | app/api/tutorbot/route.ts, POST | A script can call /api/tutorbot in a loop with huge prompts and run up your Gemini bill without any account. | Require sign-in, cap question length and output tokens, add a per-user daily limit, and return only the answer text |
| 8 | Fix soon | Two parents can pay for the same slot | app/api/checkout/route.ts, POST (no availability check or hold) | Two parents start checkout on one slot at the same time, both are charged, and one booking is lost. | Check status === "open" (included in fix #5), set Checkout expires_at, and have the webhook log a second payment so you can refund it (included in fix #4) |
| 9 | Fine for now | Firebase web API key is public | lib/firebase.ts line 3 | This key is meant to be public, and Firestore rules (fix #3) are what protect your data. | Restrict the key to your domains in Google Cloud (see dashboard checks) |
I could not see the sign-up and role code, the pages that write children and slots, or the full list of collections. The rules below assume users, children and slots. Please send those files so I can confirm the rules fit.
2. Fix details
#1 and #2: keys. Roll the keys first. The repo is public, so assume both keys have already been copied, and deleting them from git history does not undo that.
# .gitignore
.env*
!.env.example
git rm --cached .env.local
git commit -m "Stop tracking env file"
# .env.local (local only; put the same names in Vercel → Environment Variables)
NEXT_PUBLIC_FIREBASE_API_KEY=AIzaSyD...web # public by design
STRIPE_SECRET_KEY=sk_live_NEW... # no NEXT_PUBLIC_ prefix
STRIPE_WEBHOOK_SECRET=whsec_...
GEMINI_API_KEY=NEW...
FIREBASE_CLIENT_EMAIL=... # service account, for the Admin SDK
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n..."
Shared helper used by fixes #4, #5 and #7:
// lib/firebaseAdmin.ts
import "server-only";
import { cert, getApps, initializeApp } from "firebase-admin/app";
import { getAuth } from "firebase-admin/auth";
import { getFirestore } from "firebase-admin/firestore";
const app =
getApps()[0] ??
initializeApp({
credential: cert({
projectId: "tutorslot-sg",
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, "\n"),
}),
});
export const adminAuth = getAuth(app);
export const adminDb = getFirestore(app);
export async function requireUser(req: Request) {
const h = req.headers.get("authorization") ?? "";
if (!h.startsWith("Bearer ")) return null;
try {
return await adminAuth.verifyIdToken(h.slice(7));
} catch {
return null;
}
}
The client must send its token when calling these routes:
const token = await auth.currentUser!.getIdToken();
await fetch("/api/checkout", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
body: JSON.stringify({ slotId, childId }),
});
#3: Firestore rules. Tutors are identified by a custom claim. Set it once per tutor from a trusted script with adminAuth.setCustomUserClaims(uid, { tutor: true }). Any collection not listed here is denied. Test the rules in the Firebase emulator or Rules Playground before deploying.
// firestore.rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function signedIn() { return request.auth != null; }
function uid() { return request.auth.uid; }
function isTutor() { return signedIn() && request.auth.token.tutor == true; }
match /users/{userId} {
allow read: if signedIn() && uid() == userId;
allow create, update: if signedIn() && uid() == userId
&& !request.resource.data.keys().hasAny(['role', 'tutor', 'admin']);
}
match /children/{childId} {
allow read: if signedIn() && (
resource.data.parentId == uid() ||
uid() in resource.data.get('tutorIds', [])
);
allow create: if signedIn()
&& request.resource.data.parentId == uid()
&& !('tutorIds' in request.resource.data)
&& request.resource.data.get('notes', '').size() <= 2000;
allow update: if signedIn()
&& resource.data.parentId == uid()
&& !request.resource.data.diff(resource.data).affectedKeys().hasAny(['parentId', 'tutorIds'])
&& request.resource.data.get('notes', '').size() <= 2000;
allow delete: if signedIn() && resource.data.parentId == uid();
}
match /slots/{slotId} {
allow read: if signedIn();
allow create: if isTutor()
&& request.resource.data.tutorId == uid()
&& request.resource.data.status == 'open'
&& !request.resource.data.keys().hasAny(['parentId', 'stripeSessionId']);
allow update: if isTutor()
&& resource.data.tutorId == uid()
&& !request.resource.data.diff(resource.data).affectedKeys()
.hasAny(['status', 'parentId', 'tutorId', 'stripeSessionId']);
allow delete: if isTutor() && resource.data.tutorId == uid() && resource.data.status == 'open';
}
// Everything else (including tutorbotUsage) is denied to clients.
}
}
#4: mark paid only from a verified webhook. Register this endpoint in Stripe for the checkout.session.completed event.
// app/api/stripe-webhook/route.ts
import Stripe from "stripe";
import { FieldValue } from "firebase-admin/firestore";
import { adminDb } from "@/lib/firebaseAdmin";
export const runtime = "nodejs";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST(req: Request) {
const body = await req.text();
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
req.headers.get("stripe-signature") ?? "",
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch {
return new Response("Bad signature", { status: 400 });
}
if (event.type === "checkout.session.completed") {
const s = event.data.object as Stripe.Checkout.Session;
const { slotId, parentId, childId } = s.metadata ?? {};
if (s.payment_status === "paid" && slotId && parentId && childId) {
const slotRef = adminDb.collection("slots").doc(slotId);
const childRef = adminDb.collection("children").doc(childId);
await adminDb.runTransaction(async (tx) => {
const slot = (await tx.get(slotRef)).data();
if (!slot) return;
if (slot.status === "paid") {
console.error("Double payment, refund needed", { slotId, session: s.id });
return;
}
tx.update(slotRef, {
status: "paid",
parentId,
childId,
stripeSessionId: s.id,
paidAt: FieldValue.serverTimestamp(),
});
tx.update(childRef, { tutorIds: FieldValue.arrayUnion(slot.tutorId) });
});
}
}
return new Response("ok");
}
// app/booked/page.tsx (read only: delete the updateDoc call)
const snap = await getDoc(doc(db, "slots", String(searchParams.slot)));
const paid = snap.exists() && snap.data().status === "paid" && snap.data().parentId === user.uid;
// Show "Booking confirmed" if paid, otherwise "Confirming your payment…" and re-check after a few seconds.
#5: checkout uses the server-side price and a verified user.
// app/api/checkout/route.ts
import Stripe from "stripe";
import { adminDb, requireUser } from "@/lib/firebaseAdmin";
export const runtime = "nodejs";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const ID = /^[A-Za-z0-9_-]{1,64}$/;
export async function POST(req: Request) {
const user = await requireUser(req);
if (!user?.email) return Response.json({ error: "Sign in required" }, { status: 401 });
const { slotId, childId } = await req.json().catch(() => ({}));
if (!ID.test(String(slotId)) || !ID.test(String(childId)))
return Response.json({ error: "Bad request" }, { status: 400 });
const [slotSnap, childSnap] = await Promise.all([
adminDb.collection("slots").doc(slotId).get(),
adminDb.collection("children").doc(childId).get(),
]);
const slot = slotSnap.data();
if (!slot || slot.status !== "open")
return Response.json({ error: "Slot not available" }, { status: 409 });
if (childSnap.data()?.parentId !== user.uid)
return Response.json({ error: "Not your child profile" }, { status: 403 });
const amount = Math.round(Number(slot.price) * 100);
if (!(amount >= 4500 && amount <= 8000))
return Response.json({ error: "Slot price invalid" }, { status: 500 });
const session = await stripe.checkout.sessions.create({
mode: "payment",
customer_email: user.email,
client_reference_id: user.uid,
metadata: { slotId, childId, parentId: user.uid },
expires_at: Math.floor(Date.now() / 1000) + 30 * 60,
line_items: [{
price_data: { currency: "sgd", unit_amount: amount, product_data: { name: `Session ${slotId}` } },
quantity: 1,
}],
success_url: `https://tutorslot.sg/booked?slot=${encodeURIComponent(slotId)}`,
cancel_url: "https://tutorslot.sg/slots",
});
return Response.json({ url: session.url });
}
#6: render notes as text.
// components/ChildCard.tsx
<p className="whitespace-pre-wrap">{child.notes}</p>
#7: TutorBot with sign-in, caps and a daily limit.
// app/api/tutorbot/route.ts
import { adminDb, requireUser } from "@/lib/firebaseAdmin";
export const runtime = "nodejs";
const DAILY_LIMIT = 30;
const MAX_CHARS = 1000;
export async function POST(req: Request) {
const user = await requireUser(req);
if (!user) return Response.json({ error: "Sign in required" }, { status: 401 });
const { question } = await req.json().catch(() => ({}));
if (typeof question !== "string" || !question.trim() || question.length > MAX_CHARS)
return Response.json({ error: `Question must be 1–${MAX_CHARS} characters` }, { status: 400 });
const day = new Date().toISOString().slice(0, 10);
const ref = adminDb.collection("tutorbotUsage").doc(`${user.uid}_${day}`);
const allowed = await adminDb.runTransaction(async (tx) => {
const n = (await tx.get(ref)).data()?.count ?? 0;
if (n >= DAILY_LIMIT) return false;
tx.set(ref, { uid: user.uid, day, count: n + 1 });
return true;
});
if (!allowed) return Response.json({ error: "Daily limit reached" }, { status: 429 });
const r = await fetch(
"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent",
{
method: "POST",
headers: { "Content-Type": "application/json", "x-goog-api-key": process.env.GEMINI_API_KEY! },
body: JSON.stringify({
contents: [{ parts: [{ text: question }] }],
generationConfig: { maxOutputTokens: 800 },
}),
}
);
if (!r.ok) return Response.json({ error: "TutorBot unavailable" }, { status: 502 });
const data = await r.json();
const answer =
data?.candidates?.[0]?.content?.parts?.map((p: { text?: string }) => p.text ?? "").join("") ?? "";
return Response.json({ answer });
}
3. Check in your dashboard
- Stripe Dashboard → Developers → API keys: roll the live secret key. Then check Developers → Logs and Payments → Refunds for activity you don't recognise since the key was pushed. Add the webhook endpoint under Developers → Webhooks and copy its signing secret.
- Google Cloud Console → APIs & Services → Credentials (project
tutorslot-sg): delete and recreate the Gemini key and restrict it to the Generative Language API. Restrict the Firebase web key to HTTP referrers tutorslot.sg/*. Set a budget alert under Billing → Budgets & alerts. - Firebase Console → Firestore → Rules: confirm the deployed rules match the file, since the live rules can differ from the repo. Then check Authentication → Settings: authorised domains should be only your own, and email enumeration protection should be on.
- Vercel → Project → Settings → Environment Variables: confirm that no secret uses a
NEXT_PUBLIC_ prefix, that the old Stripe variable is deleted, and that all new variables are set for Production. Turn on Deployment Protection for preview URLs. - GitHub → repo Settings: make the repo private, and review Security → Secret scanning alerts for anything else that was leaked.
4. Looks fine
- Payments go through hosted Stripe Checkout, so card details never touch your code or database.
success_url and cancel_url are fixed to your own domain, so the checkout route cannot be used as an open redirect.- The Gemini key is only read inside a server route and is not exposed in the browser bundle. The leak is the repo, not the code.
- No database query is built from strings. All Firestore access goes through SDK calls, so there is no query-injection path.