Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ jobs:

- run: npm run lint

- name: Test demo isolation and school login
run: npm run test --workspace=apps/admin

- name: Build admin console
run: npm run build --workspace=apps/admin

Expand Down
21 changes: 18 additions & 3 deletions PROJECT_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ This file is the single source of truth for project state. Every agent must read
| Helpers | `src/lib/utils.ts` | Dates, INR, CSV parser, `normalizeDob` (rejects 31 Feb), `passwordFromDob`, `gradeFor`, `printHtml` |
| Supabase client | `src/lib/supabase.ts` | Reads `SUPABASE_URL` / `SUPABASE_PUBLISHABLE_KEY`; `configHint()` names the missing pair |
| Build config | `vite.config.ts` | `loadEnv(mode, cwd, '')` so **unprefixed** `SUPABASE_URL` works from `.env`; inlines both names via `define` |
| Login | `src/pages/Login.tsx` | School design; small passwordless **"Try a demo"** button (Admin / Teacher / Student picker, demo mode only); remembered account |
| Demo entry | `src/contexts/AuthContext.tsx` | `signInAsDemo(role)` signs in as the seeded person for the role; refused whenever a Supabase client exists; no credentials anywhere in the client |
| Login | `src/pages/Login.tsx` | School design; always-visible **"Try a demo"** button (Admin / Teacher / Student), including with Supabase configured; remembered account |
| Demo entry | `src/contexts/AuthContext.tsx` | `signInAsDemo(role)` opens isolated `/demo` with a seeded role; `src/lib/demo.ts` defines the route boundary; no Supabase client is created inside `/demo` |

### Dashboard modules

Expand Down Expand Up @@ -61,7 +61,7 @@ This file is the single source of truth for project state. Every agent must read
| Admin bootstrap | `scripts/create-admin.mjs` | Local-only, service role from environment |
| CI | `.github/workflows/ci.yml` | Rewritten (the committed file was a single line of literal `\n`): typecheck, lint, build, secret guard, env-name guard |

### Demo entry + credential removal (2026-11-05)
### Original demo entry + credential removal (2026-11-05; visibility restriction superseded below)

- Login page has a small "Try a demo" button that expands into Admin / Teacher / Student options; one click enters that role's dashboard with no login. Shown only in demo mode (no Supabase configured); `signInAsDemo` refuses when a Supabase client exists, so the client never decides identity against a live backend.
- Demo teacher display name is now **Teacher** (seed profile, sample notification, and teaching-assignment sample row). Existing `v3` demo data migrates to `v4` without resetting other demo edits. Verified: admin typecheck/lint/build clean; 39 role smoke checks and 6 storage-migration checks pass; production bundle contains no old display name.
Expand All @@ -70,6 +70,21 @@ This file is the single source of truth for project state. Every agent must read
- The school's `Student@DDMMYYYY` initial-password rule is unchanged — it is derived from DOB at runtime (`utils.ts`, `admin-users` Edge Function), never stored as a literal.
- Verified: admin + shared typecheck clean; eslint 0 errors; production build passes; `grep` of `dist/assets/*.js` finds zero credential strings and the demo button ships in the bundle (works on a deployed demo-mode build). jsdom smoke test clicked through all three roles: correct seeded identity, role-aware nav, sign-out returns to login — 39/39 checks pass.

### Demo visibility investigation (2026-11-05; before the fix below)

- Read-only application/configuration review confirmed the demo picker exists in `apps/admin/src/pages/Login.tsx`, but renders only when `missingSupabaseConfig()` is true (`src/lib/supabase.ts`, `src/contexts/AuthContext.tsx`). Network unavailability does not enable demo mode; the presence of both public configuration values disables the picker.
- Vercel metadata confirms the latest ready production deployment uses commit `29681ccca26a4af81602b2e072fe9018c5efe4fe` (the inspected source), and the project has `SUPABASE_URL` and `SUPABASE_PUBLISHABLE_KEY` configured for production. This explains the hidden production demo entry; no secrets were decrypted and no deployment/settings were changed. Live browser behaviour was not tested in this investigation.
- The separate header **View as** control in `src/components/AppShell.tsx` is available only after signing in with an admin profile. Next: decide whether to offer a separate isolated demo deployment or implement an explicit isolated demo experience alongside live login; do not remove production authentication configuration to expose the picker.

### Demo alongside configured Supabase (2026-11-05)

- Owner requested demos on the configured production site without creating accounts. `apps/admin/src/pages/Login.tsx` now always offers **Try a demo → Admin / Teacher / Student**; the signed-in header also links to `/demo/login`. Live login remains visible while auth restoration is pending, so slow Supabase does not hide demo entry.
- `src/lib/demo.ts`, `src/lib/supabase.ts`, `src/contexts/AuthContext.tsx`, and `src/App.tsx` isolate the showcase under `/demo` using full-page entry/exit and a separate router base. No Supabase client or live auth subscription is created there; backend session identity stays null. The seeded role survives refresh in tab-local storage. Invalid roles are rejected; demo sign-out does not sign out a real account.
- `src/lib/appData.tsx` stores showcase edits separately (`pws.showcase.data.v1`), with no migration from the school-console store. `src/components/AppShell.tsx` displays a persistent sample-data banner and **Exit demo · School sign in**. Demo login never displays a remembered real account.
- Added Vitest/jsdom regression tests under `apps/admin/tests/`, `vitest.config.ts`, the `test` workspace script, and a CI test step. Verified: 10 tests pass (all roles, configured Supabase, direct entry, refresh, sign-out, data/reset isolation, blocked storage, invalid roles, pending auth, normal password login); admin/shared typechecks pass; admin lint has 0 errors and 3 existing fast-refresh warnings; production build passes (bundle-size warning only).
- PR #4 review follow-up: school password submission waits for session restoration (including Enter-key submission), while demo links remain available. Added regression assertions for this race; async mount checks use a closure to avoid incorrect static narrowing across `await`.
- Updated `docs/security/environment-variables.md` and the design decision log. No production environment variables, auth accounts, database policies, or deployments changed. Next: deploy this branch's changes to make the demo entry visible on the production site; keep future backend modules isolated from `/demo`.

### Verification done

- `npm run typecheck --workspace=apps/admin` — clean.
Expand Down
9 changes: 7 additions & 2 deletions apps/admin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"typecheck": "tsc -b --noEmit"
"typecheck": "tsc -b --noEmit",
"test": "vitest run"
},
"dependencies": {
"@schoolerp/shared": "*",
Expand All @@ -24,6 +25,8 @@
},
"devDependencies": {
"@eslint/js": "^10.0.0",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.8",
"@types/node": "^24.6.0",
"@types/react": "^19.1.16",
"@types/react-dom": "^19.1.9",
Expand All @@ -35,10 +38,12 @@
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
"globals": "^16.4.0",
"jsdom": "^31.0.0",
"postcss": "^8.5.32",
"tailwindcss": "^3.4.19",
"typescript": "~5.9.3",
"typescript-eslint": "^8.45.0",
"vite": "^7.1.7"
"vite": "^7.1.7",
"vitest": "^5.1.0"
}
}
6 changes: 4 additions & 2 deletions apps/admin/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ReactNode } from 'react';
import { BrowserRouter, Navigate, Routes, Route, useLocation } from 'react-router-dom';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import { isDemoPath } from './lib/demo';
import { AppDataProvider } from './lib/appData';
import AppShell from './components/AppShell';
import Login from './pages/Login';
Expand Down Expand Up @@ -37,7 +38,8 @@ function RequireAuth({ children }: { children: ReactNode }) {

function GuestOnly({ children }: { children: ReactNode }) {
const { loading, profile } = useAuth();
if (loading) return null;
// Demo entry must remain available while live auth is slow or offline.
if (loading) return <>{children}</>;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: If school login is submitted before session restoration finishes, the initial session’s delayed profile lookup can complete after sign-in and replace the new user’s profile with the old one.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Race condition

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** apps/admin/src/App.tsx
**Line:** 42:42
**Comment:**
	*Race Condition: If school login is submitted before session restoration finishes, the initial session’s delayed profile lookup can complete after sign-in and replace the new user’s profile with the old one.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

return profile ? <Navigate to="/dashboard" replace /> : <>{children}</>;
}

Expand All @@ -57,7 +59,7 @@ export default function App() {
return (
<AuthProvider>
<AppDataProvider>
<BrowserRouter>
<BrowserRouter basename={isDemoPath ? '/demo' : '/'}>
<Routes>
<Route
path="/login"
Expand Down
15 changes: 12 additions & 3 deletions apps/admin/src/components/AppShell.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState, useMemo, type ReactNode } from 'react';
import { useNavigate, useLocation, Link, Outlet } from 'react-router-dom';
import { isDemoPath } from '../lib/demo';
import { useAuth } from '../contexts/AuthContext';
import { useAppData } from '../lib/appData';
import { cn, initials } from '../lib/utils';
Expand Down Expand Up @@ -283,7 +284,7 @@ export default function AppShell({ children }: { children?: ReactNode }) {
<div className="mb-3 rounded-lg border border-amber-100 bg-amber-50 p-2.5">
<div className="text-[11px] font-semibold text-amber-800">Demo data</div>
<div className="mt-0.5 text-[10px] leading-snug text-amber-700">
Supabase keys are not set, so the console runs on the seeded school.
Sample data only. Changes stay in this browser and never affect school records.
</div>
<button
onClick={() => data.resetDemoData()}
Expand Down Expand Up @@ -357,8 +358,10 @@ export default function AppShell({ children }: { children?: ReactNode }) {
Config
</Badge>
)}
{/* Gate on the REAL profile role, not the view-as override, so an
admin previewing another role can always switch back. */}
{!isDemoPath && (
<a href="/demo/login" className="text-xs font-medium text-olive underline underline-offset-2">Try a demo</a>
)}
{/* Gate on the real profile so an admin can always switch back. */}
{profile?.role === 'admin' && (
<RoleSwitcher
roles={['admin', 'teacher', 'student']}
Expand All @@ -382,6 +385,12 @@ export default function AppShell({ children }: { children?: ReactNode }) {
</div>
</header>

{isDemoPath && (
<div className="flex shrink-0 flex-wrap items-center justify-between gap-2 border-b border-amber-200 bg-amber-50 px-4 py-2 text-xs text-amber-900 md:px-6">
<span><strong>Demo mode</strong> · Sample data only — no school records are changed.</span>
<a href="/login" className="font-semibold underline underline-offset-2">Exit demo · School sign in</a>
</div>
)}
<div className="shrink-0 px-4 pt-3 md:px-6">
<Breadcrumbs items={breadcrumbItems} />
</div>
Expand Down
74 changes: 44 additions & 30 deletions apps/admin/src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
} from 'react';
import { supabase, configHint, missingSupabaseConfig } from '../lib/supabase';
import { toAuthEmail } from '../lib/utils';
import { isDemoPath, readDemoRole, saveDemoRole } from '../lib/demo';
import { seedPeople } from '../lib/seed';
import type { Profile, Role } from '@schoolerp/shared';

Expand All @@ -19,9 +20,8 @@
* attendance and leaves empty.
*
* No credentials exist anywhere in the client: the demo button picks a seeded
* identity directly, and only when no Supabase client is configured (see
* `signInAsDemo`). Against a real project, identity always comes from Supabase
* Auth — the client never decides it.
* identity only inside the isolated /demo app, where no Supabase client is
* created. School-account identity always comes from Supabase Auth.
*/
function demoProfileFor(role: Role): Profile | null {
const person = seedPeople.find((p) => p.role === role && p.is_active);
Expand All @@ -45,7 +45,7 @@
demoMode: boolean;
configError: string | null;
signIn: (loginId: string, password: string) => Promise<{ error: string | null }>;
/** Passwordless demo entry; only works while no Supabase client is configured. */
/** Opens the isolated showcase; never creates a real auth session. */
signInAsDemo: (role: Role) => { error: string | null };
signOut: () => Promise<void>;
requireRole: (roles: Role[]) => boolean;
Expand All @@ -58,23 +58,38 @@

const AuthContext = createContext<AuthContextType | null>(null);

export function useAuth() {

Check warning on line 61 in apps/admin/src/contexts/AuthContext.tsx

View workflow job for this annotation

GitHub Actions / lint-and-typecheck

Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
return ctx;
}

export function AuthProvider({ children }: { children: ReactNode }) {
const [profile, setProfile] = useState<Profile | null>(null);
const [profile, setProfile] = useState<Profile | null>(() => {
const role = readDemoRole();
return role ? demoProfileFor(role) : null;
});
const [sessionUserId, setSessionUserId] = useState<string | null>(null);
// Without a Supabase client there is no session to wait for, so start out
// resolved rather than flipping `loading` inside an effect (which cascades
// renders on mount).
const [loading, setLoading] = useState(() => !missingSupabaseConfig());
const [loading, setLoading] = useState(() => !!supabase);
const [viewingRole, setViewingRole] = useState<Role | null>(null);

const demoMode = missingSupabaseConfig();
const configError = demoMode ? configHint() : null;
const demoMode = isDemoPath || missingSupabaseConfig();
const configError = isDemoPath ? null : configHint();

useEffect(() => {
if (!isDemoPath) return;
saveDemoRole(profile?.role ?? null);
// The entry URL works even without storage; subsequent navigation uses
// tab-local sessionStorage, not the real account's persisted session.
const url = new URL(window.location.href);
if (url.searchParams.has('role')) {
url.searchParams.delete('role');
window.history.replaceState(window.history.state, '', url);
}
}, [profile]);

// Resolve the "effective" role for display/authorisation: explicit view-as
// override wins, then the real profile role.
Expand All @@ -90,14 +105,16 @@

useEffect(() => {
let mounted = true;
// Read through a closure: this can change while a profile query awaits.
const isMounted = () => mounted;
const client = supabase;
if (!client) {
// `loading` already starts false in this case; nothing to await.
return undefined;
}

client.auth.getSession().then(async ({ data, error }) => {
if (!mounted) return;
if (!isMounted()) return;
if (error) {
setLoading(false);
return;
Expand All @@ -109,23 +126,23 @@
.select('*')
.eq('id', data.session.user.id)
.single();
setProfile(prof ?? null);
if (isMounted()) setProfile(prof ?? null);
}
setLoading(false);
}).catch(() => {
if (mounted) setLoading(false);
if (isMounted()) setLoading(false);
});

const { data: sub } = client.auth.onAuthStateChange(async (_event, session) => {
if (!mounted) return;
if (!isMounted()) return;
setSessionUserId(session?.user.id ?? null);
if (session?.user) {
const { data: prof } = await client
.from('profiles')
.select('*')
.eq('id', session.user.id)
.single();
setProfile(prof ?? null);
if (isMounted()) setProfile(prof ?? null);
} else {
setProfile(null);
}
Expand All @@ -140,9 +157,10 @@
const signIn = useCallback(
async (loginId: string, password: string) => {
// Without a Supabase client there is no real authentication to perform.
// The passwordless demo button is the only way in, and it is refused
// whenever a real project is configured — the client must never decide
// identity against a live backend.
// Demo identities are local and never passed to Supabase Auth.
if (isDemoPath) {
return { error: 'You are in the demo. Use School sign in for your real account.' };
}
if (!supabase) {
return {
error:
Expand All @@ -156,33 +174,29 @@
[],
);

/**
* Passwordless demo sign-in for showcasing the console. Available only in
* demo mode (no Supabase client): the profile is local UI state over the
* localStorage demo store and no Supabase session is ever created, so no
* real data is reachable. With a real project configured this refuses.
*/
/** Enter via a full load so live auth callbacks cannot overwrite demo state. */
const signInAsDemo = useCallback((role: Role): { error: string | null } => {
if (supabase) {
return {
error: 'Demo access is disabled when Supabase is configured. Sign in with your school account.',
};
}
const demoProfile = demoProfileFor(role);
if (!demoProfile) {
return { error: `No demo ${role} account is seeded.` };
}
setSessionUserId(demoProfile.id);
if (!isDemoPath) {
window.location.assign(`/demo/dashboard?role=${role}`);
return { error: null };
}
setSessionUserId(null); // No authenticated backend user in a demo.
setViewingRole(null);
setProfile(demoProfile);
return { error: null };
}, []);

const signOut = useCallback(async () => {
if (supabase) await supabase.auth.signOut();
if (isDemoPath) saveDemoRole(null);
else if (supabase) await supabase.auth.signOut();
setProfile(null);
setSessionUserId(null);
setViewingRole(null);
}, [supabase]);
}, []);

const viewAsRole = useCallback((role: Role | null) => {
setViewingRole(role);
Expand Down
5 changes: 3 additions & 2 deletions apps/admin/src/lib/appData.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isDemoPath } from './demo';
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import {
ACADEMIC_YEAR,
Expand Down Expand Up @@ -80,14 +81,14 @@
audit: AuditEntry[];
}

const STORAGE_KEY = 'pws.demo.data.v4';
const STORAGE_KEY = isDemoPath ? 'pws.showcase.data.v1' : 'pws.demo.data.v4';
const PREVIOUS_STORAGE_KEY = 'pws.demo.data.v3';

/** Class teacher for IX-E owns door-to-door leave approvals in the demo. */
export const CLASS_TEACHER_ID = 'p-teacher-1';

/** Sections whose leaves the class teacher is allowed to action. */
export function teacherSections(people: Person[], teacherId: string): string[] {

Check warning on line 91 in apps/admin/src/lib/appData.tsx

View workflow job for this annotation

GitHub Actions / lint-and-typecheck

Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components
return people
.filter((p) => p.id === teacherId)
.flatMap((p) => (p.section_label ? [p.section_label] : []));
Expand Down Expand Up @@ -125,7 +126,7 @@
const fresh = initialData();
try {
const currentRaw = localStorage.getItem(STORAGE_KEY);
const raw = currentRaw ?? localStorage.getItem(PREVIOUS_STORAGE_KEY);
const raw = currentRaw ?? (isDemoPath ? null : localStorage.getItem(PREVIOUS_STORAGE_KEY));
if (!raw) return fresh;
const parsed = JSON.parse(raw) as Partial<AppState>;
// Any collection that is empty in storage but seeded by a newer build is
Expand Down Expand Up @@ -212,7 +213,7 @@

const AppDataContext = createContext<AppDataContextValue | null>(null);

export function useAppData() {

Check warning on line 216 in apps/admin/src/lib/appData.tsx

View workflow job for this annotation

GitHub Actions / lint-and-typecheck

Fast refresh only works when a file only exports components. Use a new file to share constants or functions between components
const context = useContext(AppDataContext);
if (!context) throw new Error('useAppData must be used inside AppDataProvider');
return context;
Expand Down
34 changes: 34 additions & 0 deletions apps/admin/src/lib/demo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { Role } from '@schoolerp/shared';

/**
* A full page load separates the showcase from the school app. Never change
* this flag in-place: the Supabase module uses it BEFORE creating a client.
* This is UI isolation, not authorization; live data remains protected by RLS.
*/
export const isDemoPath = /^\/demo(?:\/|$)/.test(window.location.pathname);
const ROLE_KEY = 'pws.showcase.role';

function isRole(value: unknown): value is Role {
return value === 'admin' || value === 'teacher' || value === 'student';
}

export function readDemoRole(): Role | null {
if (!isDemoPath) return null;
const requested = new URLSearchParams(window.location.search).get('role');
if (requested !== null) return isRole(requested) ? requested : null;
try {
const saved = sessionStorage.getItem(ROLE_KEY);
return isRole(saved) ? saved : null;
} catch {
return null;
}
}

export function saveDemoRole(role: Role | null) {
try {
if (role) sessionStorage.setItem(ROLE_KEY, role);
else sessionStorage.removeItem(ROLE_KEY);
} catch {
// In-memory demo entry still works when storage is unavailable.
}
}
Loading
Loading