Spaces:
Runtime error
Runtime error
elshaddaioheha commited on
Commit ·
bbc5521
1
Parent(s): 2703c9d
feat(app): migrate auth to supabase and add landing page
Browse filesFiles changed (33)
- .env.example+2-5
- README.md+23-17
- apps/web/next.config.mjs+9-2
- apps/web/package.json-2
- apps/web/src/app/api/alerts/route.ts+4-2
- apps/web/src/app/api/analyze/text/route.ts+2-2
- apps/web/src/app/api/auth/[...nextauth]/route.tsDeleted-8
- apps/web/src/app/api/incidents/[id]/route.ts+4-2
- apps/web/src/app/api/incidents/route.ts+4-2
- apps/web/src/app/moderation/incidents/[id]/page.tsx+3-1
- apps/web/src/app/moderation/page.tsx+7-3
- apps/web/src/app/page.tsx+166-3
- apps/web/src/app/settings/page.tsx+1-1
- apps/web/src/app/sign-in/page.tsx+10-18
- apps/web/src/app/sign-up/page.tsxAdded+16
- apps/web/src/components/AppShell.tsx+11-41
- apps/web/src/components/AuthPanel.tsxAdded+215
- apps/web/src/components/BrandLogo.tsxAdded+20
- apps/web/src/components/ProfileMenu.tsxAdded+121
- apps/web/src/components/SignOutButton.tsx+26-4
- apps/web/src/lib/auth.ts+51-34
- apps/web/src/lib/backend.ts+13-5
- apps/web/src/lib/env.ts+5-4
- apps/web/src/lib/guards.ts+1-1
- apps/web/src/lib/server-env.tsAdded+68
- apps/web/src/middleware.tsAdded+11
- apps/web/src/utils/supabase/client.tsAdded+8
- apps/web/src/utils/supabase/middleware.tsAdded+35
- apps/web/src/utils/supabase/server.tsAdded+27
- package-lock.json+124-230
- package.json+4-1
- services/api/app/core/config.py+25-3
- services/api/tests/test_config.pyAdded+11
2 unmodified lines345678920 unmodified lines30313232333435363334352 unmodified lines
# Backend / Next.js BFFAPI_BASE_URL=http://localhost:8000# Optional fallback for non-user service calls and manual local scripts.BACKEND_INTERNAL_TOKEN=dev-internal-tokenALLOWED_CORS_ORIGINS=http://localhost:3000
20 unmodified linesREPETITION_DECAY=0.7ADMIN_NOTIFICATION_EMAIL=moderation@example.com
# Frontend/Auth.jsNEXTAUTH_URL=http://localhost:3000NEXTAUTH_SECRET=replace-with-a-long-random-stringGOOGLE_CLIENT_ID=replace-with-google-client-idGOOGLE_CLIENT_SECRET=replace-with-google-client-secret# Frontend / role gatingMODERATOR_EMAILS=moderator@example.comNEXT_PUBLIC_APP_NAME=Cybully Safety1 unmodified line2345567828 unmodified lines373839404041424344454643444546474849505149525354551 unmodified line575859576061626364656664676869702 unmodified lines73747576777873747576777879808182838485808687888949 unmodified lines1391401411361421431441451 unmodified line
This repository implements the 1-week MVP plan from the system design document:
- Next.js app shell with Google OAuth via Auth.js.- Next.js app shell with Supabase email/password auth and SSR session handling.- User-facing text submission flow.- Moderator incident queue, detail view, review actions, and polling refresh.- FastAPI backend with Supabase Postgres persistence, direct mini-project processing, optional RabbitMQ workers, and stubbed alert storage.28 unmodified lines
`PIPELINE_MODE=direct` removes the need for Docker, RabbitMQ, and local PostgreSQL. The API processes the text and persists the incident during the request.
4. Fill in Google OAuth values in `.env`.4. Configure backend and moderator values in `.env`.
```textGOOGLE_CLIENT_ID=...GOOGLE_CLIENT_SECRET=...NEXTAUTH_SECRET=...MODERATOR_EMAILS=your-moderator-google-email@example.comMODERATOR_EMAILS=your-moderator-email@example.com```5. Create `apps/web/.env.local` for the public Supabase web keys.
```textNEXT_PUBLIC_SUPABASE_URL=https://YOUR_PROJECT_REF.supabase.coNEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=replace-with-supabase-publishable-key```
5. Install and run the backend.6. Install and run the backend.
```powershellcd services/api1 unmodified lineuvicorn app.main:app --reload --port 8000```
6. Install and run the frontend.7. Install and run the frontend.
```powershellnpm installnpm run dev:web```
7. Open the apps.8. Open the apps.
- Web app: http://localhost:3000- FastAPI docs: http://localhost:8000/docs2 unmodified lines
## Manual Demo
1. Open http://localhost:3000/sign-in.2. Sign in with a Supabase email/password account, or create one at `/sign-up`.3. New sign-ups must confirm their email before sign-in when Supabase email confirmation is enabled.1. Sign in at http://localhost:3000/sign-in with the Google account listed in `MODERATOR_EMAILS`.2. Submit text at `/app`.3. In direct mode, the API writes the incident to Supabase during the request.4. Review incidents at `/moderation`.5. Open an incident detail page and mark it reviewed, dismissed, or escalated.6. Check high-severity alert stubs in the lower panel of `/moderation`.4. To preview moderator screens immediately, sign in with an email listed in `MODERATOR_EMAILS`.5. Submit text at `/app`.6. In direct mode, the API writes the incident to Supabase during the request.7. Review incidents at `/moderation`.8. Open an incident detail page and mark it reviewed, dismissed, or escalated.9. Check high-severity alert stubs in the lower panel of `/moderation`.
You can also use `scripts/demo_payloads.http` against the FastAPI service directly. Include `X-Internal-Token` when calling backend endpoints outside the Next.js proxy.You can also use `scripts/demo_payloads.http` against the FastAPI service directly. Prefer a Supabase bearer token for user-scoped calls. `X-Internal-Token` remains available as a fallback for local service-to-service or manual script use.
## Backend Development
49 unmodified lines- `PATCH /api/v1/incidents/{id}`: update moderation status and note.- `GET /api/v1/alerts`: list stubbed high-severity alerts.
All `/api/v1/*` backend routes require `X-Internal-Token`. The Next.js server routes add it automatically.All `/api/v1/*` backend routes require either a Supabase bearer token or `X-Internal-Token`. The Next.js server routes now forward the signed-in user's Supabase access token to FastAPI.
## Optional Queue Mode
123345678910111213147/** @type {import('next').NextConfig} */const nextConfig = { reactStrictMode: true reactStrictMode: true, images: { remotePatterns: [ { protocol: "https", hostname: "images.unsplash.com" } ] }};
export default nextConfig;
9 unmodified lines10111213131415171617189 unmodified lines "test": "vitest run" }, "dependencies": { "@auth/core": "^0.34.0", "@hugeicons/core-free-icons": "^4.1.4", "@hugeicons/react": "^1.1.6", "next": "^14.2.0", "next-auth": "^4.24.11", "react": "^18.3.1", "react-dom": "^18.3.1" },18 unmodified lines192021222223242526272518 unmodified lines } }
const alerts = await backendFetch<AlertListResponse>("/api/v1/alerts", { query }); const alerts = await backendFetch<AlertListResponse>("/api/v1/alerts", { authToken: session.accessToken, query }); return NextResponse.json(alerts);}
17 unmodified lines18192021222323242526272 unmodified lines3031323217 unmodified lines }
const response = await backendFetch<{ tracking_id: string; status: "accepted" }>("/api/v1/analyze/text", { authToken: session.accessToken, method: "POST", body: { user_id: session.user.email, user_id: session.user.id, target_user_id: targetUserId, timestamp: new Date().toISOString(), text2 unmodified lines
return NextResponse.json(response, { status: 202 });}
12345678import NextAuth from "next-auth";
import { authOptions } from "@/lib/auth";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
15 unmodified lines161718191920212223245 unmodified lines3031323334353637383615 unmodified lines return NextResponse.json({ error: "Moderator access required" }, { status: 403 }); }
const incident = await backendFetch<Incident>(`/api/v1/incidents/${context.params.id}`); const incident = await backendFetch<Incident>(`/api/v1/incidents/${context.params.id}`, { authToken: session.accessToken }); return NextResponse.json(incident);}
5 unmodified lines
const body = await request.json(); const incident = await backendFetch<Incident>(`/api/v1/incidents/${context.params.id}`, { authToken: session.accessToken, method: "PATCH", body }); return NextResponse.json(incident);}
18 unmodified lines192021222223242526272518 unmodified lines } }
const incidents = await backendFetch<IncidentListResponse>("/api/v1/incidents", { query }); const incidents = await backendFetch<IncidentListResponse>("/api/v1/incidents", { authToken: session.accessToken, query }); return NextResponse.json(incidents);}
14 unmodified lines1516171818192021222314 unmodified lines
export default async function IncidentDetailPage({ params }: PageProps) { const session = await requireModerator(); const incident = await backendFetch<Incident>(`/api/v1/incidents/${params.id}`); const incident = await backendFetch<Incident>(`/api/v1/incidents/${params.id}`, { authToken: session.accessToken });
return ( <AppShell session={session}>6 unmodified lines7891011101112131415161718192 unmodified lines222324206 unmodified linesexport default async function ModerationPage() { const session = await requireModerator(); const [incidents, alerts] = await Promise.all([ backendFetch<IncidentListResponse>("/api/v1/incidents"), backendFetch<AlertListResponse>("/api/v1/alerts", { query: new URLSearchParams({ limit: "10" }) }) backendFetch<IncidentListResponse>("/api/v1/incidents", { authToken: session.accessToken }), backendFetch<AlertListResponse>("/api/v1/alerts", { authToken: session.accessToken, query: new URLSearchParams({ limit: "10" }) }) ]);
return (2 unmodified lines </AppShell> );}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354553455657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169import Image from "next/image";import Link from "next/link";import { redirect } from "next/navigation";import { HugeiconsIcon } from "@hugeicons/react";import { Alert02Icon, AiSecurity01Icon, Analytics01Icon, CheckmarkBadge01Icon} from "@hugeicons/core-free-icons";
import { BrandLogo } from "@/components/BrandLogo";import { getSession } from "@/lib/auth";
const featureHighlights = [ { title: "Early detection", description: "Flag abusive text quickly with severity scoring tuned for safety triage.", icon: Alert02Icon }, { title: "Moderator workflow", description: "Review incidents, inspect signals, and track outcomes from one moderation queue.", icon: Analytics01Icon }, { title: "Bearer-secured API", description: "Supabase sessions flow from the app to FastAPI without exposing admin credentials.", icon: AiSecurity01Icon }];
const trustPoints = [ "Email and password sign-in with Supabase Auth", "FastAPI moderation API backed by Supabase Postgres", "Focused moderator review flow for MVP validation"];
const galleryImages = [ { src: "https://images.unsplash.com/photo-1516321318423-f06f85e504b3?auto=format&fit=crop&w=1200&q=80", alt: "People collaborating around a laptop in a digital workspace" }, { src: "https://images.unsplash.com/photo-1515378791036-0648a3ef77b2?auto=format&fit=crop&w=900&q=80", alt: "Person working on a laptop with messaging and productivity tools" }, { src: "https://images.unsplash.com/photo-1522202176988-66273c2fd55f?auto=format&fit=crop&w=900&q=80", alt: "Team discussion around shared work and online communication" }];
export default async function HomePage() { const session = await getSession();export default function HomePage() { redirect("/app");} if (session) { redirect("/app"); }
return ( <main className="min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(31,138,168,0.14),_transparent_28%),linear-gradient(180deg,_#ffffff_0%,_#f8f9fa_48%,_#eef5f7_100%)]"> <header className="mx-auto flex max-w-6xl items-center justify-between px-4 py-6 sm:px-6 lg:px-8"> <BrandLogo href="/" /> <div className="flex items-center gap-3"> <Link href="/sign-in" className="ui-secondary-button"> Sign in </Link> <Link href="/sign-up" className="ui-primary-button w-auto px-6"> Create account </Link> </div> </header>
<section className="mx-auto max-w-6xl px-4 pb-14 pt-6 sm:px-6 lg:px-8 lg:pb-20"> <div className="grid gap-10 lg:grid-cols-[1.05fr_0.95fr] lg:items-center"> <div className="space-y-7"> <div className="inline-flex items-center gap-2 rounded-full border border-line bg-white/90 px-4 py-2 text-sm font-bold text-ink shadow-[0_4px_20px_rgba(0,0,0,0.03)]"> <HugeiconsIcon icon={CheckmarkBadge01Icon} size={16} strokeWidth={1.9} aria-hidden /> Safer conversations, clearer moderation </div>
<div className="space-y-5"> <h1 className="ui-heading max-w-3xl text-5xl md:text-6xl"> Understand harmful messages before they escalate. </h1> <p className="max-w-2xl text-lg leading-8 text-muted md:text-xl"> CyBully is a focused cyberbullying detection workspace for submitting text, scoring risk, and giving moderators a fast path from signal to review. </p> </div>
<div className="flex flex-col gap-3 sm:flex-row"> <Link href="/sign-up" className="ui-primary-button w-full sm:w-auto sm:px-7"> Start with email </Link> <Link href="/sign-in" className="ui-secondary-button min-h-12 w-full sm:w-auto sm:px-6"> Sign in to dashboard </Link> </div>
<div className="grid gap-3 sm:grid-cols-3"> {featureHighlights.map((feature) => ( <div key={feature.title} className="rounded-2xl border border-line bg-white/88 px-5 py-5 shadow-[0_4px_20px_rgba(0,0,0,0.03)]" > <HugeiconsIcon icon={feature.icon} size={20} strokeWidth={1.9} aria-hidden /> <h2 className="mt-4 text-base font-bold text-ink">{feature.title}</h2> <p className="mt-2 text-sm leading-6 text-muted">{feature.description}</p> </div> ))} </div> </div>
<div className="grid gap-4 sm:grid-cols-[1.08fr_0.92fr]"> <div className="overflow-hidden rounded-2xl border border-line bg-white shadow-[0_10px_28px_rgba(16,20,24,0.08)]"> <Image src={galleryImages[0].src} alt={galleryImages[0].alt} width={1200} height={900} className="h-[420px] w-full object-cover" /> </div> <div className="grid gap-4"> {galleryImages.slice(1).map((image) => ( <div key={image.src} className="overflow-hidden rounded-2xl border border-line bg-white shadow-[0_10px_24px_rgba(16,20,24,0.08)]" > <Image src={image.src} alt={image.alt} width={900} height={700} className="h-[202px] w-full object-cover" /> </div> ))} </div> </div> </div> </section>
<section className="border-t border-black/5 bg-white/80"> <div className="mx-auto grid max-w-6xl gap-8 px-4 py-14 sm:px-6 lg:grid-cols-[0.9fr_1.1fr] lg:px-8 lg:py-16"> <div> <p className="text-sm font-bold uppercase tracking-[0.08em] text-brand"> What users get </p> <h2 className="mt-4 text-3xl font-normal leading-tight text-ink" style={{ letterSpacing: "-0.02em" }}> A lean workflow built for product validation, not presentation fluff. </h2> </div> <div className="grid gap-4 sm:grid-cols-3"> {trustPoints.map((point) => ( <div key={point} className="rounded-2xl border border-line bg-field px-5 py-5 text-sm font-medium leading-6 text-ink" > {point} </div> ))} </div> </div> </section> </main> );}23 unmodified lines242526272728293023 unmodified lines </div> </dl> <div className="mt-8"> <SignOutButton /> <SignOutButton variant="danger" /> </div> </section> </AppShell>11234345567891071191011121314151617181920211213141516"use client";import { AuthPanel } from "@/components/AuthPanel";import { getSession } from "@/lib/auth";import { redirect } from "next/navigation";
import { signIn } from "next-auth/react";import { HugeiconsIcon } from "@hugeicons/react";import { Login01Icon } from "@hugeicons/core-free-icons";export default async function SignInPage() { const session = await getSession(); if (session) { redirect("/app"); }
export default function SignInPage() { return ( <main className="flex min-h-screen items-center justify-center bg-surface px-4"> <section className="ui-card w-full max-w-md"> <h1 className="ui-section-title">Sign in to Cybully Safety</h1> <p className="mt-3 text-base leading-7 text-muted">Use the Google account configured for the MVP workspace.</p> <button type="button" onClick={() => signIn("google", { callbackUrl: "/app" })} className="ui-primary-button mt-8" > <HugeiconsIcon icon={Login01Icon} size={17} strokeWidth={1.9} aria-hidden /> Continue with Google </button> </section> <main className="flex min-h-screen items-center justify-center bg-surface px-4 py-8 sm:py-10"> <AuthPanel mode="sign-in" appName={process.env.NEXT_PUBLIC_APP_NAME ?? "Cybully Safety"} /> </main> );}12345678910111213141516import { AuthPanel } from "@/components/AuthPanel";import { getSession } from "@/lib/auth";import { redirect } from "next/navigation";
export default async function SignUpPage() { const session = await getSession(); if (session) { redirect("/app"); }
return ( <main className="flex min-h-screen items-center justify-center bg-surface px-4 py-8 sm:py-10"> <AuthPanel mode="sign-up" appName={process.env.NEXT_PUBLIC_APP_NAME ?? "Cybully Safety"} /> </main> );}1234123457678911121314151610181920111213241415162627282930313233343536371718192021223940414243444546474849505152232425import Link from "next/link";import { HugeiconsIcon } from "@hugeicons/react";import { SecurityCheckIcon, Settings01Icon, Shield01Icon, SentIcon } from "@hugeicons/core-free-icons";import type { Session } from "next-auth";import type { AppSession } from "@/lib/auth";import { BrandLogo } from "@/components/BrandLogo";import { ProfileMenu } from "@/components/ProfileMenu";
type AppShellProps = { session: Session; session: AppSession; children: React.ReactNode;};
const links = [ { href: "/app", label: "Submit", icon: SentIcon, role: "user" }, { href: "/moderation", label: "Moderation", icon: Shield01Icon, role: "moderator" }, { href: "/settings", label: "Settings", icon: Settings01Icon, role: "user" }];
export function AppShell({ session, children }: AppShellProps) { const role = session.user?.role ?? "user"; const visibleLinks = links.filter((link) => link.role === "user" || role === "moderator");
return ( <div className="min-h-screen bg-surface"> <header className="bg-surface"> <div className="mx-auto flex max-w-6xl flex-col gap-4 px-4 py-6 sm:px-6 lg:px-8"> <div className="mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-6 sm:px-6 lg:px-8"> <BrandLogo href="/app" className="min-w-0" /> <div className="flex items-center justify-between gap-4"> <Link href="/app" className="flex items-center gap-3 text-sm font-bold text-ink"> <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-brand text-white"> <HugeiconsIcon icon={SecurityCheckIcon} size={18} strokeWidth={1.9} aria-hidden /> </span> Cybully Safety </Link> <div className="flex items-center gap-3 text-sm text-muted"> <span className="hidden sm:inline">{session.user?.email}</span> <span className="rounded-xl border border-line bg-white px-3 py-2 text-xs font-bold uppercase tracking-normal"> {role} </span> </div> <ProfileMenu email={session.user?.email} name={session.user?.name} role={session.user?.role} /> </div> <nav className="flex gap-2 overflow-x-auto"> {visibleLinks.map((link) => { return ( <Link key={link.href} href={link.href} className="flex min-h-11 shrink-0 items-center gap-2 rounded-xl border border-line bg-white px-4 py-2 text-sm font-bold text-ink shadow-[0_4px_20px_rgba(0,0,0,0.03)] hover:border-brand hover:text-brand" > <HugeiconsIcon icon={link.icon} size={17} strokeWidth={1.9} aria-hidden /> {link.label} </Link> ); })} </nav> </div> </header> <main className="mx-auto max-w-6xl px-4 pb-12 sm:px-6 lg:px-8">{children}</main>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215"use client";
import Link from "next/link";import { useRouter } from "next/navigation";import { useState } from "react";import { HugeiconsIcon } from "@hugeicons/react";import { CheckmarkCircle01Icon, Login01Icon } from "@hugeicons/core-free-icons";
import { BrandLogo } from "@/components/BrandLogo";import { createClient } from "@/utils/supabase/client";
type AuthPanelProps = { mode: "sign-in" | "sign-up"; appName: string;};
function validateEmail(email: string): boolean { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);}
function normalizeMessage(message: string): string { if (message.toLowerCase().includes("email not confirmed")) { return "Sign-up succeeded, but email confirmation is still required before sign-in."; } return message;}
export function AuthPanel({ mode, appName }: AuthPanelProps) { const router = useRouter(); const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isSubmitting, setSubmitting] = useState(false); const [error, setError] = useState<string | null>(null); const [notice, setNotice] = useState<string | null>(null);
const isSignUp = mode === "sign-up";
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) { event.preventDefault(); setError(null); setNotice(null);
if (isSignUp && !name.trim()) { setError("Name is required."); return; } if (!validateEmail(email.trim().toLowerCase())) { setError("Enter a valid email address."); return; } if (password.length < 6) { setError("Password must be at least 6 characters."); return; }
setSubmitting(true); const supabase = createClient();
if (isSignUp) { const { data, error: signUpError } = await supabase.auth.signUp({ email: email.trim().toLowerCase(), password, options: { data: { full_name: name.trim() } } });
setSubmitting(false);
if (signUpError) { setError(normalizeMessage(signUpError.message)); return; }
if (data.session) { router.push("/app"); router.refresh(); return; }
setNotice("Account created. Check your email for a confirmation link, then sign in."); return; }
const { error: signInError } = await supabase.auth.signInWithPassword({ email: email.trim().toLowerCase(), password });
setSubmitting(false);
if (signInError) { setError(normalizeMessage(signInError.message)); return; }
router.push("/app"); router.refresh(); }
return ( <section className="ui-card w-full max-w-md px-6 py-8 sm:px-7 sm:py-9"> <BrandLogo href="/sign-in" className="mb-6" /> <h1 className="ui-section-title">{isSignUp ? `Create ${appName} account` : `Sign in to ${appName}`}</h1> <p className="mt-3 text-base leading-7 text-muted"> {isSignUp ? "Use Supabase email/password auth for the MVP workspace. New accounts must confirm their email before sign-in." : "Sign in with the email/password account provisioned in Supabase Auth."} </p>
{error ? ( <p className="mt-5 rounded-xl bg-danger px-4 py-3 text-center text-sm font-bold text-white"> {error} </p> ) : null}
{notice ? ( <p className="mt-5 rounded-xl border border-line bg-field px-4 py-3 text-center text-sm font-medium text-ink"> {notice} </p> ) : null}
<form className="mt-6 space-y-4" onSubmit={handleSubmit}> {isSignUp ? ( <div> <label htmlFor="name" className="ui-label"> Full name </label> <input id="name" name="name" type="text" autoComplete="name" value={name} onChange={(event) => setName(event.target.value)} className="ui-input" placeholder="Your full name" required /> </div> ) : null} <div> <label htmlFor="email" className="ui-label"> Email </label> <input id="email" name="email" type="email" autoComplete="email" value={email} onChange={(event) => setEmail(event.target.value)} className="ui-input" placeholder="you@example.com" required /> </div> <div> <label htmlFor="password" className="ui-label"> Password </label> <input id="password" name="password" type="password" autoComplete={isSignUp ? "new-password" : "current-password"} value={password} onChange={(event) => setPassword(event.target.value)} className="ui-input" placeholder="At least 6 characters" required /> </div>
<button type="submit" className="ui-primary-button" disabled={isSubmitting}> <HugeiconsIcon icon={isSignUp ? CheckmarkCircle01Icon : Login01Icon} size={17} strokeWidth={1.9} aria-hidden /> {isSubmitting ? "Please wait..." : isSignUp ? "Create account" : "Sign in"} </button> </form>
<div className="mt-6 rounded-xl border border-line bg-field px-4 py-3 text-sm text-muted"> <p className="font-medium text-ink">Moderator access</p> <p className="mt-1"> Sign in with an email listed in <code>MODERATOR_EMAILS</code> to unlock moderation screens. </p> </div>
<p className="mt-6 text-sm text-muted"> {isSignUp ? ( <> Already have an account?{" "} <Link href="/sign-in" className="font-bold text-brand hover:underline"> Sign in </Link> </> ) : ( <> Need an account?{" "} <Link href="/sign-up" className="font-bold text-brand hover:underline"> Create account </Link> </> )} </p> </section> );}1234567891011121314151617181920import Link from "next/link";import { Pacifico } from "next/font/google";
const pacifico = Pacifico({ subsets: ["latin"], weight: "400"});
type BrandLogoProps = { href?: string; className?: string;};
export function BrandLogo({ href = "/app", className = "" }: BrandLogoProps) { return ( <Link href={href} className={`inline-flex items-center ${className}`} aria-label="CyBully home"> <span className={`${pacifico.className} text-3xl leading-none text-ink`}>CyBully</span> </Link> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121"use client";
import Link from "next/link";import { useEffect, useMemo, useRef, useState } from "react";import { usePathname } from "next/navigation";import { HugeiconsIcon } from "@hugeicons/react";import { SentIcon, Settings01Icon, Shield01Icon, UserCircleIcon } from "@hugeicons/core-free-icons";
import { SignOutButton } from "@/components/SignOutButton";
type ProfileMenuProps = { email?: string | null; name?: string | null; role?: "user" | "moderator";};
const links = [ { href: "/app", label: "Submit", icon: SentIcon, role: "user" }, { href: "/moderation", label: "Moderation", icon: Shield01Icon, role: "moderator" }, { href: "/settings", label: "Settings", icon: Settings01Icon, role: "user" }] as const;
function profileInitial(name?: string | null, email?: string | null): string { const source = name?.trim() || email?.trim() || "U"; return source.charAt(0).toUpperCase();}
export function ProfileMenu({ email, name, role = "user" }: ProfileMenuProps) { const pathname = usePathname(); const [isOpen, setOpen] = useState(false); const menuRef = useRef<HTMLDivElement>(null); const visibleLinks = useMemo( () => links.filter((link) => link.role === "user" || role === "moderator"), [role] ); const initial = profileInitial(name, email);
useEffect(() => { function handlePointerDown(event: MouseEvent) { if (!menuRef.current?.contains(event.target as Node)) { setOpen(false); } }
function handleEscape(event: KeyboardEvent) { if (event.key === "Escape") { setOpen(false); } }
document.addEventListener("mousedown", handlePointerDown); document.addEventListener("keydown", handleEscape); return () => { document.removeEventListener("mousedown", handlePointerDown); document.removeEventListener("keydown", handleEscape); }; }, []);
return ( <div ref={menuRef} className="relative"> <button type="button" aria-haspopup="menu" aria-expanded={isOpen} aria-label="Open profile menu" onClick={() => setOpen((current) => !current)} className="focus-ring flex h-12 w-12 items-center justify-center rounded-full border border-line bg-white text-sm font-bold text-ink shadow-[0_4px_20px_rgba(0,0,0,0.03)] hover:border-brand hover:text-brand" > {name || email ? ( <span aria-hidden>{initial}</span> ) : ( <HugeiconsIcon icon={UserCircleIcon} size={20} strokeWidth={1.9} aria-hidden /> )} </button>
{isOpen ? ( <div className="absolute right-0 top-14 z-20 w-72 rounded-2xl border border-line bg-white p-4 shadow-[0_14px_32px_rgba(16,20,24,0.12)]"> <div className="rounded-2xl bg-field px-4 py-4"> <div className="flex items-center gap-3"> <span className="flex h-12 w-12 items-center justify-center rounded-full bg-brand text-base font-bold text-white"> {initial} </span> <div className="min-w-0"> <p className="truncate text-sm font-bold text-ink">{name ?? "Preview account"}</p> <p className="truncate text-sm text-muted">{email ?? "No email"}</p> </div> </div> </div>
<nav className="mt-4 space-y-2" aria-label="Profile navigation"> {visibleLinks.map((link) => { const isActive = pathname === link.href || (link.href !== "/app" && pathname.startsWith(link.href));
return ( <Link key={link.href} href={link.href} onClick={() => setOpen(false)} className={`flex min-h-11 items-center gap-3 rounded-xl px-4 py-3 text-sm font-bold transition-colors ${ isActive ? "bg-field text-brand" : "text-ink hover:bg-field hover:text-brand" }`} > <HugeiconsIcon icon={link.icon} size={18} strokeWidth={1.9} aria-hidden /> {link.label} </Link> ); })} </nav>
<div className="mt-4 border-t border-line pt-4"> <SignOutButton variant="danger" fullWidth /> </div> </div> ) : null} </div> );}1 unmodified line23455678910111213141516171819202122232425262728297303110323312343536371 unmodified line
import { HugeiconsIcon } from "@hugeicons/react";import { Logout01Icon } from "@hugeicons/core-free-icons";import { signOut } from "next-auth/react";import { useRouter } from "next/navigation";
import { createClient } from "@/utils/supabase/client";
type SignOutButtonProps = { fullWidth?: boolean; variant?: "neutral" | "danger";};
export function SignOutButton({ fullWidth = false, variant = "neutral" }: SignOutButtonProps) { const router = useRouter(); const className = variant === "danger" ? `focus-ring inline-flex min-h-11 items-center justify-center gap-2 rounded-xl border border-red-200 bg-red-50 px-4 py-2 text-sm font-bold text-red-700 hover:bg-red-100 ${ fullWidth ? "w-full" : "" }` : `ui-secondary-button ${fullWidth ? "w-full" : ""}`;
async function handleSignOut() { const supabase = createClient(); await supabase.auth.signOut(); router.push("/sign-in"); router.refresh(); }
export function SignOutButton() { return ( <button className="ui-secondary-button" className={className} type="button" onClick={() => signOut({ callbackUrl: "/sign-in" })} onClick={handleSignOut} > <HugeiconsIcon icon={Logout01Icon} size={16} strokeWidth={1.9} aria-hidden /> Sign out1212345678910111213141516171819202122678910111213141516171819202122232425262724252628282930313031323334353634353637383940413738394041424344454647484950435152535455565758596061import { getServerSession, type NextAuthOptions } from "next-auth";import GoogleProvider from "next-auth/providers/google";import type { User } from "@supabase/supabase-js";
import { isModeratorEmail } from "@/lib/env";import { createClient } from "@/utils/supabase/server";
export const authOptions: NextAuthOptions = { providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID ?? "", clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? "" }) ], callbacks: { async session({ session }) { const email = session.user?.email; return { ...session, user: { ...session.user, role: isModeratorEmail(email) ? "moderator" : "user" } };export type AppSession = { accessToken: string | null; user: { id: string; email: string | null; name: string | null; role: "user" | "moderator"; };};
function userDisplayName(user: User): string | null { const metadata = user.user_metadata; if (metadata && typeof metadata === "object") { const fullName = metadata.full_name; if (typeof fullName === "string" && fullName.trim()) { return fullName.trim(); }
const name = metadata.name; if (typeof name === "string" && name.trim()) { return name.trim(); } }, pages: { signIn: "/sign-in" }};
export function getSession() { return getServerSession(authOptions); if (user.email) { return user.email.split("@")[0] ?? null; }
return null;}
declare module "next-auth" { interface Session { user?: { name?: string | null; email?: string | null; image?: string | null; role?: "user" | "moderator"; };export async function getSession(): Promise<AppSession | null> { const supabase = createClient(); const { data: { user }, error } = await supabase.auth.getUser();
const { data: { session } } = await supabase.auth.getSession();
if (error || !user) { return null; }}
return { accessToken: session?.access_token ?? null, user: { id: user.id, email: user.email ?? null, name: userDisplayName(user), role: isModeratorEmail(user.email) ? "moderator" : "user" } };}12345675 unmodified lines1314151617181920212223242526272817181920293031325 unmodified lines38394032import { apiBaseUrl, backendInternalToken } from "@/lib/env";
type BackendFetchOptions = { authToken?: string | null; method?: "GET" | "POST" | "PATCH"; body?: unknown; query?: URLSearchParams;5 unmodified lines options.query.forEach((value, key) => url.searchParams.set(key, value)); }
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (options.authToken) { headers.Authorization = `Bearer ${options.authToken}`; headers.apikey = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ?? ""; } else { headers["X-Internal-Token"] = backendInternalToken(); }
const response = await fetch(url, { method: options.method ?? "GET", headers: { "Content-Type": "application/json", "X-Internal-Token": backendInternalToken() }, headers, body: options.body ? JSON.stringify(options.body) : undefined, cache: "no-store" });5 unmodified lines
return response.json() as Promise<T>;}
123245677 unmodified lines151617161819202120222322import { serverEnv } from "@/lib/server-env";
export function moderatorEmails(): string[] { return (process.env.MODERATOR_EMAILS ?? "") return (serverEnv("MODERATOR_EMAILS") ?? "") .split(",") .map((email) => email.trim().toLowerCase()) .filter(Boolean);7 unmodified lines}
export function apiBaseUrl(): string { return process.env.API_BASE_URL ?? "http://localhost:8000"; return serverEnv("API_BASE_URL") ?? "http://localhost:8000";}
export function backendInternalToken(): string { return process.env.BACKEND_INTERNAL_TOKEN ?? "dev-internal-token"; return serverEnv("BACKEND_INTERNAL_TOKEN") ?? "dev-internal-token";}
3 unmodified lines4567789103 unmodified lines
export async function requireUser() { const session = await getSession(); if (!session?.user?.email) { if (!session?.user?.email || !session.accessToken) { redirect("/sign-in"); } return session;1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import fs from "node:fs";import path from "node:path";
const candidateDirectories = [ process.cwd(), path.resolve(process.cwd(), ".."), path.resolve(process.cwd(), "..", "..")];
const candidateFiles = [".env.local", ".env"];
let cachedEnv: Map<string, string> | null = null;
function parseLine(line: string): [string, string] | null { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) { return null; }
const separatorIndex = trimmed.indexOf("="); if (separatorIndex === -1) { return null; }
const key = trimmed.slice(0, separatorIndex).trim(); const rawValue = trimmed.slice(separatorIndex + 1).trim(); const value = rawValue.replace(/^['"]|['"]$/g, "");
return key ? [key, value] : null;}
function loadFallbackEnv(): Map<string, string> { const envMap = new Map<string, string>();
for (const directory of candidateDirectories) { for (const filename of candidateFiles) { const filePath = path.join(directory, filename); if (!fs.existsSync(filePath)) { continue; }
const fileContents = fs.readFileSync(filePath, "utf8"); for (const line of fileContents.split(/\r?\n/)) { const entry = parseLine(line); if (!entry) { continue; }
const [key, value] = entry; if (!envMap.has(key)) { envMap.set(key, value); } } } }
return envMap;}
export function serverEnv(name: string): string | undefined { const directValue = process.env[name]; if (directValue) { return directValue; }
cachedEnv ??= loadFallbackEnv(); return cachedEnv.get(name);}1234567891011import { type NextRequest } from "next/server";
import { updateSession } from "@/utils/supabase/middleware";
export async function middleware(request: NextRequest) { return updateSession(request);}
export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"]};12345678import { createBrowserClient } from "@supabase/ssr";
export function createClient() { return createBrowserClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY! );}1234567891011121314151617181920212223242526272829303132333435import { createServerClient } from "@supabase/ssr";import { type NextRequest, NextResponse } from "next/server";
export async function updateSession(request: NextRequest) { let response = NextResponse.next({ request: { headers: request.headers } });
const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, { cookies: { getAll() { return request.cookies.getAll(); }, setAll(cookiesToSet) { cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value)); response = NextResponse.next({ request }); cookiesToSet.forEach(({ name, value, options }) => response.cookies.set(name, value, options) ); } } } );
await supabase.auth.getUser();
return response;}123456789101112131415161718192021222324252627import { createServerClient } from "@supabase/ssr";import { cookies } from "next/headers";
export function createClient() { const cookieStore = cookies();
return createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, { cookies: { getAll() { return cookieStore.getAll(); }, setAll(cookiesToSet) { try { cookiesToSet.forEach(({ name, value, options }) => { cookieStore.set(name, value, options); }); } catch { // Server Components can't always persist cookies directly. } } } } );}6 unmodified lines7891010111213141516171819162021222023242548 unmodified lines7475767576777879808182838485868788899091929394959697989910010110210310410577787925 unmodified lines105106107108109110111972 unmodified lines108410851086111511161117111811191120112111221123108710881089369 unmodified lines1459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573119 unmodified lines1693169416951624162516261627162816291696169716981461 unmodified lines3160316131623097309830993100310131023103310431053163316431651610 unmodified lines477647774778477947804781478247834784478547864787478847894790591 unmodified lines538253835384531953205321532253235324532553265327538553865387448 unmodified lines5836583758385782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158395840584175 unmodified lines5917591859195913591459155916591759185919592059215922592359245925592659275920592159224 unmodified lines592759285929593859395940594159425943594459455946593059315932107 unmodified lines6040604160426060606160626063606460656066606760686043604460454 unmodified lines605060516052607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114605360546055393 unmodified lines64496450645165146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416452645364541535 unmodified lines7990799179928083808480858086808780888089809080918092799379947995483 unmodified lines8479848084818582858385848585858685878482848384846 unmodified lines "name": "cybully", "workspaces": [ "apps/web" ] ], "dependencies": { "@supabase/ssr": "^0.10.3", "@supabase/supabase-js": "^2.106.0" } }, "apps/web": { "name": "@cybully/web", "version": "0.1.0", "dependencies": { "@auth/core": "^0.34.0", "@hugeicons/core-free-icons": "^4.1.4", "@hugeicons/react": "^1.1.6", "next": "^14.2.0", "next-auth": "^4.24.11", "react": "^18.3.1", "react-dom": "^18.3.1" },48 unmodified lines "lru-cache": "^10.4.3" } }, "node_modules/@auth/core": { "version": "0.34.3", "resolved": "https://registry.npmjs.org/@auth/core/-/core-0.34.3.tgz", "integrity": "sha512-jMjY/S0doZnWYNV90x0jmU3B+UcrsfGYnukxYrRbj0CVvGI/MX3JbHsxSrx2d4mbnXaUsqJmAcDfoQWA6r0lOw==", "license": "ISC", "dependencies": { "@panva/hkdf": "^1.1.1", "@types/cookie": "0.6.0", "cookie": "0.6.0", "jose": "^5.1.3", "oauth4webapi": "^2.10.4", "preact": "10.11.3", "preact-render-to-string": "5.2.3" }, "peerDependencies": { "@simplewebauthn/browser": "^9.0.1", "@simplewebauthn/server": "^9.0.2", "nodemailer": "^7" }, "peerDependenciesMeta": { "@simplewebauthn/browser": { "optional": true }, "@simplewebauthn/server": { "optional": true }, "nodemailer": { "optional": true } } }, "node_modules/@babel/code-frame": { "version": "7.29.0", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",25 unmodified lines "version": "7.29.2", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz", "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==", "dev": true, "license": "MIT", "engines": { "node": ">=6.9.0"972 unmodified lines "node": ">=12.4.0" } }, "node_modules/@panva/hkdf": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/@panva/hkdf/-/hkdf-1.2.1.tgz", "integrity": "sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/panva" } }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",369 unmodified lines "dev": true, "license": "MIT" }, "node_modules/@supabase/auth-js": { "version": "2.106.0", "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.106.0.tgz", "integrity": "sha512-JY7602OvjK2l3BjsQkpePpxR+6P0iG37gCrZNWAMhAuNh1iFnhGRwj/y5EshUG0INMPGFrj0UA9MErQ/kOEKFg==", "license": "MIT", "dependencies": { "tslib": "2.8.1" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@supabase/functions-js": { "version": "2.106.0", "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.106.0.tgz", "integrity": "sha512-ADIkJYH5w7HbnGVAAlCbyKoLF5QdfyezBLfYXpUqhxZOacK6YepOvnP/8p4p+50bhTPWp6VhDxu19KO7e/qU2g==", "license": "MIT", "dependencies": { "tslib": "2.8.1" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@supabase/phoenix": { "version": "0.4.2", "resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.2.tgz", "integrity": "sha512-YSAGnmDAfuleFCVt3CeurQZAhxRfXWeZIIkwp7NhYzQ1UwW6ePSnzsFAiUm/mbCkfoCf70QQHKW/K6RKh52a4A==", "license": "MIT" }, "node_modules/@supabase/postgrest-js": { "version": "2.106.0", "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.106.0.tgz", "integrity": "sha512-vNKFAXQrtmUn7J3LbN+uMlt0jciAwRIBpdy6Do4DKrpf1xj0kJhbqXTX4y8ziewWUEEx8G5GPnDmprXXaO9f3w==", "license": "MIT", "dependencies": { "tslib": "2.8.1" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@supabase/realtime-js": { "version": "2.106.0", "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.106.0.tgz", "integrity": "sha512-mYZoaYpkyjlecixbvxCu0h3jw12uHfEcUqNdaRATNI8zQVI5arels+VJzAGcHwNiD+/Juv0OXIuk+M7SHsdI4A==", "license": "MIT", "dependencies": { "@supabase/phoenix": "^0.4.2", "tslib": "2.8.1" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@supabase/ssr": { "version": "0.10.3", "resolved": "https://registry.npmjs.org/@supabase/ssr/-/ssr-0.10.3.tgz", "integrity": "sha512-ux2CJgX89h0Fz2lY7ZNafNG2SkXpyRc5dz77K9eKeBLPdtywQixKwIuetDeIViAJBp/buOUVmgj8PVesOklNpw==", "license": "MIT", "dependencies": { "cookie": "^1.0.2" }, "peerDependencies": { "@supabase/supabase-js": "^2.105.3" } }, "node_modules/@supabase/ssr/node_modules/cookie": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", "license": "MIT", "engines": { "node": ">=18" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, "node_modules/@supabase/storage-js": { "version": "2.106.0", "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.106.0.tgz", "integrity": "sha512-BHc3nIjD3zfdDxBenphXrLJSoQ+qwo24VD96cVzmjBFbQVk5krvwRNUXrA5ozPplA3Vhlst2d/hy9R9ViqH2lg==", "license": "MIT", "dependencies": { "iceberg-js": "^0.8.1", "tslib": "2.8.1" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@supabase/supabase-js": { "version": "2.106.0", "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.106.0.tgz", "integrity": "sha512-OOoo3sLj9iVXNp6b+fkyOfFeQrvvNy7nQbaONNf72dOaictUeS39hFDS9argIRTag6M3ZxIypNWcrDAwLgUihQ==", "license": "MIT", "dependencies": { "@supabase/auth-js": "2.106.0", "@supabase/functions-js": "2.106.0", "@supabase/postgrest-js": "2.106.0", "@supabase/realtime-js": "2.106.0", "@supabase/storage-js": "2.106.0" }, "engines": { "node": ">=20.0.0" } }, "node_modules/@swc/counter": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",119 unmodified lines "license": "MIT", "peer": true }, "node_modules/@types/cookie": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==", "license": "MIT" }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",1461 unmodified lines "dev": true, "license": "MIT" }, "node_modules/cookie": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", "license": "MIT", "engines": { "node": ">= 0.6" } }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",1610 unmodified lines "node": ">= 14" } }, "node_modules/iceberg-js": { "version": "0.8.1", "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz", "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==", "license": "MIT", "engines": { "node": ">=20.0.0" } }, "node_modules/iconv-lite": { "version": "0.6.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",591 unmodified lines "jiti": "bin/jiti.js" } }, "node_modules/jose": { "version": "5.10.0", "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz", "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/panva" } }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",448 unmodified lines } } }, "node_modules/next-auth": { "version": "4.24.14", "resolved": "https://registry.npmjs.org/next-auth/-/next-auth-4.24.14.tgz", "integrity": "sha512-YRz6xFDXKUwiXSMMChbrBEWyFktZ1qZXEgeSHQQ3nsy08B4c/xLk6REeutRsIFwkjY/1+ShHnu07DN3JeJguig==", "license": "ISC", "dependencies": { "@babel/runtime": "^7.20.13", "@panva/hkdf": "^1.0.2", "cookie": "^0.7.0", "jose": "^4.15.5", "oauth": "^0.9.15", "openid-client": "^5.4.0", "preact": "^10.6.3", "preact-render-to-string": "^5.1.19", "uuid": "^8.3.2" }, "peerDependencies": { "@auth/core": "0.34.3", "next": "^12.2.5 || ^13 || ^14 || ^15 || ^16", "nodemailer": "^7.0.7", "react": "^17.0.2 || ^18 || ^19", "react-dom": "^17.0.2 || ^18 || ^19" }, "peerDependenciesMeta": { "@auth/core": { "optional": true }, "nodemailer": { "optional": true } } }, "node_modules/next-auth/node_modules/cookie": { "version": "0.7.2", "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", "license": "MIT", "engines": { "node": ">= 0.6" } }, "node_modules/next-auth/node_modules/jose": { "version": "4.15.9", "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/panva" } }, "node_modules/next/node_modules/postcss": { "version": "8.4.31", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",75 unmodified lines "dev": true, "license": "MIT" }, "node_modules/oauth": { "version": "0.9.15", "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", "integrity": "sha512-a5ERWK1kh38ExDEfoO6qUHJb32rd7aYmPHuyCu3Fta/cnICvYmgd2uhuKXvPD+PXB+gCEYYEaQdIRAjCOwAKNA==", "license": "MIT" }, "node_modules/oauth4webapi": { "version": "2.17.0", "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-2.17.0.tgz", "integrity": "sha512-lbC0Z7uzAFNFyzEYRIC+pkSVvDHJTbEW+dYlSBAlCYDe6RxUkJ26bClhk8ocBZip1wfI9uKTe0fm4Ib4RHn6uQ==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/panva" } }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",4 unmodified lines "node": ">=0.10.0" } }, "node_modules/object-hash": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz", "integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==", "license": "MIT", "engines": { "node": ">= 6" } }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",107 unmodified lines "url": "https://github.com/sponsors/ljharb" } }, "node_modules/oidc-token-hash": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz", "integrity": "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==", "license": "MIT", "engines": { "node": "^10.13.0 || >=12.0.0" } }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",4 unmodified lines "wrappy": "1" } }, "node_modules/openid-client": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.7.1.tgz", "integrity": "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew==", "license": "MIT", "dependencies": { "jose": "^4.15.9", "lru-cache": "^6.0.0", "object-hash": "^2.2.0", "oidc-token-hash": "^5.0.3" }, "funding": { "url": "https://github.com/sponsors/panva" } }, "node_modules/openid-client/node_modules/jose": { "version": "4.15.9", "resolved": "https://registry.npmjs.org/jose/-/jose-4.15.9.tgz", "integrity": "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/panva" } }, "node_modules/openid-client/node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", "license": "ISC", "dependencies": { "yallist": "^4.0.0" }, "engines": { "node": ">=10" } }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",393 unmodified lines "dev": true, "license": "MIT" }, "node_modules/preact": { "version": "10.11.3", "resolved": "https://registry.npmjs.org/preact/-/preact-10.11.3.tgz", "integrity": "sha512-eY93IVpod/zG3uMF22Unl8h9KkrcKIRs2EGar8hwLZZDU1lkjph303V9HZBwufh2s736U6VXuhD109LYqPoffg==", "license": "MIT", "funding": { "type": "opencollective", "url": "https://opencollective.com/preact" } }, "node_modules/preact-render-to-string": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-5.2.3.tgz", "integrity": "sha512-aPDxUn5o3GhWdtJtW0svRC2SS/l8D9MAgo2+AWml+BhDImb27ALf04Q2d+AHqUUOc6RdSXFIBVa2gxzgMKgtZA==", "license": "MIT", "dependencies": { "pretty-format": "^3.8.0" }, "peerDependencies": { "preact": ">=10" } }, "node_modules/preact-render-to-string/node_modules/pretty-format": { "version": "3.8.0", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-3.8.0.tgz", "integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==", "license": "MIT" }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",1535 unmodified lines "dev": true, "license": "MIT" }, "node_modules/uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).", "license": "MIT", "bin": { "uuid": "dist/bin/uuid" } }, "node_modules/vite": { "version": "5.4.21", "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",483 unmodified lines "dev": true, "license": "MIT" }, "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "license": "ISC" }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",8 unmodified lines91011121314151617148 unmodified lines "build:web": "npm --workspace apps/web run build", "lint:web": "npm --workspace apps/web run lint", "test:web": "npm --workspace apps/web run test" }, "dependencies": { "@supabase/ssr": "^0.10.3", "@supabase/supabase-js": "^2.106.0" }}
123456768910111213141516171819202122232425102627282930313213333435363738from __future__ import annotations
from functools import lru_cachefrom pathlib import Pathfrom typing import Annotated
from pydantic import Field, field_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDictfrom pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
def default_env_files() -> tuple[str, ...]: config_file = Path(__file__).resolve() repo_root = config_file.parents[4] api_root = config_file.parents[2]
candidates = ( repo_root / ".env", repo_root / ".env.local", api_root / ".env", api_root / ".env.local", ) return tuple(str(path) for path in candidates)
class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore") model_config = SettingsConfigDict( env_file=default_env_files(), env_file_encoding="utf-8", extra="ignore", )
environment: str = "development" allowed_cors_origins: list[str] = Field(default_factory=lambda: ["http://localhost:3000"]) allowed_cors_origins: Annotated[list[str], NoDecode] = Field( default_factory=lambda: ["http://localhost:3000"] ) backend_internal_token: str = "dev-internal-token" supabase_url: str | None = None supabase_publishable_key: str | None = None1234567891011from pathlib import Path
from app.core.config import default_env_files
def test_default_env_files_include_repo_root_env() -> None: repo_root = Path(__file__).resolve().parents[3] env_files = {Path(path) for path in default_env_files()}
assert repo_root.joinpath(".env") in env_files assert repo_root.joinpath(".env.local") in env_files.env.example+2-5
README.md+23-17
apps/web/next.config.mjs+9-2
apps/web/package.json-2
apps/web/src/app/api/alerts/route.ts+4-2
apps/web/src/app/api/analyze/text/route.ts+2-2
apps/web/src/app/api/auth/[...nextauth]/route.tsDeleted-8
apps/web/src/app/api/incidents/[id]/route.ts+4-2
apps/web/src/app/api/incidents/route.ts+4-2
apps/web/src/app/moderation/incidents/[id]/page.tsx+3-1
apps/web/src/app/moderation/page.tsx+7-3
apps/web/src/app/page.tsx+166-3
apps/web/src/app/settings/page.tsx+1-1
apps/web/src/app/sign-in/page.tsx+10-18
apps/web/src/app/sign-up/page.tsxAdded+16
apps/web/src/components/AppShell.tsx+11-41
apps/web/src/components/AuthPanel.tsxAdded+215
apps/web/src/components/BrandLogo.tsxAdded+20
apps/web/src/components/ProfileMenu.tsxAdded+121
apps/web/src/components/SignOutButton.tsx+26-4
apps/web/src/lib/auth.ts+51-34
apps/web/src/lib/backend.ts+13-5
apps/web/src/lib/env.ts+5-4
apps/web/src/lib/guards.ts+1-1
apps/web/src/lib/server-env.tsAdded+68
apps/web/src/middleware.tsAdded+11
apps/web/src/utils/supabase/client.tsAdded+8
apps/web/src/utils/supabase/middleware.tsAdded+35
apps/web/src/utils/supabase/server.tsAdded+27
package-lock.json+124-230
package.json+4-1
services/api/app/core/config.py+25-3
services/api/tests/test_config.pyAdded+11