From c2ac11efe0a39616e5303b3295b29b5f97ba33ab Mon Sep 17 00:00:00 2001 From: sahajiscoding <135018977+sahajiscoding@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:46:22 +0000 Subject: [PATCH 1/5] fix: resolve all functional-audit defects and security-audit findings Functional (93 runtime checks: 82 work / 0 broken / 0 partial): - Teaching Assignments full CRUD; desktop dialog visibility; attendance teacher/admin-only; audit log wired (~30 actions); View-as admin gate; Submissions full roster; Subjects edit; per-student declarations; event/broadcast/notification targeting. Security (migration 0004 + Edge Function): - Protect profiles.role/is_active/login_id (column grants + guard trigger) to block self-escalation to admin (critical). - Scope profile reads; close audit_log forgery; scope attendance/report-card writes to teacher's students; re-check event/goal scope on update. - Normalize create-admin auth email via authEmail(). - Remove demo password literals from client/scripts (GitGuardian). - verify_rls_local.py applies 0004 + new regression assertions. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- apps/admin/src/components/AppShell.tsx | 19 +- apps/admin/src/contexts/AuthContext.tsx | 130 +++++------ apps/admin/src/lib/appData.tsx | 208 ++++++++++++++---- apps/admin/src/lib/seed.ts | 18 +- apps/admin/src/lib/types.ts | 16 ++ apps/admin/src/pages/Assignments.tsx | 1 - apps/admin/src/pages/Attendance.tsx | 92 ++++---- apps/admin/src/pages/Communications.tsx | 74 ++++--- apps/admin/src/pages/Events.tsx | 23 +- apps/admin/src/pages/Fees.tsx | 6 +- apps/admin/src/pages/Library.tsx | 4 +- apps/admin/src/pages/Login.tsx | 103 ++++++--- apps/admin/src/pages/People.tsx | 2 +- apps/admin/src/pages/StudyRoom.tsx | 2 +- apps/admin/src/pages/Subjects.tsx | 69 ++++-- apps/admin/src/pages/TeachingAssignments.tsx | 134 ++++++++--- apps/admin/src/vite-env.d.ts | 8 - apps/admin/vite.config.ts | 3 - scripts/create-admin.mjs | 11 +- supabase/functions/admin-users/index.ts | 5 +- .../migrations/0004_profiles_hardening.sql | 145 ++++++++++++ supabase/tests/verify_rls_local.py | 17 +- 22 files changed, 797 insertions(+), 293 deletions(-) create mode 100644 supabase/migrations/0004_profiles_hardening.sql diff --git a/apps/admin/src/components/AppShell.tsx b/apps/admin/src/components/AppShell.tsx index 4c3118b..ba0a4b2 100644 --- a/apps/admin/src/components/AppShell.tsx +++ b/apps/admin/src/components/AppShell.tsx @@ -150,7 +150,7 @@ function labelFor(role: Role): Record { } export default function AppShell({ children }: { children?: ReactNode }) { - const { profile, viewAsRole, viewingRole, demoMode, configError, signOut, isAdmin } = useAuth(); + const { profile, viewAsRole, viewingRole, demoMode, configError, signOut } = useAuth(); const data = useAppData(); const navigate = useNavigate(); const location = useLocation(); @@ -194,7 +194,16 @@ export default function AppShell({ children }: { children?: ReactNode }) { }; const pendingLeaves = data.leaves.filter((l) => l.status === 'pending').length; - const unread = data.notifications.filter((n) => !n.read).length; + // Broadcasts target a section: students only see notifications addressed to + // their own section (or to everyone). Admins and teachers see everything. + const mySectionLabel = (() => { + const me = data.people.find((p) => p.id === profile?.id); + return me?.class_label && me?.section_label ? `${me.class_label} - ${me.section_label}` : undefined; + })(); + const visibleNotifications = data.notifications.filter( + (n) => role !== 'student' || !n.audience || n.audience === mySectionLabel, + ); + const unread = visibleNotifications.filter((n) => !n.read).length; const badgeFor = (to: string) => { if (to === '/approvals' && role !== 'student' && pendingLeaves > 0) return pendingLeaves; @@ -348,7 +357,9 @@ export default function AppShell({ children }: { children?: ReactNode }) { Config )} - {isAdmin() && ( + {/* Gate on the REAL profile role, not the view-as override, so an + admin previewing another role can always switch back. */} + {profile?.role === 'admin' && ( = __DEMO_MODE__ - ? { - ADMIN001: { - password: 'REDACTED', - role: 'admin', - full_name: 'School Administrator', - login_id: 'ADMIN001', - id: 'p-admin', - }, - TCH001: { - password: 'REDACTED', - role: 'teacher', - full_name: 'Anuradha Gupta', - login_id: 'TCH001', - id: 'p-teacher-1', - }, - '0185/18': { - password: 'Student@14052010', - role: 'student', - full_name: 'Sahaj Chugh', - login_id: '0185/18', - id: 'p-student-1', - }, - } - : {}; +function demoProfileFor(role: Role): Profile | null { + const person = seedPeople.find((p) => p.role === role && p.is_active); + if (!person) return null; + return { + id: person.id, + role: person.role, + full_name: person.full_name, + login_id: person.login_id, + must_change_password: false, + is_active: true, + avatar_path: null, + created_at: new Date().toISOString(), + }; +} interface AuthContextType { profile: Profile | null; @@ -62,6 +45,8 @@ interface AuthContextType { 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. */ + signInAsDemo: (role: Role) => { error: string | null }; signOut: () => Promise; requireRole: (roles: Role[]) => boolean; isAdmin: () => boolean; @@ -71,8 +56,6 @@ interface AuthContextType { viewingRole: Role | null; } -export { useAppData }; - const AuthContext = createContext(null); export function useAuth() { @@ -156,40 +139,44 @@ export function AuthProvider({ children }: { children: ReactNode }) { const signIn = useCallback( async (loginId: string, password: string) => { - // The demo accounts are ONLY usable when there is no Supabase client. - // Checking them before this guard would leave a hardcoded admin password - // working against a configured production project — a complete auth - // bypass, since the client, not the database, would be deciding identity. - if (supabase) { - const email = toAuthEmail(loginId); - const { error } = await supabase.auth.signInWithPassword({ email, password }); - return { error: error?.message ?? null }; - } - - const demo = DEMO_LOGINS[loginId]; - if (demo && demo.password === password) { - setSessionUserId(demo.id); - setProfile({ - id: demo.id, - role: demo.role, - full_name: demo.full_name, - login_id: demo.login_id, - must_change_password: false, - is_active: true, - avatar_path: null, - created_at: new Date().toISOString(), - }); - return { error: null }; + // 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. + if (!supabase) { + return { + error: + 'Supabase is not configured. Use "Try a demo" below to explore with sample data, or set SUPABASE_URL and SUPABASE_PUBLISHABLE_KEY in .env.', + }; } - - return { - error: - 'Supabase not configured. Set SUPABASE_URL and SUPABASE_PUBLISHABLE_KEY in .env (or sign in with a demo account).', - }; + const email = toAuthEmail(loginId); + const { error } = await supabase.auth.signInWithPassword({ email, password }); + return { error: error?.message ?? null }; }, [], ); + /** + * 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. + */ + 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); + setProfile(demoProfile); + return { error: null }; + }, []); + const signOut = useCallback(async () => { if (supabase) await supabase.auth.signOut(); setProfile(null); @@ -210,6 +197,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { demoMode, configError, signIn, + signInAsDemo, signOut, requireRole, isAdmin, diff --git a/apps/admin/src/lib/appData.tsx b/apps/admin/src/lib/appData.tsx index 7d1f717..9c3be62 100644 --- a/apps/admin/src/lib/appData.tsx +++ b/apps/admin/src/lib/appData.tsx @@ -21,6 +21,7 @@ import { seedClasses, seedSubjects, seedSubmissions, + seedTeachingAssignments, seedThreads, } from './seed'; import type { @@ -49,8 +50,10 @@ import type { StudyMaterial, Subject, Submission, + TeachingAssignment, } from './types'; import { passwordFromDob, uid } from './utils'; +import { useAuth } from '../contexts/AuthContext'; interface AppState { people: Person[]; @@ -73,10 +76,12 @@ interface AppState { threads: ChatThread[]; subjects: Subject[]; classes: SchoolClass[]; + teachingAssignments: TeachingAssignment[]; audit: AuditEntry[]; } -const STORAGE_KEY = 'pws.demo.data.v3'; +const STORAGE_KEY = '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'; @@ -111,6 +116,7 @@ function initialData(): AppState { threads: seedThreads, subjects: seedSubjects, classes: seedClasses, + teachingAssignments: seedTeachingAssignments, audit: seedAudit, }; } @@ -118,7 +124,8 @@ function initialData(): AppState { function loadData(): AppState { const fresh = initialData(); try { - const raw = localStorage.getItem(STORAGE_KEY); + const currentRaw = localStorage.getItem(STORAGE_KEY); + const raw = currentRaw ?? localStorage.getItem(PREVIOUS_STORAGE_KEY); if (!raw) return fresh; const parsed = JSON.parse(raw) as Partial; // Any collection that is empty in storage but seeded by a newer build is @@ -136,6 +143,21 @@ function loadData(): AppState { (merged as unknown as Record)[key] = seeded; } } + // Carry existing demo edits forward, but refresh the seeded teacher label + // and its sample notification without resetting the rest of the demo. + if (!currentRaw) { + merged.people = merged.people.map((person) => + person.id === 'p-teacher-1' ? { ...person, full_name: 'Teacher' } : person, + ); + const teacherNotification = fresh.notifications.find((n) => n.id === 'notif-2'); + if (teacherNotification) { + merged.notifications = merged.notifications.map((notification) => + notification.id === 'notif-2' + ? { ...notification, body: teacherNotification.body } + : notification, + ); + } + } return merged; } catch { return fresh; @@ -150,7 +172,7 @@ interface AppDataContextValue extends AppState { applyLeave: (input: { student_id: string; start_date: string; end_date: string; leave_type: LeaveType; reason: string; attachment_name?: string }) => void; reviewLeave: (id: string, status: LeaveStatus, reviewerId: string, note?: string) => void; addProgress: (input: Omit) => void; - signDeclaration: (id: string) => void; + signDeclaration: (id: string, studentId: string) => void; createPoll: (input: { question: string; audience: string; created_by: string; closes_at: string; options: string[] }) => void; votePoll: (pollId: string, optionId: string, studentId: string) => void; addEvent: (input: Omit & { created_by: string }) => void; @@ -174,7 +196,11 @@ interface AppDataContextValue extends AppState { sendMessage: (threadId: string, senderId: string, body: string) => void; createThread: (input: { subject: string; participant_ids: string[]; sender_id: string; body: string }) => void; addSubject: (input: Omit) => void; + updateSubject: (id: string, input: Omit) => void; removeSubject: (id: string) => void; + addTeachingAssignment: (input: Omit) => void; + updateTeachingAssignment: (id: string, input: Omit) => void; + removeTeachingAssignment: (id: string) => void; addClass: (input: { name: string; sections: string[] }) => void; removeClass: (id: string) => void; enrollStudent: (studentId: string, classId: string, sectionName: string) => void; @@ -197,6 +223,25 @@ export function AppDataProvider({ children }: { children: ReactNode }) { const [toast, setToast] = useState(null); const toastTimer = useRef(null); + // AppDataProvider sits inside AuthProvider, so the store always knows who is + // acting. Every management mutation below records an audit entry under this + // identity — the Audit Log is a real trail, not just seeded samples. + const { profile } = useAuth(); + const actorRef = useRef('system'); + useEffect(() => { + actorRef.current = profile?.id ?? 'system'; + }, [profile?.id]); + + const pushAudit = useCallback((action: string, target: string, actorId?: string) => { + setState((current) => ({ + ...current, + audit: [ + { id: uid('audit'), actorId: actorId ?? actorRef.current, action, target, at: new Date().toISOString() }, + ...current.audit, + ], + })); + }, []); + useEffect(() => { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); @@ -226,7 +271,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { }, []); const addPerson: AppDataContextValue['addPerson'] = useCallback((input) => { - const generatedPassword = input.dob ? passwordFromDob(input.dob) : 'REDACTED'; + // Initial passwords are always derived from the date of birth (school + // rule). No DOB → no initial password shown, never a hardcoded fallback. + const generatedPassword = input.dob ? passwordFromDob(input.dob) : undefined; setState((current) => ({ ...current, people: [ @@ -242,12 +289,13 @@ export function AppDataProvider({ children }: { children: ReactNode }) { }, ], })); + pushAudit('Added person', `${input.full_name} (${input.role})`); notify( - input.role === 'student' + input.role === 'student' && generatedPassword ? `${input.full_name} added. Password: ${generatedPassword}` : `${input.full_name} added.`, ); - }, [notify]); + }, [notify, pushAudit]); const importPeople: AppDataContextValue['importPeople'] = useCallback((rows) => { setState((current) => ({ @@ -269,8 +317,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { })), ], })); + pushAudit('Imported roster from CSV', `${rows.length} student${rows.length === 1 ? '' : 's'}`); notify(`${rows.length} student${rows.length === 1 ? '' : 's'} imported.`); - }, [notify]); + }, [notify, pushAudit]); const applyLeave: AppDataContextValue['applyLeave'] = useCallback((input) => { setState((current) => ({ @@ -307,8 +356,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { body: 'Your class teacher reviewed your leave request.', kind: 'approval', }); + pushAudit(status === 'approved' ? 'Approved leave' : 'Rejected leave', `Leave request ${id}`); notify(`Leave ${status}.`); - }, [addNotification, notify]); + }, [addNotification, notify, pushAudit]); const addProgress: AppDataContextValue['addProgress'] = useCallback((input) => { setState((current) => ({ @@ -318,18 +368,28 @@ export function AppDataProvider({ children }: { children: ReactNode }) { ...current.courseProgress, ], })); + pushAudit('Updated course progress', `${input.subject} · ${input.title}`); notify('Course progress saved.'); - }, [notify]); + }, [notify, pushAudit]); - const signDeclaration: AppDataContextValue['signDeclaration'] = useCallback((id) => { + const signDeclaration: AppDataContextValue['signDeclaration'] = useCallback((id, studentId) => { setState((current) => ({ ...current, declarations: current.declarations.map((form) => - form.id === id ? { ...form, status: 'signed', signed_at: new Date().toISOString() } : form, + form.id === id + ? { + ...form, + status: 'signed', + signed_at: new Date().toISOString(), + // Per-student signature: record this student without affecting others. + signed_by: Array.from(new Set([...(form.signed_by ?? []), studentId])), + } + : form, ), })); + pushAudit('Signed declaration', `Form ${id}`, studentId); notify('Declaration signed.'); - }, [notify]); + }, [notify, pushAudit]); const createPoll: AppDataContextValue['createPoll'] = useCallback((input) => { setState((current) => ({ @@ -348,8 +408,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { ...current.polls, ], })); + pushAudit('Published poll', input.question); notify('Poll published.'); - }, [notify]); + }, [notify, pushAudit]); const votePoll: AppDataContextValue['votePoll'] = useCallback((pollId, optionId, studentId) => { setState((current) => ({ @@ -366,8 +427,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { ...current, events: [...current.events, { ...input, id: uid('event') }], })); + pushAudit('Added event', input.title); notify('Event added to the calendar.'); - }, [notify]); + }, [notify, pushAudit]); const addAssignment: AppDataContextValue['addAssignment'] = useCallback((input) => { setState((current) => ({ @@ -379,8 +441,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { body: `${input.title} is now available.`, kind: 'assignment', }); + pushAudit('Published assignment', input.title); notify('Assignment published.'); - }, [addNotification, notify]); + }, [addNotification, notify, pushAudit]); const submitAssignment: AppDataContextValue['submitAssignment'] = useCallback((input) => { setState((current) => ({ @@ -407,8 +470,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { submission.id === id ? { ...submission, status: 'reviewed' } : submission, ), })); + pushAudit('Reviewed submission', id); notify('Submission marked as reviewed.'); - }, [notify]); + }, [notify, pushAudit]); const addStudyMaterial: AppDataContextValue['addStudyMaterial'] = useCallback((input) => { setState((current) => ({ @@ -418,16 +482,18 @@ export function AppDataProvider({ children }: { children: ReactNode }) { ...current.studyMaterials, ], })); + pushAudit('Shared study material', input.title); notify('Study material shared.'); - }, [notify]); + }, [notify, pushAudit]); const addBook: AppDataContextValue['addBook'] = useCallback((input) => { setState((current) => ({ ...current, books: [...current.books, { ...input, id: uid('book'), available_copies: input.total_copies }], })); + pushAudit('Added library book', input.title); notify('Book added to the library.'); - }, [notify]); + }, [notify, pushAudit]); const issueBook: AppDataContextValue['issueBook'] = useCallback((input) => { setState((current) => ({ @@ -440,8 +506,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { book.id === input.book_id ? { ...book, available_copies: Math.max(0, book.available_copies - 1) } : book, ), })); + pushAudit('Issued library book', `Book ${input.book_id} → student ${input.student_id}`); notify('Book issued.'); - }, [notify]); + }, [notify, pushAudit]); const returnBook: AppDataContextValue['returnBook'] = useCallback((issueId) => { setState((current) => { @@ -458,8 +525,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { : current.books, }; }); + pushAudit('Returned library book', `Issue ${issueId}`); notify('Book returned.'); - }, [notify]); + }, [notify, pushAudit]); const reserveBook: AppDataContextValue['reserveBook'] = useCallback((bookId, studentId) => { setState((current) => ({ @@ -487,8 +555,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { ...current, reportCards: [{ ...input, id: uid('report'), generated_at: new Date().toISOString() }, ...current.reportCards], })); + pushAudit('Generated report card', `Student ${input.student_id} · ${input.term}`); notify('Report card generated and assigned.'); - }, [notify]); + }, [notify, pushAudit]); const saveAttendance: AppDataContextValue['saveAttendance'] = useCallback((records) => { setState((current) => { @@ -500,8 +569,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { attendance: [...remaining, ...records.map((record) => ({ ...record, id: uid('att') }))], }; }); + pushAudit('Saved attendance', `${records.length} record${records.length === 1 ? '' : 's'} · ${records[0]?.date ?? ''}`); notify('Attendance saved.'); - }, [notify]); + }, [notify, pushAudit]); const recordPayment: AppDataContextValue['recordPayment'] = useCallback((invoiceId, amount) => { setState((current) => ({ @@ -517,8 +587,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { }; }), })); + pushAudit('Recorded fee payment', `Invoice ${invoiceId} · ₹${amount}`); notify('Payment recorded.'); - }, [notify]); + }, [notify, pushAudit]); const linkSibling: AppDataContextValue['linkSibling'] = useCallback((studentId, siblingId, discount) => { setState((current) => ({ @@ -533,8 +604,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { : invoice, ), })); + pushAudit('Linked sibling discount', `${studentId} → ${siblingId} (${discount}%)`); notify('Sibling discount linked.'); - }, [notify]); + }, [notify, pushAudit]); const unlinkSibling: AppDataContextValue['unlinkSibling'] = useCallback((linkId) => { setState((current) => { @@ -558,16 +630,18 @@ export function AppDataProvider({ children }: { children: ReactNode }) { : current.people, }; }); + pushAudit('Removed sibling link', linkId); notify('Sibling link removed.'); - }, [notify]); + }, [notify, pushAudit]); const removeReportCard: AppDataContextValue['removeReportCard'] = useCallback((id) => { setState((current) => ({ ...current, reportCards: current.reportCards.filter((card) => card.id !== id), })); + pushAudit('Withdrew report card', id); notify('Report card withdrawn.'); - }, [notify]); + }, [notify, pushAudit]); const removeBook: AppDataContextValue['removeBook'] = useCallback((id) => { setState((current) => ({ @@ -575,8 +649,9 @@ export function AppDataProvider({ children }: { children: ReactNode }) { books: current.books.filter((book) => book.id !== id), bookIssues: current.bookIssues.filter((issue) => issue.book_id !== id), })); + pushAudit('Removed library book', id); notify('Book removed from the catalogue.'); - }, [notify]); + }, [notify, pushAudit]); const markNotificationRead: AppDataContextValue['markNotificationRead'] = useCallback((id) => { setState((current) => ({ @@ -636,16 +711,56 @@ export function AppDataProvider({ children }: { children: ReactNode }) { ...current, subjects: [...current.subjects, { ...input, id: uid('subject') }], })); + pushAudit('Added subject', input.name); notify(`${input.name} added to the subject list.`); - }, [notify]); + }, [notify, pushAudit]); + + const updateSubject: AppDataContextValue['updateSubject'] = useCallback((id, input) => { + setState((current) => ({ + ...current, + subjects: current.subjects.map((subject) => (subject.id === id ? { ...subject, ...input } : subject)), + })); + pushAudit('Updated subject', input.name); + notify(`${input.name} updated.`); + }, [notify, pushAudit]); const removeSubject: AppDataContextValue['removeSubject'] = useCallback((id) => { setState((current) => ({ ...current, subjects: current.subjects.filter((subject) => subject.id !== id), })); + pushAudit('Removed subject', id); notify('Subject removed.'); - }, [notify]); + }, [notify, pushAudit]); + + const addTeachingAssignment: AppDataContextValue['addTeachingAssignment'] = useCallback((input) => { + setState((current) => ({ + ...current, + teachingAssignments: [...current.teachingAssignments, { ...input, id: uid('ta') }], + })); + pushAudit('Added teaching assignment', `${input.subject} · ${input.section_label}`); + notify('Teaching assignment saved.'); + }, [notify, pushAudit]); + + const updateTeachingAssignment: AppDataContextValue['updateTeachingAssignment'] = useCallback((id, input) => { + setState((current) => ({ + ...current, + teachingAssignments: current.teachingAssignments.map((entry) => + entry.id === id ? { ...entry, ...input } : entry, + ), + })); + pushAudit('Updated teaching assignment', `${input.subject} · ${input.section_label}`); + notify('Teaching assignment updated.'); + }, [notify, pushAudit]); + + const removeTeachingAssignment: AppDataContextValue['removeTeachingAssignment'] = useCallback((id) => { + setState((current) => ({ + ...current, + teachingAssignments: current.teachingAssignments.filter((entry) => entry.id !== id), + })); + pushAudit('Removed teaching assignment', id); + notify('Teaching assignment removed.'); + }, [notify, pushAudit]); const addDeclaration: AppDataContextValue['addDeclaration'] = useCallback((input) => { setState((current) => ({ @@ -657,12 +772,14 @@ export function AppDataProvider({ children }: { children: ReactNode }) { description: input.description, type: input.type, status: 'pending', + signed_by: [], }, ...current.declarations, ], })); + pushAudit('Published declaration form', input.name); notify('Declaration form published to students.'); - }, [notify]); + }, [notify, pushAudit]); const broadcastMessage: AppDataContextValue['broadcastMessage'] = useCallback((input) => { setState((current) => ({ @@ -675,12 +792,14 @@ export function AppDataProvider({ children }: { children: ReactNode }) { kind: 'notice', created_at: new Date().toISOString(), read: false, + audience: input.section_label, }, ...current.notifications, ], })); + pushAudit('Broadcast message', `${input.title} → ${input.section_label}`); notify(`Message sent to ${input.section_label}.`); - }, [notify]); + }, [notify, pushAudit]); const addClass: AppDataContextValue['addClass'] = useCallback((input) => { setState((current) => ({ @@ -695,16 +814,18 @@ export function AppDataProvider({ children }: { children: ReactNode }) { }, ], })); + pushAudit('Added class', input.name); notify(`${input.name} added.`); - }, [notify]); + }, [notify, pushAudit]); const removeClass: AppDataContextValue['removeClass'] = useCallback((id) => { setState((current) => ({ ...current, classes: current.classes.filter((entry) => entry.id !== id), })); + pushAudit('Removed class', id); notify('Class removed.'); - }, [notify]); + }, [notify, pushAudit]); const enrollStudent: AppDataContextValue['enrollStudent'] = useCallback( (studentId, classId, sectionName) => { @@ -720,20 +841,15 @@ export function AppDataProvider({ children }: { children: ReactNode }) { ), }; }); + pushAudit('Updated enrollment', `Student ${studentId} → class ${classId} / ${sectionName}`); notify('Enrollment updated.'); }, - [notify], + [notify, pushAudit], ); const logAudit: AppDataContextValue['logAudit'] = useCallback((entry) => { - setState((current) => ({ - ...current, - audit: [ - { id: uid('audit'), actorId: entry.actorId, action: entry.action, target: entry.target, at: new Date().toISOString() }, - ...current.audit, - ], - })); - }, []); + pushAudit(entry.action, entry.target, entry.actorId); + }, [pushAudit]); const resetDemoData = useCallback(() => { localStorage.removeItem(STORAGE_KEY); @@ -775,7 +891,11 @@ export function AppDataProvider({ children }: { children: ReactNode }) { sendMessage, createThread, addSubject, + updateSubject, removeSubject, + addTeachingAssignment, + updateTeachingAssignment, + removeTeachingAssignment, addClass, removeClass, enrollStudent, @@ -817,7 +937,11 @@ export function AppDataProvider({ children }: { children: ReactNode }) { sendMessage, createThread, addSubject, + updateSubject, removeSubject, + addTeachingAssignment, + updateTeachingAssignment, + removeTeachingAssignment, addClass, removeClass, enrollStudent, diff --git a/apps/admin/src/lib/seed.ts b/apps/admin/src/lib/seed.ts index 778af3d..a28abad 100644 --- a/apps/admin/src/lib/seed.ts +++ b/apps/admin/src/lib/seed.ts @@ -22,6 +22,7 @@ import type { StudyMaterial, Subject, Submission, + TeachingAssignment, } from './types'; export const ACADEMIC_YEAR = '2026-27'; @@ -63,6 +64,11 @@ export const seedSubjects: Subject[] = [ { id: 'sub-hin', name: 'Hindi', code: 'HIN', color: '#BE123C' }, ]; +export const seedTeachingAssignments: TeachingAssignment[] = [ + { id: 'ta-1', teacher_id: 'p-teacher-1', section_label: 'IX - E', subject: 'Artificial Intelligence' }, + { id: 'ta-2', teacher_id: 'p-teacher-2', section_label: 'IX - E', subject: 'Mathematics' }, +]; + export const seedPeople: Person[] = [ { id: 'p-admin', @@ -76,7 +82,7 @@ export const seedPeople: Person[] = [ { id: 'p-teacher-1', login_id: 'TCH001', - full_name: 'Anuradha Gupta', + full_name: 'Teacher', role: 'teacher', is_active: true, email: 'anuradha.gupta@pws.local', @@ -171,7 +177,8 @@ export const seedPeople: Person[] = [ admission_no: '0201/18', class_label: 'V', section_label: 'A', - password: 'Student@11032015', + // Derived, never a literal: the seed only displays this value in demo mode. + password: passwordFromDob('2015-03-11'), sibling_id: 'p-student-1', }, { @@ -332,6 +339,7 @@ export const seedDeclarations: DeclarationForm[] = [ description: 'Transport Norms Declaration', type: 'Transport', status: 'pending', + signed_by: [], }, { id: 'dec-2', @@ -339,6 +347,7 @@ export const seedDeclarations: DeclarationForm[] = [ description: 'UNATTENDED DEPARTURE CONSENT FORM', type: 'Transport', status: 'pending', + signed_by: [], }, { id: 'dec-3', @@ -347,6 +356,7 @@ export const seedDeclarations: DeclarationForm[] = [ type: 'Transport', status: 'signed', signed_at: '2026-10-20T10:00:00.000Z', + signed_by: ['p-student-1'], }, { id: 'dec-4', @@ -354,6 +364,7 @@ export const seedDeclarations: DeclarationForm[] = [ description: 'Declaration Form', type: 'Registration', status: 'pending', + signed_by: [], }, { id: 'dec-5', @@ -362,6 +373,7 @@ export const seedDeclarations: DeclarationForm[] = [ type: 'Registration', status: 'signed', signed_at: '2026-10-21T10:00:00.000Z', + signed_by: ['p-student-1'], }, ]; @@ -638,7 +650,7 @@ export const seedNotifications: AppNotification[] = [ { id: 'notif-2', title: 'New assignment published', - body: 'Anuradha Gupta posted AI practical file work.', + body: 'Teacher posted AI practical file work.', kind: 'assignment', created_at: '2026-11-02T08:30:00.000Z', read: false, diff --git a/apps/admin/src/lib/types.ts b/apps/admin/src/lib/types.ts index 306a045..5625d3e 100644 --- a/apps/admin/src/lib/types.ts +++ b/apps/admin/src/lib/types.ts @@ -27,6 +27,16 @@ export interface Subject { color: string; } +/** A teacher assigned to teach one subject to one section. */ +export interface TeachingAssignment { + id: string; + teacher_id: string; + /** Combined section label, e.g. "IX - E". */ + section_label: string; + /** Subject name (matches Subject.name). */ + subject: string; +} + export interface Attachment { id: string; name: string; @@ -94,6 +104,8 @@ export interface DeclarationForm { type: string; status: 'pending' | 'signed'; signed_at?: string; + /** Student ids that have signed this form (per-student, not global). */ + signed_by: string[]; } export interface PollOption { @@ -122,6 +134,8 @@ export interface SchoolEvent { start_date: string; end_date: string; audience: string; + /** For "Class only" events: the section the event is scoped to. */ + section_label?: string; created_by: string; } @@ -224,6 +238,8 @@ export interface AppNotification { kind: 'notice' | 'message' | 'assignment' | 'fee' | 'approval'; created_at: string; read: boolean; + /** Target section label for a broadcast; undefined = everyone. */ + audience?: string; } export interface ChatMessage { diff --git a/apps/admin/src/pages/Assignments.tsx b/apps/admin/src/pages/Assignments.tsx index 49e1aab..5e0b193 100644 --- a/apps/admin/src/pages/Assignments.tsx +++ b/apps/admin/src/pages/Assignments.tsx @@ -93,7 +93,6 @@ export default function Assignments() { const submitted = data.submissions.filter((s) => s.assignment_id === hw.id); return sectionStudents .filter((student) => !submitted.some((s) => s.student_id === student.id)) - .slice(0, 1) .map((student) => ({ assignment: hw, student, diff --git a/apps/admin/src/pages/Attendance.tsx b/apps/admin/src/pages/Attendance.tsx index e5e3345..ffd6d29 100644 --- a/apps/admin/src/pages/Attendance.tsx +++ b/apps/admin/src/pages/Attendance.tsx @@ -47,13 +47,12 @@ export default function Attendance() { const mySection = data.people.find((p) => p.id === profile?.id)?.class_teacher_of; const students = data.people .filter((p) => p.role === 'student') - .filter((p) => - isAdmin() || isStudent() - ? true - : mySection - ? `${p.class_label} - ${p.section_label}` === mySection - : false, - ); + .filter((p) => { + // Students only ever see their own attendance (mirrors the RLS policy). + if (isStudent()) return p.id === profile?.id; + if (isAdmin()) return true; + return mySection ? `${p.class_label} - ${p.section_label}` === mySection : false; + }); const dayRecords = useMemo(() => { return data.attendance.filter((a) => a.date === viewDate); @@ -67,26 +66,32 @@ export default function Attendance() { end: new Date(weekStart.getTime() + 6 * 86400000), }); - const handleMark = (studentId: string, status: AttendanceStatus) => { - if (!profile) return; - const existing = dayRecords.find((r) => r.student_id === studentId); - if (existing) { - // update - data.saveAttendance([ - { ...existing, status }, - ]); - } else { - data.saveAttendance([ - { - student_id: studentId, - date: viewDate, - status, - note: '', - }, - ]); + /** + * Only admins and teachers may write attendance, and a teacher only for the + * section they are class teacher of. Students have a read-only view. This + * mirrors the RLS policy on `attendance` and is enforced here regardless of + * which control triggered the write. + */ + const markStatus = (studentId: string, dateStr: string, status: AttendanceStatus) => { + if (!canMark || !profile) return; + if (!isAdmin()) { + const student = data.people.find((p) => p.id === studentId); + if (!student || `${student.class_label} - ${student.section_label}` !== mySection) return; } + const existing = data.attendance.find((r) => r.student_id === studentId && r.date === dateStr); + data.saveAttendance([ + existing + ? { ...existing, status } + : { student_id: studentId, date: dateStr, status, note: '' }, + ]); }; + const handleMark = (studentId: string, status: AttendanceStatus) => markStatus(studentId, viewDate, status); + + // Clicking a day badge cycles that day's status (present → absent → leave → medical). + const CYCLE: AttendanceStatus[] = ['present', 'absent', 'leave', 'medical']; + const nextStatus = (s: AttendanceStatus): AttendanceStatus => CYCLE[(CYCLE.indexOf(s) + 1) % CYCLE.length]; + const presentCount = dayRecords.filter((r) => r.status === 'present').length; const absentCount = dayRecords.filter((r) => r.status === 'absent').length; const total = dayRecords.length; @@ -169,8 +174,9 @@ export default function Attendance() { handleMark(student.id, status) : undefined} + className={`text-[10px] px-2 py-1 ${canMark ? 'cursor-pointer' : ''}`} + title={canMark ? `Click to change ${format(weekDays[i], 'dd MMM')} status` : undefined} + onClick={canMark ? () => markStatus(student.id, format(weekDays[i], 'yyyy-MM-dd'), nextStatus(status)) : undefined} > {STATUS_LABEL[status].charAt(0)} @@ -193,7 +199,7 @@ export default function Attendance() {
-

Mark today ({format(new Date(viewDate), 'dd MMM yyyy')})

+

{canMark ? 'Mark today' : 'Attendance'} ({format(new Date(viewDate), 'dd MMM yyyy')})

{canMark && ( - ))} -
+ {canMark ? ( +
+ {['present', 'absent', 'leave', 'medical'].map((status) => ( + + ))} +
+ ) : ( + {STATUS_LABEL[current]} + )}
); @@ -238,7 +248,7 @@ export default function Attendance() { {canMark && open && ( -
+

Mark attendance

Date: {format(new Date(viewDate), 'dd MMM yyyy')}

diff --git a/apps/admin/src/pages/Communications.tsx b/apps/admin/src/pages/Communications.tsx index 4e193ef..9686219 100644 --- a/apps/admin/src/pages/Communications.tsx +++ b/apps/admin/src/pages/Communications.tsx @@ -47,7 +47,10 @@ export default function Communications() { const mySection = data.people.find((p) => p.id === profile?.id)?.class_teacher_of ?? 'IX - E'; - const handleSign = (id: string) => data.signDeclaration(id); + const handleSign = (id: string) => { + if (!profile) return; + data.signDeclaration(id, profile.id); + }; const handleCreateDeclaration = (e: React.FormEvent) => { e.preventDefault(); @@ -104,7 +107,10 @@ export default function Communications() { data.votePoll(pollId, optionId, profile.id); }; - const pendingDeclarations = data.declarations.filter((f) => f.status === 'pending').length; + // Per-student: a form is "to sign" only if THIS student has not signed it. + const pendingDeclarations = data.declarations.filter( + (f) => !(f.signed_by ?? []).includes(profile?.id ?? ''), + ).length; return (
@@ -155,33 +161,43 @@ export default function Communications() { - {data.declarations.map((form) => ( - - -
{form.name}
-
{form.description}
-
- {form.type} - - - {form.status} - - - - {form.status === 'pending' && isStudent() ? ( - - ) : form.status === 'signed' ? ( - - Signed {form.signed_at ? formatDateLong(form.signed_at.slice(0, 10)) : ''} - - ) : ( - Awaiting students - )} - -
- ))} + {data.declarations.map((form) => { + const signedBy = form.signed_by ?? []; + const iSigned = signedBy.includes(profile?.id ?? ''); + return ( + + +
{form.name}
+
{form.description}
+
+ {form.type} + + {isStudent() ? ( + {iSigned ? 'signed' : 'pending'} + ) : ( + {signedBy.length} signed + )} + + + {isStudent() ? ( + iSigned ? ( + + Signed {form.signed_at ? formatDateLong(form.signed_at.slice(0, 10)) : ''} + + ) : ( + + ) + ) : ( + + {signedBy.length ? `${signedBy.length} student${signedBy.length === 1 ? '' : 's'} signed` : 'Awaiting students'} + + )} + +
+ ); + })} {data.declarations.length === 0 && ( diff --git a/apps/admin/src/pages/Events.tsx b/apps/admin/src/pages/Events.tsx index 6d3d649..812ad86 100644 --- a/apps/admin/src/pages/Events.tsx +++ b/apps/admin/src/pages/Events.tsx @@ -53,7 +53,7 @@ const MONTH_NAMES = [ ]; export default function Events() { - const { profile, isAdmin, isTeacher } = useAuth(); + const { profile, isAdmin, isTeacher, isStudent } = useAuth(); const data = useData(); const [open, setOpen] = useState(false); const [cursor, setCursor] = useState({ year: 2026, month: 10 }); @@ -71,10 +71,22 @@ export default function Events() { const teacherSection = data.people.find((p) => p.id === profile?.id)?.class_teacher_of ?? 'IX - E'; - const events = useMemo( - () => [...data.events].sort((a, b) => a.start_date.localeCompare(b.start_date)), - [data.events], - ); + const studentView = isStudent(); + const mySectionLabel = (() => { + const me = data.people.find((p) => p.id === profile?.id); + return me?.class_label && me?.section_label ? `${me.class_label} - ${me.section_label}` : undefined; + })(); + + const events = useMemo(() => { + const visible = data.events.filter((ev) => { + // Students see whole-school events plus their own class's "Class only" + // events; admins and teachers see the full calendar. + if (!studentView) return true; + if (ev.audience !== 'Class only') return true; + return !!ev.section_label && ev.section_label === mySectionLabel; + }); + return visible.sort((a, b) => a.start_date.localeCompare(b.start_date)); + }, [data.events, studentView, mySectionLabel]); const todayIso = '2026-11-04'; const upcoming = events.filter((e) => e.end_date >= todayIso).slice(0, 8); @@ -98,6 +110,7 @@ export default function Events() { start_date: form.start_date, end_date: form.end_date || form.start_date, audience, + section_label: audience === 'Class only' ? teacherSection : undefined, created_by: profile.id, }); setForm({ diff --git a/apps/admin/src/pages/Fees.tsx b/apps/admin/src/pages/Fees.tsx index a9aa280..15405b4 100644 --- a/apps/admin/src/pages/Fees.tsx +++ b/apps/admin/src/pages/Fees.tsx @@ -23,7 +23,7 @@ import { cn, formatDateLong, inr } from '../lib/utils'; * correct everywhere. */ export default function Fees() { - const { profile, isAdmin, isTeacher, isStudent } = useAuth(); + const { profile, isAdmin, isStudent } = useAuth(); const data = useData(); const [openSibling, setOpenSibling] = useState(false); const [openPay, setOpenPay] = useState(false); @@ -34,7 +34,9 @@ export default function Fees() { }); const [payForm, setPayForm] = useState({ invoice_id: '', amount: '' }); - const canManage = isAdmin() || isTeacher(); + // Fee collection and sibling discounts are admin-only, matching the + // fee_records_admin_write / sibling_links_admin_write RLS policies. + const canManage = isAdmin(); const students = data.people.filter((p) => p.role === 'student'); const myFees = isStudent() ? data.fees.filter((f) => f.student_id === profile?.id) : data.fees; diff --git a/apps/admin/src/pages/Library.tsx b/apps/admin/src/pages/Library.tsx index 366bdb9..05f844d 100644 --- a/apps/admin/src/pages/Library.tsx +++ b/apps/admin/src/pages/Library.tsx @@ -222,7 +222,7 @@ export default function Library() { {canManage && openAdd && ( -
+

Add book

@@ -279,7 +279,7 @@ export default function Library() { )} {canManage && openIssue && ( -
+

Issue book

diff --git a/apps/admin/src/pages/Login.tsx b/apps/admin/src/pages/Login.tsx index 5b44902..24af7d2 100644 --- a/apps/admin/src/pages/Login.tsx +++ b/apps/admin/src/pages/Login.tsx @@ -1,38 +1,33 @@ import { useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; -import { FiChevronRight, FiEye, FiEyeOff, FiPlus } from 'react-icons/fi'; +import { + FiBookOpen, + FiChevronDown, + FiChevronRight, + FiEye, + FiEyeOff, + FiPlay, + FiPlus, + FiShield, + FiUser, +} from 'react-icons/fi'; +import type { Role } from '@schoolerp/shared'; import { useAuth } from '../contexts/AuthContext'; import { supabase } from '../lib/supabase'; const REMEMBERED_ACCOUNT_KEY = 'pws.rememberedAccount'; /** - * The demo credentials hint, built behind the compile-time `__DEMO_MODE__` - * flag. Returning it from a function (rather than rendering `

` inside a - * `&&`) keeps the JSX literal inside the dead branch, so both Vite and esbuild - * strip it from production bundles. + * Passwordless demo entry: one small button that reveals the three roles. + * No credentials are stored or shown anywhere — picking a role signs in as + * the matching seeded person, and only while the app runs in demo mode + * (no Supabase configured). See `signInAsDemo` in AuthContext. */ -function demoHint() { - if (!SHOW_DEMO_HINT) return null; - // Assembled from parts so no complete credential string exists in source. - // Bundlers keep the JSX literal itself even in dead branches, so a literal - // here would leak the passwords into the production bundle regardless. - const accounts = [ - ['ADMIN001', ['Admin', '@', '1234']], - ['TCH001', ['Teacher', '@', '1234']], - ['0185/18', ['Student', '@', '14052010']], - ].map(([id, parts]) => `${id} / ${(parts as string[]).join('')}`); - return ( -

Demo: {accounts.join(' · ')}

- ); -} - -/** - * Demo credentials are never advertised in a production build. Bound to a local - * const so the bundler folds the whole branch away and the literals never reach - * the bundle (verified by grepping dist/assets/*.js for them). - */ -const SHOW_DEMO_HINT = __DEMO_MODE__; +const DEMO_ROLES: { role: Role; label: string; Icon: typeof FiShield }[] = [ + { role: 'admin', label: 'Admin', Icon: FiShield }, + { role: 'teacher', label: 'Teacher', Icon: FiBookOpen }, + { role: 'student', label: 'Student', Icon: FiUser }, +]; type RememberedAccount = { loginId: string; @@ -62,10 +57,11 @@ function getInitials(account: RememberedAccount) { } export default function Login() { - const { signIn } = useAuth(); + const { signIn, signInAsDemo, demoMode } = useAuth(); const navigate = useNavigate(); const [remembered] = useState(readRememberedAccount); const [showForm, setShowForm] = useState(() => !readRememberedAccount()); + const [demoOpen, setDemoOpen] = useState(false); const [loginId, setLoginId] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); @@ -134,6 +130,17 @@ export default function Login() { navigate('/dashboard'); }; + const handleDemo = (role: Role) => { + const { error: err } = signInAsDemo(role); + if (err) { + // Surface the refusal in the form's error area. + setError(err); + setShowForm(true); + return; + } + navigate('/dashboard'); + }; + const openRememberedAccount = () => { if (!remembered) return; setLoginId(remembered.loginId); @@ -263,8 +270,6 @@ export default function Login() {

)} - {demoHint()} -
)} + + {demoMode && ( +
+ + {demoOpen && ( +
+ {DEMO_ROLES.map(({ role, label, Icon }) => ( + + ))} +
+ )} +

+ Explore with sample data — no login needed. +

+
+ )}
diff --git a/apps/admin/src/pages/People.tsx b/apps/admin/src/pages/People.tsx index a98fbc0..92fbc7f 100644 --- a/apps/admin/src/pages/People.tsx +++ b/apps/admin/src/pages/People.tsx @@ -378,7 +378,7 @@ export default function People() { Every account starts with the password{' '} Student@ followed by the date of birth as DDMMYYYY. A student born 14 May 2010 gets{' '} - {`Student@${passwordFromDob('14/05/2010')}`}. + {passwordFromDob('14/05/2010')}.
diff --git a/apps/admin/src/pages/StudyRoom.tsx b/apps/admin/src/pages/StudyRoom.tsx index 7ae9e60..c4a0d7a 100644 --- a/apps/admin/src/pages/StudyRoom.tsx +++ b/apps/admin/src/pages/StudyRoom.tsx @@ -146,7 +146,7 @@ export default function StudyRoom() { {canShare && open && ( -
+

Share PDF

diff --git a/apps/admin/src/pages/Subjects.tsx b/apps/admin/src/pages/Subjects.tsx index 6334383..e34b75e 100644 --- a/apps/admin/src/pages/Subjects.tsx +++ b/apps/admin/src/pages/Subjects.tsx @@ -12,27 +12,57 @@ import { } from '../components/ui'; import { FiPlus, FiEdit3, FiTrash2 } from 'react-icons/fi'; +const DEFAULT_COLOR = '#4B5D2A'; +const EMPTY_FORM = { name: '', code: '', color: DEFAULT_COLOR }; + export default function Subjects() { const { isAdmin } = useAuth(); const data = useAppData(); const [open, setOpen] = useState(false); - const [form, setForm] = useState({ name: '', code: '' }); + const [editingId, setEditingId] = useState(null); + const [form, setForm] = useState(EMPTY_FORM); + + const subjects = data.subjects; + + if (!isAdmin()) return
Admin only
; - const handleCreate = (e: React.FormEvent) => { + const openCreate = () => { + setEditingId(null); + setForm(EMPTY_FORM); + setOpen(true); + }; + + const openEdit = (id: string) => { + const subject = subjects.find((s) => s.id === id); + if (!subject) return; + setEditingId(id); + setForm({ name: subject.name, code: subject.code, color: subject.color }); + setOpen(true); + }; + + const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); - if (!form.name.trim() || !form.code.trim()) { + const name = form.name.trim(); + const code = form.code.trim().toUpperCase(); + if (!name || !code) { data.notify('Subject name and code are required.'); return; } - data.addSubject({ name: form.name.trim(), code: form.code.trim().toUpperCase(), color: '#4B5D2A' }); - setForm({ name: '', code: '' }); + const duplicate = subjects.some((s) => s.id !== editingId && s.code.toUpperCase() === code); + if (duplicate) { + data.notify(`Code ${code} is already used by another subject.`); + return; + } + if (editingId) { + data.updateSubject(editingId, { name, code, color: form.color }); + } else { + data.addSubject({ name, code, color: form.color }); + } + setForm(EMPTY_FORM); + setEditingId(null); setOpen(false); }; - const subjects = data.subjects; - - if (!isAdmin()) return
Admin only
; - return (
@@ -40,7 +70,7 @@ export default function Subjects() {

Subjects

Manage school subjects.

-
@@ -71,7 +101,7 @@ export default function Subjects() { {s.code}
- - +
@@ -119,4 +158,4 @@ export default function Subjects() { )}
); -} +} \ No newline at end of file diff --git a/apps/admin/src/pages/TeachingAssignments.tsx b/apps/admin/src/pages/TeachingAssignments.tsx index 3cf5ddf..0583c25 100644 --- a/apps/admin/src/pages/TeachingAssignments.tsx +++ b/apps/admin/src/pages/TeachingAssignments.tsx @@ -1,5 +1,6 @@ -import { useState } from 'react'; +import { useMemo, useState } from 'react'; import { useAuth } from '../contexts/AuthContext'; +import { useAppData } from '../lib/appData'; import { Card, Button, @@ -11,16 +12,72 @@ import { } from '../components/ui'; import { FiPlus, FiEdit3, FiTrash2 } from 'react-icons/fi'; +const EMPTY_FORM = { teacher_id: '', section_label: '', subject: '' }; + export default function TeachingAssignments() { const { isAdmin } = useAuth(); + const data = useAppData(); const [open, setOpen] = useState(false); - const [form, setForm] = useState({ teacher: '', section: '', subject: '' }); + const [editingId, setEditingId] = useState(null); + const [form, setForm] = useState(EMPTY_FORM); + + const teachers = useMemo( + () => data.people.filter((p) => p.role === 'teacher' && p.is_active), + [data.people], + ); + const sections = useMemo( + () => data.classes.flatMap((c) => c.sections.map((s) => `${c.name} - ${s}`)), + [data.classes], + ); + const subjectNames = useMemo(() => data.subjects.map((s) => s.name), [data.subjects]); if (!isAdmin()) return
Admin only
; - const handleCreate = (e: React.FormEvent) => { + const teacherName = (id: string) => + data.people.find((p) => p.id === id)?.full_name ?? 'Unknown teacher'; + + const openCreate = () => { + setEditingId(null); + setForm({ + teacher_id: teachers[0]?.id ?? '', + section_label: sections[0] ?? '', + subject: subjectNames[0] ?? '', + }); + setOpen(true); + }; + + const openEdit = (id: string) => { + const entry = data.teachingAssignments.find((t) => t.id === id); + if (!entry) return; + setEditingId(id); + setForm({ teacher_id: entry.teacher_id, section_label: entry.section_label, subject: entry.subject }); + setOpen(true); + }; + + const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); - setForm({ teacher: '', section: '', subject: '' }); + if (!form.teacher_id || !form.section_label || !form.subject) { + data.notify('Pick a teacher, section and subject.'); + return; + } + const duplicate = data.teachingAssignments.some( + (t) => + t.id !== editingId && + t.teacher_id === form.teacher_id && + t.section_label === form.section_label && + t.subject === form.subject, + ); + if (duplicate) { + data.notify('That teacher is already assigned to this section and subject.'); + return; + } + if (editingId) { + data.updateTeachingAssignment(editingId, form); + } else { + data.addTeachingAssignment(form); + } + setForm(EMPTY_FORM); + setEditingId(null); setOpen(false); }; @@ -31,7 +88,7 @@ export default function TeachingAssignments() {

Teaching Assignments

Assign teachers to sections and subjects.

-
@@ -48,24 +105,28 @@ export default function TeachingAssignments() { - {[ - { teacher: 'Anuradha Gupta', section: 'IX - E', subject: 'Artificial Intelligence' }, - { teacher: 'Radhika Malhotra', section: 'IX - E', subject: 'Mathematics' }, - ].map((t, i) => ( - - {t.teacher} - {t.section} + {data.teachingAssignments.map((t) => ( + + {teacherName(t.teacher_id)} + {t.section_label} {t.subject} - - ))} + {data.teachingAssignments.length === 0 && ( + + + No teaching assignments yet. Use “Add assignment” to create one. + + + )}
@@ -74,37 +135,54 @@ export default function TeachingAssignments() { {open && (
-

Add teaching assignment

-
+

+ {editingId ? 'Edit teaching assignment' : 'Add teaching assignment'} +

+
- setForm({ ...form, teacher: e.target.value })} +
- setForm({ ...form, section: e.target.value })} +
- setForm({ ...form, subject: e.target.value })} className="w-full px-3 py-2 border rounded-lg" - /> + > + + {subjectNames.map((s) => ( + + ))} +
- +
@@ -112,4 +190,4 @@ export default function TeachingAssignments() { )}
); -} +} \ No newline at end of file diff --git a/apps/admin/src/vite-env.d.ts b/apps/admin/src/vite-env.d.ts index 6a763cd..11f02fe 100644 --- a/apps/admin/src/vite-env.d.ts +++ b/apps/admin/src/vite-env.d.ts @@ -1,9 +1 @@ /// - -/** - * Replaced at build time by the `__DEMO_MODE__` define in `vite.config.ts` - * (true outside production). Guarding demo-only code with it — rather than with - * a runtime object such as `import.meta.env.DEV` — lets the bundler prove the - * branch is dead and strip the demo credentials from a production bundle. - */ -declare const __DEMO_MODE__: boolean; diff --git a/apps/admin/vite.config.ts b/apps/admin/vite.config.ts index 53fd318..02133b2 100644 --- a/apps/admin/vite.config.ts +++ b/apps/admin/vite.config.ts @@ -28,9 +28,6 @@ export default defineConfig(({ mode }) => { define: { 'import.meta.env.SUPABASE_URL': JSON.stringify(supabaseUrl), 'import.meta.env.SUPABASE_PUBLISHABLE_KEY': JSON.stringify(supabaseKey), - // Replaced with the literal `true`/`false`, so demo accounts and the - // demo-credential hint are eliminated from production bundles. - __DEMO_MODE__: JSON.stringify(mode !== 'production'), }, server: { host: '0.0.0.0', diff --git a/scripts/create-admin.mjs b/scripts/create-admin.mjs index e0c0ee9..54f89ff 100755 --- a/scripts/create-admin.mjs +++ b/scripts/create-admin.mjs @@ -5,11 +5,12 @@ * Usage: * SUPABASE_URL=https://xxx.supabase.co \ * SUPABASE_SERVICE_ROLE_KEY=... \ - * node scripts/create-admin.mjs ADMIN001 "School Administrator" 'REDACTED' + * node scripts/create-admin.mjs ADMIN001 "School Administrator" * - * Or run `node scripts/create-admin.mjs` and answer the prompts (the service - * role key is read from the environment, or from .env.local, never typed into - * a browser). + * The password is then prompted for interactively (preferred — it stays out + * of shell history). Or run `node scripts/create-admin.mjs` and answer all + * prompts. The service role key is read from the environment, or from + * .env.local, never typed into a browser. * * The service role key must stay on this machine. Never commit it, never put it * in apps/*, and never ship it to Vercel as a client variable. @@ -55,7 +56,7 @@ Set the project URL and the SERVICE ROLE key (server-side only): SUPABASE_URL=https://.supabase.co \\ SUPABASE_SERVICE_ROLE_KEY= \\ - node scripts/create-admin.mjs ADMIN001 "School Administrator" 'REDACTED' + node scripts/create-admin.mjs ADMIN001 "School Administrator" The service role key is never used by the web apps. Do not put it in .env files that Vite reads. diff --git a/supabase/functions/admin-users/index.ts b/supabase/functions/admin-users/index.ts index 5ba48a9..0ffeaf8 100644 --- a/supabase/functions/admin-users/index.ts +++ b/supabase/functions/admin-users/index.ts @@ -21,7 +21,6 @@ interface ImportRow { } const STUDENT_DOMAIN = 'pws.local'; -const ADMIN_DOMAIN = 'pws.local'; /** School rule: Student@ + DDMMYYYY. */ function passwordFromDob(isoDate: string): string { @@ -119,7 +118,9 @@ Deno.serve(async (req) => { } const { data: created, error: createError } = await admin.auth.admin.createUser({ - email: `${loginId.toLowerCase()}@${ADMIN_DOMAIN}`, + // Normalize identically to authEmail()/client toAuthEmail() so the created + // account matches the sign-in lookup (audit finding F8). + email: authEmail(loginId), password, email_confirm: true, user_metadata: { full_name: fullName, login_id: loginId }, diff --git a/supabase/migrations/0004_profiles_hardening.sql b/supabase/migrations/0004_profiles_hardening.sql new file mode 100644 index 0000000..a8bd5a3 --- /dev/null +++ b/supabase/migrations/0004_profiles_hardening.sql @@ -0,0 +1,145 @@ +-- ============================================================================ +-- 0004_profiles_hardening.sql +-- Security fixes from the full-mode security audit (run-1). Each block maps to a +-- confirmed finding. Safe to run once after 0001-0003; idempotent where practical. +-- +-- F1 (critical) rls-profiles-self-escalation -> protect privileged columns +-- F5 (medium) rls-profiles-directory-overbroad-read-> scoped directory reads +-- F2 (medium) rls-audit-log-insert-forgery -> close open audit INSERT +-- F3 (medium) rls-attendance-cross-section-write -> scope to teacher's students +-- F4 (medium) rls-report-cards-cross-section-insert-> scope to teacher's students +-- F6 (low) rls-events-update-scope-recheck -> re-check sections on UPDATE +-- F7 (low) rls-course-goals-update-scope-recheck-> re-check teaching on UPDATE +-- ============================================================================ + +BEGIN; + +-- --------------------------------------------------------------------------- +-- F1: A user must not be able to raise their own role / is_active / login_id. +-- Two independent layers: +-- (a) column-level grants: authenticated may UPDATE only non-privileged columns; +-- (b) a BEFORE UPDATE trigger as defense-in-depth (also covers any future grant). +-- service_role (Edge Functions / create-admin) keeps full access and bypasses RLS. +-- --------------------------------------------------------------------------- + +-- (b) Trigger. SECURITY INVOKER so current_user reflects the calling role +-- (a SECURITY DEFINER function would mask it as the owner). search_path pinned. +CREATE OR REPLACE FUNCTION public.protect_profile_privileges() +RETURNS trigger +LANGUAGE plpgsql +SET search_path = '' +AS $$ +BEGIN + -- The service role and the database owner provision accounts; admins may manage + -- other users. Everyone else is blocked from touching the privileged columns. + IF current_user IN ('service_role', 'postgres') OR public.is_admin() THEN + RETURN NEW; + END IF; + + IF NEW.role IS DISTINCT FROM OLD.role + OR NEW.is_active IS DISTINCT FROM OLD.is_active + OR NEW.login_id IS DISTINCT FROM OLD.login_id THEN + RAISE EXCEPTION 'permission denied: role, is_active and login_id are protected' + USING ERRCODE = '42501'; + END IF; + + RETURN NEW; +END; +$$; + +DROP TRIGGER IF EXISTS profiles_protect_privileges ON public.profiles; +CREATE TRIGGER profiles_protect_privileges + BEFORE UPDATE ON public.profiles + FOR EACH ROW EXECUTE FUNCTION public.protect_profile_privileges(); + +-- Narrow the self policy from FOR ALL to read + update of own row only. +DROP POLICY IF EXISTS profiles_self ON public.profiles; +CREATE POLICY profiles_self ON public.profiles + FOR SELECT USING (auth.uid() = id); +CREATE POLICY profiles_self_update ON public.profiles + FOR UPDATE USING (auth.uid() = id) WITH CHECK (auth.uid() = id); + +-- (a) Column grants. Profiles are provisioned by the service role, so anon/authenticated +-- do not need INSERT/DELETE, and may UPDATE only the safe self-service columns. +REVOKE INSERT, DELETE ON public.profiles FROM anon, authenticated; +REVOKE UPDATE ON public.profiles FROM anon, authenticated; +GRANT UPDATE (full_name, avatar_path, must_change_password) ON public.profiles TO authenticated; + +-- --------------------------------------------------------------------------- +-- F5: Replace the blanket "read every active profile" with scoped reads. +-- Matches supabase/tests/rls_matrix.sql: student reads self only; teacher reads the +-- students they teach; admin reads all (profiles_admin_read already exists). +-- If a product requirement later needs a broader directory, add it explicitly. +-- --------------------------------------------------------------------------- +DROP POLICY IF EXISTS profiles_read_active ON public.profiles; +CREATE POLICY profiles_teacher_read ON public.profiles + FOR SELECT USING (public.teaches_student(id)); + +-- --------------------------------------------------------------------------- +-- F2: Audit trail integrity. service_role bypasses RLS, so the Edge Function keeps +-- writing without any policy. Remove the open INSERT; allow admins to append only. +-- --------------------------------------------------------------------------- +DROP POLICY IF EXISTS audit_log_service_insert ON public.audit_log; +CREATE POLICY audit_log_admin_insert ON public.audit_log + FOR INSERT WITH CHECK (public.is_admin()); + +-- --------------------------------------------------------------------------- +-- F3: Attendance writes must be scoped to the teacher's own students (the read +-- policy already does this). Admins remain unrestricted. +-- --------------------------------------------------------------------------- +DROP POLICY IF EXISTS attendance_teacher_write ON public.attendance; +CREATE POLICY attendance_teacher_write ON public.attendance + FOR ALL USING ( + public.is_admin() + OR (auth.uid() = marked_by AND public.teaches_student(student_id)) + ) WITH CHECK ( + public.is_admin() + OR (auth.uid() = marked_by AND public.teaches_student(student_id)) + ); + +-- --------------------------------------------------------------------------- +-- F4: Report-card create/update must be scoped to the teacher's own students. +-- --------------------------------------------------------------------------- +DROP POLICY IF EXISTS report_cards_teacher_write ON public.report_cards; +CREATE POLICY report_cards_teacher_write ON public.report_cards + FOR INSERT WITH CHECK ( + auth.uid() = created_by + AND (public.is_admin() OR public.teaches_student(student_id)) + ); +DROP POLICY IF EXISTS report_cards_teacher_update ON public.report_cards; +CREATE POLICY report_cards_teacher_update ON public.report_cards + FOR UPDATE USING ( + auth.uid() = created_by + AND (public.is_admin() OR public.teaches_student(student_id)) + ) WITH CHECK ( + auth.uid() = created_by + AND (public.is_admin() OR public.teaches_student(student_id)) + ); + +-- --------------------------------------------------------------------------- +-- F6: Re-check section scope when a teacher updates their own event, so it cannot +-- be retargeted to sections they do not teach. +-- --------------------------------------------------------------------------- +DROP POLICY IF EXISTS school_events_owner_update ON public.school_events; +CREATE POLICY school_events_owner_update ON public.school_events + FOR UPDATE USING (auth.uid() = created_by OR public.is_admin()) + WITH CHECK ( + public.is_admin() + OR ( + auth.uid() = created_by + AND NOT EXISTS ( + SELECT 1 FROM unnest(COALESCE(section_ids, ARRAY[]::uuid[])) AS s + WHERE NOT public.teaches_section(s) + ) + ) + ); + +-- --------------------------------------------------------------------------- +-- F7: Re-check the teaching relationship when a teacher updates a course goal. +-- --------------------------------------------------------------------------- +DROP POLICY IF EXISTS course_goals_teacher_update ON public.course_goals; +CREATE POLICY course_goals_teacher_update ON public.course_goals + FOR UPDATE USING (auth.uid() = teacher_id AND public.teaches_student(student_id)) + WITH CHECK (auth.uid() = teacher_id AND public.teaches_student(student_id)); + +COMMIT; diff --git a/supabase/tests/verify_rls_local.py b/supabase/tests/verify_rls_local.py index 6b668b6..cec6324 100644 --- a/supabase/tests/verify_rls_local.py +++ b/supabase/tests/verify_rls_local.py @@ -2,7 +2,7 @@ pgTAP (`supabase/tests/*.sql`) is the canonical suite and needs `supabase test db`. This script is the fallback for environments without Docker: it boots a -throwaway Postgres with `pgserver`, applies 0001 + 0002 + 0003, seeds a school and +throwaway Postgres with `pgserver`, applies 0001-0004, seeds a school and asserts the same rules through the `authenticated` role. python3 -m venv .venv && .venv/bin/pip install pgserver @@ -22,6 +22,7 @@ db.psql(open('/home/user/schoolerp/supabase/migrations/0001_initial_schema.sql').read().replace('CREATE EXTENSION IF NOT EXISTS pgcrypto;','')) db.psql(open('/home/user/schoolerp/supabase/migrations/0002_dashboard_modules.sql').read()) db.psql(open('/home/user/schoolerp/supabase/migrations/0003_function_hardening.sql').read()) +db.psql(open('/home/user/schoolerp/supabase/migrations/0004_profiles_hardening.sql').read()) ids = {k: str(uuid.uuid4()) for k in ['admin','cteach','oteach','sa','sb']} sec, osec, cls, subj = (str(uuid.uuid4()) for _ in range(4)) @@ -145,6 +146,16 @@ def attempt(uid, sql): # which collapsed to a tautology and let a teacher open a thread with ANY # student. 'sa' sits in a section this teacher does not teach. ("teacher opens thread with foreign student", attempt(ids['oteach'], f"insert into threads (teacher_id,student_id,subject) values ('{ids['oteach']}','{ids['sa']}','Extra classes')")), + # Regression (security audit run-1 / migration 0004): + # F1 — a user must not be able to raise their own role / is_active / login_id. + ("student escalates own role to admin", attempt(ids['sa'], f"update profiles set role='admin' where id='{ids['sa']}'")), + ("student flips own is_active", attempt(ids['sa'], f"update profiles set is_active=false where id='{ids['sa']}'")), + ("student rewrites own login_id", attempt(ids['sa'], f"update profiles set login_id='HACKED' where id='{ids['sa']}'")), + # F2 — the audit trail must not be forgeable by a regular user. + ("student forges an audit_log entry", attempt(ids['sa'], f"insert into audit_log (actor_id,action,entity_type) values ('{ids['admin']}','create-admin','profile')")), + # F3/F4 — teacher writes must be scoped to students they teach (sa is NOT oteach's). + ("unrelated teacher marks foreign attendance", attempt(ids['oteach'], f"insert into attendance (student_id,section_id,date,mark,marked_by) values ('{ids['sa']}','{sec}','2026-11-10','present','{ids['oteach']}')")), + ("unrelated teacher authors foreign report card", attempt(ids['oteach'], f"insert into report_cards (student_id,term,academic_year,created_by) values ('{ids['sa']}','FORGED','2026-27','{ids['oteach']}')")), ] for name, res in neg: ok = res.startswith("DENIED") or res.startswith("NO-ROWS"); fails += 0 if ok else 1 @@ -156,6 +167,10 @@ def attempt(uid, sql): ("teacher creates class event", attempt(ids['oteach'], f"insert into school_events (title,kind,start_date,end_date,section_ids,created_by) values ('Unit test','Exam','2026-12-02','2026-12-02',ARRAY['{osec}']::uuid[],'{ids['oteach']}')")), ("admin applies sibling discount", attempt(ids['admin'], f"update fee_records set sibling_discount_percent=50 where student_id='{ids['sb']}'")), ("teacher opens thread with own student", attempt(ids['oteach'], f"insert into threads (teacher_id,student_id,subject) values ('{ids['oteach']}','{ids['sb']}','Revision plan')")), + # Regression (migration 0004) — legitimate self-service / in-scope writes still work. + ("student updates own full_name", attempt(ids['sa'], f"update profiles set full_name='Student A Renamed' where id='{ids['sa']}'")), + ("teacher marks own-student attendance", attempt(ids['oteach'], f"insert into attendance (student_id,section_id,date,mark,marked_by) values ('{ids['sb']}','{osec}','2026-11-12','present','{ids['oteach']}')")), + ("teacher authors own-student report card", attempt(ids['oteach'], f"insert into report_cards (student_id,term,academic_year,created_by) values ('{ids['sb']}','UNIT','2026-27','{ids['oteach']}')")), ] for name, res in pos: ok = res == "ALLOWED"; fails += 0 if ok else 1 From 402e022dd52b745bf6c76adceadcfae8ddb60bb1 Mon Sep 17 00:00:00 2001 From: sahajiscoding <135018977+sahajiscoding@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:46:22 +0000 Subject: [PATCH 2/5] docs: record functional + security audit results and live migration verification - Functional audit marked resolved (82/0/0/11). - Full-mode security audit reports (8 findings, all fixed). - Migrations 0001-0004 applied to live Supabase and empirically verified (escalation blocked, self-service allowed); test data cleaned up. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- PROJECT_STATUS.md | 22 ++- docs/audits/2026-11-05-functional-audit.md | 148 ++++++++++++++++++ .../2026-11-05-security-audit-findings.md | 100 ++++++++++++ .../2026-11-05-security-audit-validation.md | 63 ++++++++ docs/audits/2026-11-05-security-audit.md | 66 ++++++++ .../specs/2026-11-03-school-erp-design.md | 1 + 6 files changed, 396 insertions(+), 4 deletions(-) create mode 100644 docs/audits/2026-11-05-functional-audit.md create mode 100644 docs/audits/2026-11-05-security-audit-findings.md create mode 100644 docs/audits/2026-11-05-security-audit-validation.md create mode 100644 docs/audits/2026-11-05-security-audit.md diff --git a/PROJECT_STATUS.md b/PROJECT_STATUS.md index 4376236..6e8e1f9 100644 --- a/PROJECT_STATUS.md +++ b/PROJECT_STATUS.md @@ -1,6 +1,6 @@ # Project Status — Pacific World School ERP -**Last updated:** 2026-11-04 +**Last updated:** 2026-11-05 **Current milestone:** Milestone 3 — Dashboard modules (admin console complete, backend schema written, mobile pending). **Next milestone:** Wire the admin console to Supabase (replace demo store), then Milestone 4 — Messaging. @@ -23,7 +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; demo credentials hint; remembered account | +| 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 | ### Dashboard modules @@ -50,14 +51,25 @@ This file is the single source of truth for project state. Every agent must read |---|---|---| | Initial schema + RLS | `supabase/migrations/0001_initial_schema.sql` | 77 statements, parses clean; `current_role()` renamed to `app_role()` (was a reserved-keyword bug) | | Dashboard schema + RLS | `supabase/migrations/0002_dashboard_modules.sql` | 15 tables, class-teacher helpers, sibling links, admin-only fees; 82 statements, parses clean | +| Function hardening | `supabase/migrations/0003_function_hardening.sql` | Narrows EXECUTE on the SECURITY DEFINER helpers to `authenticated` | +| **Security-audit hardening** | `supabase/migrations/0004_profiles_hardening.sql` | Fixes the 8 audit findings: protects `profiles.role/is_active/login_id` (column grants + trigger), scopes profile reads, closes audit-log forgery, scopes attendance/report-card/event/goal writes | | Base RLS matrix | `supabase/tests/rls_matrix.sql` | 24 assertions | | Dashboard RLS matrix | `supabase/tests/rls_matrix_dashboard.sql` | 24 assertions (leave routing, self-approval guard, events scoping, fees/siblings, cards) | -| Local RLS verifier | `supabase/tests/verify_rls_local.py` | Boots a throwaway Postgres, applies both migrations, asserts 20 rules as `authenticated` — **all pass** | +| Local RLS verifier | `supabase/tests/verify_rls_local.py` | Boots a throwaway Postgres, applies 0001–0004, asserts the rules as `authenticated` incl. new security regressions (self-escalation, audit forgery, cross-section writes) — run `npm run verify:rls` | | Admin provisioning function | `supabase/functions/admin-users/index.ts` | `create-admin`, `import-students` (`Student@DDMMYYYY`); verifies JWT + admin role, writes audit log | | Shared CORS | `supabase/functions/_shared/cors.ts` | — | | 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) + +- 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. +- All hardcoded demo passwords removed (GitGuardian): `DEMO_LOGINS` in `AuthContext.tsx`, the split-string credential hint in `Login.tsx`, the `'REDACTED'` fallback in `appData.tsx` (no DOB → no initial password shown), the literal sibling password in `seed.ts` (now derived via `passwordFromDob`), and the example password in `scripts/create-admin.mjs` (password is prompted interactively). The `__DEMO_MODE__` compile flag is gone — there is nothing left to strip. +- Fixed a display bug in `People.tsx`: the import help rendered `Student@Student@14052010` (double prefix); it now shows the derived value once. +- 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. + ### Verification done - `npm run typecheck --workspace=apps/admin` — clean. @@ -110,6 +122,8 @@ have not been applied to that project from this environment. ## Known gaps +0. **Functional audit (2026-11-05) — all defects FIXED:** every module was click-tested as admin/teacher/student. The first pass found 12 broken + 4 partial defects (Teaching Assignments stub, four desktop-hidden dialogs, students marking attendance, empty audit log, "View as" trap, Submissions roster, Subjects edit, per-student declarations, event/broadcast targeting). **All 15 were fixed and re-verified: 82 working / 0 broken / 0 partial / 11 notes across 93 runtime checks.** Details: `docs/audits/2026-11-05-functional-audit.md`. +0b. **Security audit (2026-11-05) — full Cloudflare `security-audit` skill, all findings FIXED:** the live Supabase RLS layer, Edge Function, client, deploy headers and CI were audited. Found **1 critical + 4 medium + 3 low** issues — the critical one let any signed-in user escalate themselves to admin via the `profiles_self` policy. All 8 are fixed in `supabase/migrations/0004_profiles_hardening.sql` (+ an Edge Function normalization fix), with new regression assertions in `verify_rls_local.py`. Report, traces and owner replay plan: `~/security-audit-skill/schoolerp/run-1/` (REPORT.md / FINDINGS-DETAIL.md / NEEDS-VALIDATION.md). **Migrations 0001–0004 have now been APPLIED to the live Supabase project (`ausnymdtnpewcfvdrpcu`) and verified empirically:** 32 tables all RLS-enabled; a live student self-escalation attempt returns `permission denied for table profiles`, while a legitimate self-service rename succeeds (role unchanged). Test data was cleaned up. 1. The admin console still runs on the demo store. Wiring it to the new tables (replacing `appData.tsx` with Supabase queries) is the next step; the types and RLS already match. 2. The pgTAP suites themselves have not been run through `supabase test db` (no Docker here); their rules are covered by `supabase/tests/verify_rls_local.py`, which passes against real Postgres 14. 3. Report card marks are stored as `jsonb`; if per-subject grade analytics become a requirement, normalise into `report_card_marks`. @@ -118,7 +132,7 @@ have not been applied to that project from this environment. ## Next up -1. Apply `0001` + `0002`, run both pgTAP suites, fix any policy fallout. +1. ~~Apply `0001`–`0004`~~ **Done** — applied to the live project and verified. Remaining: run the pgTAP suites (`supabase test db`) when Docker is available, and deploy the `admin-users` Edge Function. 2. Swap the demo store for Supabase queries, module by module (Approvals → Assignments → Communications). 3. Deploy `admin-users`; run `scripts/create-admin.mjs` for the first admin. 4. Mobile: login, assignments, approvals. diff --git a/docs/audits/2026-11-05-functional-audit.md b/docs/audits/2026-11-05-functional-audit.md new file mode 100644 index 0000000..19285db --- /dev/null +++ b/docs/audits/2026-11-05-functional-audit.md @@ -0,0 +1,148 @@ +# Functional Audit — Pacific World School ERP (Admin Console) + +**Date:** 2026-11-05 +**Scope:** Every feature in the admin console (`apps/admin`), exercised as Admin, Teacher, and Student. +**Method:** The real production app was bundled and booted in a DOM (jsdom), then driven like a user — clicking buttons, filling forms, navigating, and checking that the underlying data actually changed. **93 checks** were run across all 19 routes. This is a runtime audit, not just a code read. + +> The console runs on the seeded demo store (no Supabase keys). Everything below is about the **demo build** the owners will see. The database schema/RLS for the live system is written separately and is not exercised here. + +--- + +## ✅ RESOLVED — update 2026-11-05 + +**Every defect in this report has been fixed and re-verified at runtime.** The original pass found +12 broken + 4 partial issues; all 15 were fixed (plus the targeting/notification items). The current +scorecard is **82 working / 0 broken / 0 partial / 11 notes (93 checks)**. Typecheck, lint (0 errors) +and the production build all pass. The sections below are kept as the historical record of what was +found; each is now resolved. A separate **full-mode security audit** of the live Supabase RLS layer was +also completed the same day and all 8 of its findings were fixed (`supabase/migrations/0004_profiles_hardening.sql`). + +--- + +## Scorecard + +| Result | Original | Now | Meaning | +|---|---|---|---| +| ✅ Working | 64 | **82** | Feature does what it claims | +| ❌ Broken | 12 | **0** | Feature is dead, wrong, or a security hole | +| ⚠️ Partial | 4 | **0** | Works, but a meaningful part is cosmetic | +| ℹ️ Note | 11 | **11** | Expected demo limitation / not built yet | + +**Bottom line (original):** most day-to-day modules genuinely work, but one whole page was a stub +(Teaching Assignments), four buttons were invisible on desktop, students could mark attendance, and the +audit log recorded nothing. **All of these are now fixed** — Teaching Assignments has full CRUD, the +dialogs open on desktop, attendance marking is teacher/admin-only, ~30 actions write to the audit log, +the "View as" switcher stays visible for admins, the Submissions tab lists every missing student, +Subjects edit works, declarations sign per-student, and events/broadcasts/notifications are correctly +targeted. The 11 remaining notes are expected demo limitations (no real file uploads, etc.), not bugs. + +--- + +## ❌ Broken — needs fixing · ✅ all resolved + +### 1. Teaching Assignments page is entirely non-functional +`apps/admin/src/pages/TeachingAssignments.tsx` +- The table is a **hardcoded 2-row array** (line 52), not real data. +- The "Add assignment" form **throws the input away** — `handleCreate` (line 21) just clears the form and closes the modal; nothing is saved. +- The **Edit and Delete buttons are empty** (`onClick={() => {}}`, lines 60 & 63). +- **Impact:** an admin cannot actually assign teachers to sections/subjects. Verified: submitting the form leaves the row count unchanged (2 → 2). + +### 2–5. Four modal dialogs are hidden on desktop (`lg:hidden`) +A CSS class (`lg:hidden`) hides these dialogs on screens ≥ 1024px, so on a laptop/desktop the button looks like it does nothing: +| Button | File:line | Severe? | +|---|---|---| +| Study Room → **Share PDF** | `StudyRoom.tsx:149` | **Yes** — no other way to share on desktop | +| Library → **Add book** | `Library.tsx:225` | **Yes** — no other way to add on desktop | +| Library → **Issue book** | `Library.tsx:282` | **Yes** — no other way to issue on desktop | +| Attendance → **Mark attendance** | `Attendance.tsx:241` | Lower — the register table below still marks fine | +- **Impact:** on desktop, Share PDF / Add book / Issue book appear completely dead. (The underlying save logic works — verified on the mobile-width dialog — so this is purely the hidden-dialog CSS.) + +### 6. Students can mark attendance (access-control hole) +`apps/admin/src/pages/Attendance.tsx` +- The "Mark today" register shows **P / A / L / M buttons to everyone**, and `handleMark` (line 70) never checks the role. +- **Verified:** signed in as a student, clicking "A" created a new attendance record. A student can mark **any** student present/absent. +- **Impact:** contradicts the rule that students are read-only for attendance (the DB RLS enforces this, but the demo UI does not). + +### 7. Attendance week-grid day badges don't work as they look +`apps/admin/src/pages/Attendance.tsx:173` +- Clicking a day badge in the weekly grid re-saves the **already-shown status** for the **currently selected date** — it does not cycle the status and does not target the day you clicked. +- **Impact:** the grid looks interactive but clicking it does nothing useful (or writes to the wrong day). + +### 8. Assignments → Submissions tab hides most missing students +`apps/admin/src/pages/Assignments.tsx:96` +- The roster of "Not submitted" rows uses `.slice(0, 1)`, so **only one** missing student is shown per assignment, no matter how many haven't submitted. +- **Impact:** a teacher can't see the full list of who still owes work. (The per-assignment "Review" modal does show the full roster correctly.) + +### 9. Subjects → Edit is a stub +`apps/admin/src/pages/Subjects.tsx:74` +- The Edit button only shows a toast ("Editing … is available to admins on the live database"). No editing happens. +- **Impact:** subjects can be added and removed, but not renamed/edited. + +### 10. Audit Log records nothing +`apps/admin/src/lib/appData.tsx` (`logAudit`) + `AuditLog.tsx` +- `logAudit` exists but **no page ever calls it**. The Audit Log only ever shows the 5 seeded entries. +- **Verified:** adding a class did not add an audit entry. +- **Impact:** the page claims "every administrative action is recorded," but in the demo nothing is. + +### 11. Admin "View as" preview traps the admin +`apps/admin/src/components/AppShell.tsx:351` +- The role switcher is shown only when `isAdmin()` is true — but `isAdmin()` respects the *previewed* role. So when an admin previews **Teacher** or **Student**, the switcher **disappears**, and there's no "Back to my role" control. +- **Verified:** after "View as → Student," the only way back is to sign out. +- **Impact:** an admin demoing the student/teacher view gets stuck and must sign out to return. + +--- + +## ⚠️ Partial — works, but a key part is cosmetic · ✅ all resolved + +| Feature | What's cosmetic | Where | +|---|---|---| +| **Communications → Send message** | The "Send to" audience is ignored — every broadcast goes into one shared notification list that **all users** see. | `appData.tsx` `broadcastMessage` | +| **Communications → Declarations** | Signing is **global**: one student signing marks the form "signed" for everyone (no per-student signatures). | `appData.tsx` `signDeclaration` | +| **Events & Calendar** | The audience ("Whole school" / "Class only") is a label only — **all users see all events**; no per-section filtering. | `Events.tsx` | +| **Fees** | **Teachers** can record payments and link siblings, but the spec/RLS says fees are **admin-only**. | `Fees.tsx:37` | + +--- + +## ℹ️ Expected demo limitations (not bugs, but know before showing owners) + +- **No real file uploads.** Assignment attachments, submissions, and Study Room "PDFs" are just file-name text. Study Room "Open" shows the teacher's note, not an actual PDF. +- **Notifications are one shared list** for every user; marking read affects everyone. +- **"Today" is hardcoded to 2026-11-04** on the Dashboard, Events, and Assignments (Attendance uses the real clock). These will look stale on any other date. +- **Poll close dates aren't enforced** — students can vote after `closes_at`. +- **Subject dropdowns are fixed lists** in Course Progress / Study Room / Assignments — new subjects added in the Subjects page don't appear there. +- **No private teacher↔student messaging UI yet** — threads are seeded but there's no inbox/thread screen (that's Milestone 4). +- **People** has add + CSV import only — no edit / deactivate / reset-password yet (Milestone 2 scope). +- **Library**: reserved books have no "Return" action (only issued ones do); the Issue form has no required-field validation. +- **Gallery** is view-only — albums look clickable but open nothing; no upload. + +--- + +## ✅ What's solid (verified working) + +- **Login & demo entry** — passwordless Admin/Teacher/Student demo button; sign out; remembered account. +- **Approvals (leave)** — student applies (with date validation), routes to the **class teacher of the section**, teacher/admin approve or reject, history + filters. +- **Course Progress** — teacher adds goals (validates 0–100), student sees only their own. +- **Communications** — create declaration / poll / broadcast; student signs and votes (with the caveats above). +- **Events** — admin adds school events, teacher adds class events, calendar month navigation. +- **Assignments** — teacher publishes, student sees only their section's work, submits, teacher marks reviewed; re-submit is blocked. +- **Report Cards** — teacher enters marks → grade/percentage auto-computed, assigned to the student, printable, withdrawable; validates empty marks. +- **Attendance marking** — teacher marks via the register table; student reads their own (but see bug #6). +- **Fees** — record payment updates status; **50% sibling discount lands on the second child's invoice**; unlink removes it; student sees only their own. +- **People** — add student (password derived from DOB), CSV import with row-level validation (bad dates rejected), template + credentials export. +- **Classes** — add (with sections), duplicate rejected, remove. +- **Subjects** — add and remove. +- **Enrollments** — place a student into a class/section; roster search. +- **Dashboard** — role-aware stats and quick links. +- **Notifications** — bell, mark read / mark all read. + +--- + +## Suggested fix priority · ✅ completed + +1. **Security first:** stop students marking attendance (#6); make Fees admin-only (partial). +2. **Un-break desktop:** remove `lg:hidden` from the four dialogs (#2–5) — one-line fixes each. +3. **Fix the trap:** keep the "View as" switcher visible for real admins (#11). +4. **Make Teaching Assignments real** (#1) — or hide the page until it's built. +5. **Wire the audit log** (#10) and the Submissions roster (#8). +6. **Smaller fixes:** Subjects edit (#9), attendance week-grid (#7). +7. Targeting (broadcast/declarations/events) and real file uploads are larger items best handled when the console is wired to Supabase. diff --git a/docs/audits/2026-11-05-security-audit-findings.md b/docs/audits/2026-11-05-security-audit-findings.md new file mode 100644 index 0000000..e30321b --- /dev/null +++ b/docs/audits/2026-11-05-security-audit-findings.md @@ -0,0 +1,100 @@ +# Findings Detail — schoolerp run-1 + +All findings are `confirmed` via complete source traces (policy text + documented grants + absence +of guards). Live Postgres execution was not available (skill forbids installing dependencies); the +owner replay plan is in NEEDS-VALIDATION.md. Every finding below is **fixed** in this branch. + +--- + +## 1. `rls-profiles-self-escalation` — CRITICAL (fixed) +**Any signed-in user can escalate themselves to admin.** + +- **Root cause:** `profiles_self` is `FOR ALL USING (auth.uid() = id)` (`0001:238`). `FOR ALL` reuses + `USING` as the implicit `WITH CHECK`, so it authorizes writing **every column** of the caller's own + row — including `role`, `is_active`, `login_id`. No trigger or column grant protects them (the only + write-guard triggers are on leave_requests/student_details/course_goals/fee_records). `authenticated` + holds `UPDATE` (the project's `verify_rls_local.py:56` grants it, mirroring Supabase defaults). +- **Trace:** `profiles_self` (0001:238) → `profiles.role` (0001:8) → `is_admin()` (0001:197) reads the + rewritten role and returns true, unlocking every admin policy + the admin Edge Function. +- **Reproduction (any student):** + ``` + PATCH /rest/v1/profiles?id=eq. + Authorization: Bearer + Content-Type: application/json + + {"role":"admin"} + ``` + The policy authorizes it (`auth.uid()=id`, no column guard). The caller is now admin. +- **Fix (0004):** two layers — + 1. Column grants: `REVOKE INSERT,DELETE,UPDATE ON profiles FROM anon,authenticated;` + `GRANT UPDATE (full_name, avatar_path, must_change_password) TO authenticated;` + 2. `protect_profile_privileges` BEFORE UPDATE trigger (SECURITY INVOKER, `search_path=''`) that + raises `permission denied` if a non-service-role/non-admin changes role/is_active/login_id. + `profiles_self` narrowed to SELECT + a separate self-UPDATE policy. + In production the column grant blocks the PATCH before the trigger; in the local verifier (which + re-grants blanket UPDATE) the trigger blocks it. Both layers are asserted by new regression tests. + +--- + +## 2. `rls-audit-log-insert-forgery` — MEDIUM (fixed) +**Any authenticated user can forge audit entries.** +- **Root cause:** `audit_log_service_insert FOR INSERT WITH CHECK (true)` (`0001:442`) applies to every + role. Reads are admin-only, but writes are open, so a student can insert rows with any `actor_id`. +- **Reproduction:** `POST /rest/v1/audit_log {"actor_id":"","action":"create-admin","entity_type":"profile"}`. +- **Fix (0004):** `DROP POLICY audit_log_service_insert;` (service_role bypasses RLS, so the Edge + Function keeps writing) + `audit_log_admin_insert WITH CHECK (is_admin())`. + +## 3. `rls-attendance-cross-section-write` — MEDIUM (fixed) +**A teacher can mark attendance for students they don't teach.** +- **Root cause:** `attendance_teacher_write FOR ALL USING/WITH CHECK (auth.uid()=marked_by OR is_admin())` + (`0002:425`) never calls `teaches_student(student_id)`, while `attendance_read` (`0002:421`) does. +- **Reproduction:** a teacher inserts an attendance row for another section's student with + `marked_by` = own id. +- **Fix (0004):** teacher branch becomes `auth.uid()=marked_by AND teaches_student(student_id)` in both + USING and WITH CHECK (admins unrestricted). Matches the read scope. + +## 4. `rls-report-cards-cross-section-insert` — MEDIUM (fixed) +**A teacher can fabricate report cards for any student.** +- **Root cause:** `report_cards_teacher_write FOR INSERT WITH CHECK (auth.uid()=created_by AND + (app_role()='teacher' OR is_admin()))` (`0002:412`) omits `teaches_student`, unlike + `course_goals_teacher_write` (`0002:336`). +- **Fix (0004):** insert + update require `created_by` AND `(is_admin() OR teaches_student(student_id))`. + +## 5. `rls-profiles-directory-overbroad-read` — MEDIUM (fixed) +**Any authenticated user can read every active profile (login ids + roles).** +- **Root cause:** `profiles_read_active FOR SELECT USING (is_active)` (`0001:241`) exposes all active + profiles, contradicting the project's own `rls_matrix.sql:90` ("student_a cannot read student_b"). + Enables username/role enumeration against predictable DOB-derived passwords. +- **Reproduction:** `GET /rest/v1/profiles?select=login_id,role,full_name` as any user. +- **Fix (0004):** drop the blanket policy; add `profiles_teacher_read USING (teaches_student(id))`. + Self read (`profiles_self`) and admin read (`profiles_admin_read`) remain. Students no longer get a + directory; add an explicit minimal policy later only if a product requirement needs it. + +## 6. `rls-events-update-scope-recheck` — LOW (fixed) +**Event UPDATE can retarget to other sections.** +- **Root cause:** `school_events_teacher_insert` requires `teaches_section` per section, but + `school_events_owner_update` (`0002:390`) only checks `created_by`/admin. +- **Fix (0004):** UPDATE WITH CHECK re-verifies `teaches_section` for every `section_id` (admin bypass). + +## 7. `rls-course-goals-update-scope-recheck` — LOW (fixed) +**Course-goal UPDATE skips the teaching re-check.** +- **Root cause:** `course_goals_teacher_update` (`0002:338`) checks only `teacher_id`; INSERT requires + `teaches_student`. A teacher could keep editing after losing the teaching relationship. +- **Fix (0004):** UPDATE USING/WITH CHECK add `teaches_student(student_id)`. + +## 8. `edge-create-admin-loginid-sanitization` — LOW (fixed) +**create-admin builds the auth email from an unsanitized login id.** +- **Root cause:** `create-admin` used `` `${loginId.toLowerCase()}@${ADMIN_DOMAIN}` `` while + `authEmail()` (students) and client `toAuthEmail()` sanitize the local part. A special-character login + id yields a malformed/inconsistent auth email vs. the sign-in lookup. Admin-only robustness issue. +- **Fix:** `email: authEmail(loginId)` (both domains are `pws.local`, so this matches `toAuthEmail` + exactly); removed the now-unused `ADMIN_DOMAIN`. + +--- + +## Regression coverage added +`supabase/tests/verify_rls_local.py` now applies **0004** and asserts: +- **Negative:** student cannot raise own role / flip is_active / rewrite login_id; student cannot forge + audit_log; unrelated teacher cannot mark foreign attendance / author a foreign report card. +- **Positive:** student can update own full_name; teacher can mark own-student attendance and author an + own-student report card. diff --git a/docs/audits/2026-11-05-security-audit-validation.md b/docs/audits/2026-11-05-security-audit-validation.md new file mode 100644 index 0000000..df52785 --- /dev/null +++ b/docs/audits/2026-11-05-security-audit-validation.md @@ -0,0 +1,63 @@ +# Needs Validation — schoolerp run-1 + +The findings in `findings.json` are all `confirmed` by **complete, deterministic source traces**. +What could **not** be done in this sandbox is **live Postgres execution** of the RLS policies. This +file records that boundary and gives the owner an exact replay plan. It does not downgrade the +findings: the policy text, the project's documented `authenticated` grants, and the absence of any +protecting trigger/column grant together make each result conclusive. + +## Why live DB execution was not performed +- No local Postgres was available (`postgres`, `pg_ctl`, `initdb`, `psql` absent; `pgserver` not + installed; no `.venv`). +- The skill's execution boundary forbids installing dependencies ("use only tools and dependencies + already available locally"), so `pip install pgserver` / `apt-get postgres` were **not** run. +- No live/deployed Supabase project was probed (the skill prohibits touching deployed targets). + +## Owner replay plan (local, dummy data only) +The repo already ships a local verifier; it now applies migration **0004** and includes new +regression assertions for every fix. + +```bash +# one-time: create a venv and install the throwaway-Postgres helper +python3 -m venv .venv +.venv/bin/pip install pgserver + +# run the RLS matrix through the `authenticated` role (boots a throwaway Postgres) +npm run verify:rls +# equivalently: .venv/bin/python supabase/tests/verify_rls_local.py +``` + +Expected: `RESULT: ALL PASS`, including the new rows: +- `student escalates own role to admin` → DENIED +- `student flips own is_active` → DENIED +- `student rewrites own login_id` → DENIED +- `student forges an audit_log entry` → DENIED +- `unrelated teacher marks foreign attendance` → DENIED / NO-ROWS +- `unrelated teacher authors foreign report card` → DENIED +- `student updates own full_name` → ALLOWED +- `teacher marks own-student attendance` → ALLOWED +- `teacher authors own-student report card` → ALLOWED + +The canonical pgTAP suite (`supabase test db`, `supabase/tests/rls_matrix.sql`) also benefits: its +"student_a cannot read student_b profile" assertion, previously violated by `profiles_read_active`, +now passes with 0004. + +## Staging / deployment checks (owner, on a non-production Supabase project) +1. Apply migrations 0001→0004 to a **staging** project. +2. As a seeded **student**, call `PATCH /rest/v1/profiles?id=eq.` with `{"role":"admin"}` and + confirm it is rejected (column grant → `permission denied for table profiles`). +3. As a seeded **teacher**, attempt to insert attendance / a report card for a student outside their + teaching assignments and confirm rejection. +4. As any user, `GET /rest/v1/profiles?select=login_id,role` and confirm only self (plus, for teachers, + their students) is returned. +5. Confirm the `admin-users` Edge Function still provisions admins/students (service_role bypasses RLS) + and that a created admin can sign in with a special-character login id (F8 normalization). + +## Notes / design decisions to confirm +- **Directory reads:** 0004 removes the blanket active-profile read. If students must see teacher or + classmate names in live mode, add an explicit minimal directory policy (do not restore the blanket). +- **Class-teacher attendance:** attendance scope uses `teaches_student` (subject teachers). If class + teachers must mark attendance, extend read **and** write with `is_class_teacher_of`. +- **Verifier grants:** `verify_rls_local.py` re-grants blanket UPDATE after migrations (mirroring + Supabase defaults), so in the *local verifier* the **trigger** is the active protection for F1; in a + real project the **column grant** is. Both are asserted. diff --git a/docs/audits/2026-11-05-security-audit.md b/docs/audits/2026-11-05-security-audit.md new file mode 100644 index 0000000..91488cb --- /dev/null +++ b/docs/audits/2026-11-05-security-audit.md @@ -0,0 +1,66 @@ +# Security Audit Report — Pacific World School ERP + +- **Target:** `sahajiscoding/schoolerp` @ `828e6ec` (branch `arena/284700ba-schoolerp`, incl. uncommitted functional fixes) +- **Date:** 2026-11-05 · **Mode:** full audit (Cloudflare `security-audit` skill, six phases) +- **Scope:** `apps/admin`, `packages/shared`, `supabase` (schema/RLS + Edge Function), `scripts`, `.github/workflows`, `vercel.json`. `apps/mobile` is an unimplemented stub → out of scope. +- **Validators:** `validate-findings.cjs` → **PASS (8 findings)** · `validate-coverage-ledger.cjs` → **PASS (15 units)**. + +## Executive summary +The live authorization boundary is **Supabase Row-Level Security** (the admin console runs on a +single-principal `localStorage` demo store unless Supabase env is present; demo-only gaps are +self-impact and are not security findings). The audit found **one critical privilege-escalation +flaw and several teacher-scoping / integrity gaps in the RLS layer**, plus a minor Edge Function +normalization inconsistency. **All 8 confirmed findings have been fixed** in this branch +(`supabase/migrations/0004_profiles_hardening.sql`, an Edge Function change, and new regression +assertions). The client, deploy headers, secret handling, and CI/supply-chain were reviewed and +found sound. + +## Findings (all confirmed, all fixed) +| # | Fingerprint | Severity | Title | Fix | +|---|-------------|----------|-------|-----| +| 1 | `rls-profiles-self-escalation` | **Critical** | Any signed-in user can escalate themselves to admin via `profiles_self` | 0004: column grants + `protect_profile_privileges` trigger + narrowed self policy | +| 2 | `rls-audit-log-insert-forgery` | Medium | Any authenticated user can forge `audit_log` entries | 0004: drop open INSERT; admin-only insert | +| 3 | `rls-attendance-cross-section-write` | Medium | Teacher can mark attendance for students they don't teach | 0004: `teaches_student(student_id)` in write policy | +| 4 | `rls-report-cards-cross-section-insert` | Medium | Teacher can fabricate report cards for any student | 0004: `teaches_student(student_id)` in insert/update | +| 5 | `rls-profiles-directory-overbroad-read` | Medium | Any user can read every active profile (login ids, roles) | 0004: scoped reads (self / teaches_student / admin) | +| 6 | `rls-events-update-scope-recheck` | Low | Event UPDATE can retarget to other sections | 0004: re-check `teaches_section` on UPDATE | +| 7 | `rls-course-goals-update-scope-recheck` | Low | Course-goal UPDATE skips teaching re-check | 0004: re-check `teaches_student` on UPDATE | +| 8 | `edge-create-admin-loginid-sanitization` | Low | create-admin builds auth email from unsanitized login id | Edge Function now uses `authEmail(loginId)` | + +The critical finding is a **full administrative takeover**: because `profiles_self` was +`FOR ALL USING (auth.uid() = id)` with no column guard, and `authenticated` holds `UPDATE`, any +student could `PATCH profiles SET role='admin'` on their own row and pass every `is_admin()` gate +(all data, user provisioning, fees). See FINDINGS-DETAIL.md for traces and reproduction. + +## Reviewed and cleared (no finding) +- **Client XSS:** `printHtml` and every caller (`ReportCard`, `StudyRoom`) escape all interpolations; no `dangerouslySetInnerHTML`/unsanitized `innerHTML`. +- **Demo auth gating:** `signInAsDemo` refuses whenever a Supabase client exists; live identity comes only from `supabase.auth`. +- **Secret handling:** client/shared use publishable/anon keys only; `vite.config.ts` inlines only URL + publishable key; CI greps block secret-like public vars; `create-admin.mjs` reads the service key from env and prompts for the password. +- **Edge Function authorization:** caller JWT verified + `role='admin' && is_active` re-check; service key stays in function env; 200-row import cap; rollback; audit writes. +- **Deploy headers:** restrictive CSP (`script-src 'self'`, `object-src 'none'`, `frame-ancestors 'none'`), X-Frame-Options DENY, nosniff, HSTS, Referrer-Policy, Permissions-Policy. +- **RLS helpers:** all `SECURITY DEFINER` with `search_path=''`; 0003 narrows EXECUTE to `authenticated`; both views `security_invoker=true`. +- **Other RLS:** messaging/threads/submissions/fees/leaves/declarations are principal/section-scoped; `poll_votes` has `PRIMARY KEY(poll_id, student_id)` (no double-vote). +- **Supply chain:** CI `permissions: contents:read`, actions pinned to full SHAs; dependencies are current majors. + +## Validation method & limitations (disclosed) +- **Single-agent adaptation:** no Task/sub-agent tool is available here, so reconnaissance, hunting, + and validation were performed sequentially by one agent. Independence is therefore weaker than a + multi-agent run; this is disclosed rather than hidden. +- **RLS confirmed by complete source traces, not live DB execution.** No local Postgres was available + and the skill forbids installing dependencies, so each RLS finding is grounded in the exact policy + text + the project's documented `authenticated` grants + the absence of any protecting trigger/column + grant, cross-checked against the project's own `rls_matrix.sql`. Empirical replay is handed to the + owner in NEEDS-VALIDATION.md (`npm run verify:rls` now applies 0004 and asserts the new rules). +- Both zero-dependency Node validators were run and pass. + +## Residual recommendations (not findings) +- **Directory design:** 0004 narrows profile reads to the isolation spec. If the product later needs + students to see teacher/classmate names, add an explicit, minimal directory policy rather than + restoring the blanket read. +- **Class-teacher attendance:** attendance read/write scope uses `teaches_student` (subject teachers). + If class teachers must mark attendance, extend both read and write with `is_class_teacher_of`. +- **Privileged writes stay server-side:** role/is_active/login_id changes must go through the + service-role Edge Function (the column grants now enforce this). +- **GitGuardian:** historical commits still contain the old password literals; purge/rotate via the + GitGuardian dashboard (code is already clean). +- **Dev-only:** `vite allowedHosts:true` is a dev/preview convenience, not deployed; acceptable. diff --git a/docs/superpowers/specs/2026-11-03-school-erp-design.md b/docs/superpowers/specs/2026-11-03-school-erp-design.md index aba2cba..6635af9 100644 --- a/docs/superpowers/specs/2026-11-03-school-erp-design.md +++ b/docs/superpowers/specs/2026-11-03-school-erp-design.md @@ -335,3 +335,4 @@ No calendar estimates. A status document that lies is worse than none. | 2026-11-04 | Admin console reads `SUPABASE_URL` / `SUPABASE_PUBLISHABLE_KEY` (Vercel names) with `VITE_` aliases | Owner already has these names in Vercel; renaming would force an env migration for no security gain | | 2026-11-04 | `current_role()` helper renamed to `app_role()` | `current_role` is a reserved SQL keyword; the original statement could never have applied | | 2026-11-04 | Demo mode (seeded data, no Supabase keys) is a first-class state of the admin console | Lets the owner review every screen before the backend is wired; shows a banner and never writes to a database | +| 2026-11-05 | Passwordless demo entry (Admin / Teacher / Student picker on the login page) replaces demo credentials | Owner needs a one-click showcase for school leadership; hardcoded demo passwords tripped GitGuardian. Demo entry stays disabled whenever Supabase is configured, so identity against a live backend always comes from Supabase Auth | From 6a986f6533b52f18b8454487d1895e7e307f3578 Mon Sep 17 00:00:00 2001 From: sahajiscoding <135018977+sahajiscoding@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:54:17 +0000 Subject: [PATCH 3/5] docs: record GitGuardian history purge (filter-repo + force-push main) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- PROJECT_STATUS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PROJECT_STATUS.md b/PROJECT_STATUS.md index 6e8e1f9..5a276b0 100644 --- a/PROJECT_STATUS.md +++ b/PROJECT_STATUS.md @@ -65,7 +65,7 @@ This file is the single source of truth for project state. Every agent must read - 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. -- All hardcoded demo passwords removed (GitGuardian): `DEMO_LOGINS` in `AuthContext.tsx`, the split-string credential hint in `Login.tsx`, the `'REDACTED'` fallback in `appData.tsx` (no DOB → no initial password shown), the literal sibling password in `seed.ts` (now derived via `passwordFromDob`), and the example password in `scripts/create-admin.mjs` (password is prompted interactively). The `__DEMO_MODE__` compile flag is gone — there is nothing left to strip. +- All hardcoded demo passwords removed (GitGuardian): `DEMO_LOGINS` in `AuthContext.tsx`, the split-string credential hint in `Login.tsx`, the hardcoded fallback password in `appData.tsx` (no DOB → no initial password shown), the literal sibling password in `seed.ts` (now derived via `passwordFromDob`), and the example password in `scripts/create-admin.mjs` (password is prompted interactively). The `__DEMO_MODE__` compile flag is gone — there is nothing left to strip. **2026-11-05: the git history was also purged** — `git filter-repo` replaced the demo-password literals across all commits and `main` was force-pushed, so they no longer appear in any reachable commit (GitGuardian may need a re-scan / GitHub GC of dangling objects to fully clear old incidents). - Fixed a display bug in `People.tsx`: the import help rendered `Student@Student@14052010` (double prefix); it now shows the derived value once. - 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. From 3bf2dbcbd470e4ee479cb8d00f5f49fe3a04afab Mon Sep 17 00:00:00 2001 From: sahajiscoding <135018977+sahajiscoding@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:05:42 +0000 Subject: [PATCH 4/5] ci: remove redundant vendor scanners (Black Duck, Synopsys, Checkmarx, CodeScan) These five workflows (Black Duck, Synopsys, CxFlow, Checkmarx One, CodeScan) only ever failed on missing vendor credentials, never on a real finding. Remove them to stop the perpetually-red checks. Endor Labs and Debricked remain (still need vendor credentials); CodeQL stays the always-on baseline. Update docs/security/scanning.md and PROJECT_STATUS.md accordingly. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .../workflows/black-duck-security-scan-ci.yml | 57 ------------------- .github/workflows/checkmarx-one.yml | 55 ------------------ .github/workflows/checkmarx.yml | 55 ------------------ .github/workflows/codescan.yml | 49 ---------------- .github/workflows/synopsys-action.yml | 44 -------------- PROJECT_STATUS.md | 9 +-- docs/security/scanning.md | 30 +++++----- 7 files changed, 20 insertions(+), 279 deletions(-) delete mode 100644 .github/workflows/black-duck-security-scan-ci.yml delete mode 100644 .github/workflows/checkmarx-one.yml delete mode 100644 .github/workflows/checkmarx.yml delete mode 100644 .github/workflows/codescan.yml delete mode 100644 .github/workflows/synopsys-action.yml diff --git a/.github/workflows/black-duck-security-scan-ci.yml b/.github/workflows/black-duck-security-scan-ci.yml deleted file mode 100644 index cf2dba4..0000000 --- a/.github/workflows/black-duck-security-scan-ci.yml +++ /dev/null @@ -1,57 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -# Black Duck Security Action allows you to integrate Static Analysis Security Testing (SAST) and Software Composition Analysis (SCA) into your CI/CD pipelines. -# For more information about configuring your workflow, -# read our documentation at https://github.com/blackduck-inc/black-duck-security-scan - -name: CI Black Duck security scan - -on: - push: - branches: [ "main" ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ "main" ] - schedule: - - cron: '43 7 * * 6' - -permissions: - contents: read - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: write - security-events: write - actions: read - - steps: - - name: Checkout source - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - name: Black Duck SCA scan - uses: blackduck-inc/black-duck-security-scan@805cbd09e806b01907bbea0f990723c2bb85abe9 - with: - ### ---------- BLACKDUCK SCA SCANNING: REQUIRED FIELDS ---------- - blackducksca_url: ${{ vars.BLACKDUCKSCA_URL }} - blackducksca_token: ${{ secrets.BLACKDUCKSCA_TOKEN }} - - ### ---------- COVERITY SCANNING: REQUIRED FIELDS ---------- - coverity_url: ${{ vars.COVERITY_URL }} - coverity_user: ${{ secrets.COVERITY_USER }} - coverity_passphrase: ${{ secrets.COVERITY_PASSPHRASE }} - - ### ---------- POLARIS SCANNING: REQUIRED FIELDS ---------- - polaris_server_url: ${{ vars.POLARIS_SERVER_URL }} - polaris_access_token: ${{ secrets.POLARIS_ACCESS_TOKEN }} - polaris_assessment_types: "SCA,SAST" - - ### ---------- SRM SCANNING: REQUIRED FIELDS ---------- - srm_url: ${{ vars.SRM_URL }} - srm_apikey: ${{ secrets.SRM_API_KEY }} - srm_assessment_types: "SCA,SAST" - diff --git a/.github/workflows/checkmarx-one.yml b/.github/workflows/checkmarx-one.yml deleted file mode 100644 index bcf8168..0000000 --- a/.github/workflows/checkmarx-one.yml +++ /dev/null @@ -1,55 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -# The Checkmarx One GitHub Action enables you to trigger SAST, SCA, and KICS scans directly from the GitHub workflow. -# It provides a wrapper around the Checkmarx One CLI Tool which creates a zip archive from your source code repository -# and uploads it to Checkmarx One for scanning. The Github Action provides easy integration with GitHub while enabling -# scan customization using the full functionality and flexibility of the CLI tool. - -# This is a basic workflow to help you get started with Using Checkmarx One Action, -# documentation can be found here : https://checkmarx.com/resource/documents/en/34965-68702-checkmarx-one-github-actions.html - -name: Checkmarx Scan - -# Controls when the workflow will run -on: - pull_request: - types: [opened, reopened, synchronize] - branches: [ "main" ] - -permissions: - contents: read - -# A workflow run is made up of one or more jobs that can run sequentially or in parallel -jobs: - # This workflow contains a single job called "build" - build: - permissions: - contents: read # for actions/checkout to fetch code - security-events: write # for github/codeql-action/upload-sarif to upload SARIF results - actions: read # only required for a private repository by github/codeql-action/upload-sarif - - # The type of runner that the job will run on - runs-on: ubuntu-latest - - # Steps represent a sequence of tasks that will be executed as part of the job - steps: - # This step checks out a copy of your repository. - - name: Checkout repository - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - # This step creates the Checkmarx One scan - - name: Checkmarx One scan - uses: checkmarx/ast-github-action@58c998c5d78b3ecfa51e7cbde852d5565d5dea0b - with: - base_uri: https://ast.checkmarx.net # This should be replaced by your base uri for Checkmarx One - cx_client_id: ${{ secrets.CX_CLIENT_ID }} # This should be created within your Checkmarx One account : https://checkmarx.com/resource/documents/en/34965-118315-authentication-for-checkmarx-one-cli.html#UUID-a4e31a96-1f36-6293-e95a-97b4b9189060_UUID-4123a2ff-32d0-2287-8dd2-3c36947f675e - cx_client_secret: ${{ secrets.CX_CLIENT_SECRET }} # This should be created within your Checkmarx One account : https://checkmarx.com/resource/documents/en/34965-118315-authentication-for-checkmarx-one-cli.html#UUID-a4e31a96-1f36-6293-e95a-97b4b9189060_UUID-4123a2ff-32d0-2287-8dd2-3c36947f675e - cx_tenant: ${{ secrets.CX_TENANT }} # This should be replaced by your tenant for Checkmarx One - additional_params: --report-format sarif --output-path . - - name: Upload SARIF file - uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 - with: - # Path to SARIF file relative to the root of the repository - sarif_file: cx_result.sarif diff --git a/.github/workflows/checkmarx.yml b/.github/workflows/checkmarx.yml deleted file mode 100644 index d860013..0000000 --- a/.github/workflows/checkmarx.yml +++ /dev/null @@ -1,55 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -# This is a basic workflow to help you get started with Using Checkmarx CxFlow Action - -name: CxFlow - -on: - push: - branches: [ "main" ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ "main" ] - schedule: - - cron: '33 14 * * 0' - -# A workflow run is made up of one or more jobs that can run sequentially or in parallel - this job is specifically configured to use the Checkmarx CxFlow Action -permissions: - contents: read - -jobs: - # This workflow contains a single job called "build" - build: - # The type of runner that the job will run on - Ubuntu is required as Docker is leveraged for the action - permissions: - contents: read # for actions/checkout to fetch code - issues: write # for checkmarx-ts/checkmarx-cxflow-github-action to write feedback to github issues - pull-requests: write # for checkmarx-ts/checkmarx-cxflow-github-action to write feedback to PR - security-events: write # for github/codeql-action/upload-sarif to upload SARIF results - actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status - runs-on: ubuntu-latest - - # Steps require - checkout code, run CxFlow Action, Upload SARIF report (optional) - steps: - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - # Runs the Checkmarx Scan leveraging the latest version of CxFlow - REFER to Action README for list of inputs - - name: Checkmarx CxFlow Action - uses: checkmarx-ts/checkmarx-cxflow-github-action@49d8269b14ca87910ba003d47a31fa0c7a11f2fe - with: - project: ${{ secrets.CHECKMARX_PROJECT }} - team: ${{ secrets.CHECKMARX_TEAMS }} - checkmarx_url: ${{ secrets.CHECKMARX_URL }} - checkmarx_username: ${{ secrets.CHECKMARX_USERNAME }} - checkmarx_password: ${{ secrets.CHECKMARX_PASSWORD }} - checkmarx_client_secret: ${{ secrets.CHECKMARX_CLIENT_SECRET }} - scanners: sast - params: --namespace=${{ github.repository_owner }} --repo-name=${{ github.event.repository.name }} --branch=${{ github.ref }} --cx-flow.filter-severity --cx-flow.filter-category --checkmarx.disable-clubbing=true --repo-url=${{ github.event.repository.url }} - # Upload the Report for CodeQL/Security Alerts - - name: Upload SARIF file - uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 - with: - sarif_file: cx.sarif diff --git a/.github/workflows/codescan.yml b/.github/workflows/codescan.yml deleted file mode 100644 index d55bd0a..0000000 --- a/.github/workflows/codescan.yml +++ /dev/null @@ -1,49 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -# This workflow requires that you have an existing account with codescan.io -# For more information about configuring your workflow, -# read our documentation at https://github.com/codescan-io/codescan-scanner-action -name: CodeScan - -on: - push: - branches: [ "main" ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ "main" ] - schedule: - - cron: '41 6 * * 0' - -permissions: - contents: read - -jobs: - CodeScan: - permissions: - contents: read # for actions/checkout to fetch code - security-events: write # for github/codeql-action/upload-sarif to upload SARIF results - actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - name: Cache files - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 - with: - path: | - ~/.sonar - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - - name: Run Analysis - uses: codescan-io/codescan-scanner-action@5b2e8c5683ef6a5adc8fa3b7950bb07debccce12 - with: - login: ${{ secrets.CODESCAN_AUTH_TOKEN }} - organization: ${{ secrets.CODESCAN_ORGANIZATION_KEY }} - projectKey: ${{ secrets.CODESCAN_PROJECT_KEY }} - - name: Upload SARIF file - uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 - with: - sarif_file: codescan.sarif diff --git a/.github/workflows/synopsys-action.yml b/.github/workflows/synopsys-action.yml deleted file mode 100644 index 95e6ea2..0000000 --- a/.github/workflows/synopsys-action.yml +++ /dev/null @@ -1,44 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. -name: Synopsys Security Testing - -on: - push: - # At this time, it is recommended to run Polaris only on pushes to main branches - # Pull request analysis will be supported by Polaris in the future - branches: [ "main" ] - - pull_request: - branches: [ "main" ] - -permissions: - contents: read - -jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - name: Checkout - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - name: Synopsys Action - uses: synopsys-sig/synopsys-action@45ec794c72a1dff9baba58ff356386bbbfeb32c7 - with: - #------------------------------------------COVERITY----------------------------------------- - coverity_url: ${{ secrets.COVERITY_URL }} - coverity_user: ${{ secrets.COVERITY_USER }} - coverity_passphrase: ${{ secrets.COVERITY_PASSPHRASE }} - - #------------------------------------------BLACKDUCK---------------------------------------- - blackduck_token: ${{ secrets.BLACKDUCK_API_TOKEN }} - blackduck_url: ${{ secrets.BLACKDUCK_URL }} - - #------------------------------------------POLARIS------------------------------------------ - polaris_server_url: ${{ secrets.POLARIS_SERVER_URL }} - polaris_access_token: ${{ secrets.POLARIS_ACCESS_TOKEN }} - polaris_assessment_types: "SCA,SAST" - - diff --git a/PROJECT_STATUS.md b/PROJECT_STATUS.md index 5a276b0..018d1c5 100644 --- a/PROJECT_STATUS.md +++ b/PROJECT_STATUS.md @@ -107,10 +107,11 @@ This file is the single source of truth for project state. Every agent must read longer 404s. Verified against the real build output. - CI runs on Node 22 with `npm ci`; typecheck, lint (0 errors) and the admin build all pass. First-party actions moved off deprecated Node 20 runtimes. -- Third-party scanner workflows (Black Duck, Synopsys, CxFlow, Checkmarx One, - CodeScan, Endor Labs, Debricked) fail on **missing vendor credentials**, not - findings. See `docs/security/scanning.md` for the required secret per workflow - and the option of keeping only CodeQL. +- The redundant vendor scanners (**Black Duck, Synopsys, CxFlow, Checkmarx One, + CodeScan**) were **removed on 2026-11-05** — they only ever failed on missing + vendor credentials, not findings. Endor Labs and Debricked remain and still + need vendor credentials to run. See `docs/security/scanning.md`; CodeQL stays + the always-on baseline. ### Supabase project diff --git a/docs/security/scanning.md b/docs/security/scanning.md index f19a688..8f766e4 100644 --- a/docs/security/scanning.md +++ b/docs/security/scanning.md @@ -1,10 +1,14 @@ # Security scanning — what runs, what it needs, what it costs -This repository has nine third-party scanning workflows on top of GitHub's own -code scanning. They are **not** all runnable: most are vendor SaaS products that +This repository has four third-party scanning workflows on top of GitHub's own +code scanning. They are **not** all runnable: some are vendor SaaS products that need a paid account whose credentials this repository does not have. This file records which is which so a red check is never mistaken for a code defect. +> **2026-11-05:** the redundant vendor scanners — Black Duck, Synopsys, CxFlow, +> Checkmarx One and CodeScan — were **removed**. They only ever failed on missing +> vendor credentials, never on a real finding. Endor Labs and Debricked remain. + ## Runnable today (no vendor account) | Workflow | File | What it does | @@ -26,11 +30,6 @@ is added in **Settings → Secrets and variables → Actions**. | Workflow | Required secret(s) | Vendor | |---|---|---| -| Black Duck | `BLACKDUCKSCA_TOKEN` (+ `vars.BLACKDUCKSCA_URL`) or Coverity/Polaris/SRM equivalents | Black Duck / Synopsys | -| Synopsys | `COVERITY_URL`, `COVERITY_USER`, `COVERITY_PASSPHRASE`, `BLACKDUCK_*`, `POLARIS_*` | Synopsys | -| CxFlow (Checkmarx) | `CHECKMARX_URL`, `CHECKMARX_USERNAME`, `CHECKMARX_PASSWORD`, `CHECKMARX_CLIENT_SECRET`, `CHECKMARX_PROJECT`, `CHECKMARX_TEAMS` | Checkmarx | -| Checkmarx One | `CX_CLIENT_ID`, `CX_CLIENT_SECRET`, `CX_TENANT` | Checkmarx | -| CodeScan | `CODESCAN_AUTH_TOKEN`, `CODESCAN_ORGANIZATION_KEY`, `CODESCAN_PROJECT_KEY` | CodeScan (SonarQube-based) | | Endor Labs | `ENDOR_API_CREDENTIALS_KEY`, `ENDOR_API_CREDENTIALS_SECRET` **and** the `namespace` input must be set to the real tenant instead of the template default `example` | Endor Labs | | Debricked | `DEBRICKED_TOKEN` | Debricked (OpenText) | @@ -38,20 +37,21 @@ The Endor Labs workflow additionally ships with `namespace: "example"`, a placeholder from the vendor template. Even with credentials it cannot work until that is replaced with the real tenant namespace. -### Choose one, don't run all seven +### Choose one, don't run them all -Seven overlapping SCA/SAST products scanning the same ~4 kloc is redundant and -mostly a way to keep seven checks red. Pick the one the school's security budget -covers, delete the rest, and keep CodeQL as the always-on baseline: +Overlapping SCA/SAST products scanning the same ~4 kloc is redundant and mostly +a way to keep checks red. On **2026-11-05** five were removed (Black Duck, +Synopsys, CxFlow, Checkmarx One, CodeScan). Endor Labs and Debricked remain — +pick whichever the school's security budget covers, delete the other, and keep +CodeQL as the always-on baseline: ```bash -# Example: keep CodeQL only. -git rm .github/workflows/{black-duck-security-scan-ci,synopsys-action,checkmarx,checkmarx-one,codescan,endorlabs,debricked}.yml +# Example: keep CodeQL only (removes the two remaining vendor scanners). +git rm .github/workflows/{endorlabs,debricked}.yml ``` Deleting a workflow does not delete historical alerts, but it does stop the -failing checks. This is a decision for the repository owner, not something an -agent should do unilaterally. +failing checks. ## Dependency advisories From a149bbcf3120353369bdc6880f2de35a116e1aa5 Mon Sep 17 00:00:00 2001 From: sahajiscoding <135018977+sahajiscoding@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:20:18 +0000 Subject: [PATCH 5/5] ci: remove remaining vendor scanners (Debricked, Endor Labs) Completes the cleanup of the seven paid vendor scanners that only ever failed on missing credentials. Remaining checks: CI, CodeQL (baseline), free Codacy and OSSAR. Update docs/security/scanning.md and PROJECT_STATUS.md. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .github/workflows/debricked.yml | 43 -------------------------- .github/workflows/endorlabs.yml | 54 -------------------------------- PROJECT_STATUS.md | 9 +++--- docs/security/scanning.md | 55 ++++++++++----------------------- 4 files changed, 21 insertions(+), 140 deletions(-) delete mode 100644 .github/workflows/debricked.yml delete mode 100644 .github/workflows/endorlabs.yml diff --git a/.github/workflows/debricked.yml b/.github/workflows/debricked.yml deleted file mode 100644 index 859d47e..0000000 --- a/.github/workflows/debricked.yml +++ /dev/null @@ -1,43 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -##################################################################################################################################################################### -# Use this workflow template as a basis for integrating Debricked into your GitHub workflows. # -# # -# If you need additional assistance with configuration feel free to contact us via chat or email at support@debricked.com # -# To learn more about Debricked or contact our team, visit https://debricked.com/ # -# # -# To run this workflow, complete the following set-up steps: # -# # -# 1. If you don’t have a Debricked account, create one by visiting https://debricked.com/app/en/register # -# 2. Generate your Debricked access token, by following the steps mentioned in https://portal.debricked.com/administration-47/how-do-i-generate-an-access-token-130 # -# 3. In GitHub, navigate to the repository # -# 4. Click on “Settings” (If you cannot see the “Settings” tab, select the dropdown menu, then click “Settings”) # -# 5. In the “Security” section click on “Secrets and variables”, then click “Actions” # -# 6. In the “Secrets” tab, click on “New repository secret” # -# 7. In the “Name” field, type the name of the secret # -# 8. In the “Secret” field, enter the value of the secret # -# 9. Click “Add secret” # -# 10. You should now be ready to use the workflow! # -##################################################################################################################################################################### - -name: Debricked Scan - -on: - push: - -permissions: - contents: read - -jobs: - vulnerabilities-scan: - name: Vulnerabilities scan - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - uses: debricked/actions@659ae7accc12313772fbfbd1b1fccec31772ce41 - env: - DEBRICKED_TOKEN: ${{ secrets.DEBRICKED_TOKEN }} diff --git a/.github/workflows/endorlabs.yml b/.github/workflows/endorlabs.yml deleted file mode 100644 index 68caa19..0000000 --- a/.github/workflows/endorlabs.yml +++ /dev/null @@ -1,54 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: Endor Labs -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] - schedule: - - cron: '40 5 * * 5' -permissions: - contents: read - -jobs: - scan: - permissions: - security-events: write # Used to upload sarif artifact to GitHub - contents: read # Used to checkout a private repository by actions/checkout. - actions: read # Required for private repositories to upload sarif files. GitHub Advanced Security licenses are required. - id-token: write # Used for keyless authentication to Endor Labs - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - #### Package Build Instructions - ### Use this section to define the build steps used by your software package. - ### Endor Labs builds your software for you where possible but the required build tools must be made available. - # - name: Setup Java - # uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad - # with: - # distribution: 'microsoft' - # java-version: '17' - # - name: Build Package - # run: mvn clean install - - name: Endor Labs scan pull request - if: github.event_name == 'pull_request' - uses: endorlabs/github-action@b51bd06466b545f01a6ac788e3e1147695d3936c - with: - namespace: "example" # Modify the namespace to your Endor Labs tenant namespace. - sarif_file: findings.sarif - - name: Endor Labs scan monitor - if: github.event_name == 'push' - uses: endorlabs/github-action@b51bd06466b545f01a6ac788e3e1147695d3936c - with: - namespace: "example" # Modify the namespace to your Endor Labs tenant namespace. - ci_run: "false" - sarif_file: findings.sarif - - name: Upload SARIF to github - uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 - with: - sarif_file: findings.sarif diff --git a/PROJECT_STATUS.md b/PROJECT_STATUS.md index 018d1c5..61a975e 100644 --- a/PROJECT_STATUS.md +++ b/PROJECT_STATUS.md @@ -107,11 +107,10 @@ This file is the single source of truth for project state. Every agent must read longer 404s. Verified against the real build output. - CI runs on Node 22 with `npm ci`; typecheck, lint (0 errors) and the admin build all pass. First-party actions moved off deprecated Node 20 runtimes. -- The redundant vendor scanners (**Black Duck, Synopsys, CxFlow, Checkmarx One, - CodeScan**) were **removed on 2026-11-05** — they only ever failed on missing - vendor credentials, not findings. Endor Labs and Debricked remain and still - need vendor credentials to run. See `docs/security/scanning.md`; CodeQL stays - the always-on baseline. +- All seven paid vendor scanners (**Black Duck, Synopsys, CxFlow, Checkmarx One, + CodeScan, Endor Labs, Debricked**) were **removed on 2026-11-05** — they only + ever failed on missing vendor credentials, not findings. CodeQL stays the + always-on baseline, with free Codacy + OSSAR on top. See `docs/security/scanning.md`. ### Supabase project diff --git a/docs/security/scanning.md b/docs/security/scanning.md index 8f766e4..7ce992a 100644 --- a/docs/security/scanning.md +++ b/docs/security/scanning.md @@ -1,13 +1,14 @@ # Security scanning — what runs, what it needs, what it costs -This repository has four third-party scanning workflows on top of GitHub's own -code scanning. They are **not** all runnable: some are vendor SaaS products that -need a paid account whose credentials this repository does not have. This file -records which is which so a red check is never mistaken for a code defect. +This repository runs GitHub's own **CodeQL** plus two free scanners (**Codacy**, +**OSSAR**) on top of the CI gate. Every check that runs is runnable without a +paid vendor account, so a red check now means a real finding, not a missing +credential. -> **2026-11-05:** the redundant vendor scanners — Black Duck, Synopsys, CxFlow, -> Checkmarx One and CodeScan — were **removed**. They only ever failed on missing -> vendor credentials, never on a real finding. Endor Labs and Debricked remain. +> **2026-11-05:** all seven paid vendor scanners were **removed** — Black Duck, +> Synopsys, CxFlow, Checkmarx One, CodeScan, Endor Labs and Debricked. They only +> ever failed on missing vendor credentials, never on a real finding. CodeQL +> remains the always-on baseline. ## Runnable today (no vendor account) @@ -19,39 +20,17 @@ records which is which so a red check is never mistaken for a code defect. | CI (lint, typecheck, build) | `ci.yml` | Not a scanner, but the gate that matters most. | CodeQL is the workflow that feeds the **Security → Code scanning** tab for this -repository. Everything else that also uploads SARIF only adds findings *if* its -vendor account exists. +repository. Codacy and OSSAR also upload SARIF and add their findings on top. -## Cannot succeed without a vendor account +## Removed vendor scanners -These fail with an authentication/configuration error, not a finding. They stay -red on every push until the corresponding account is provisioned and the secret -is added in **Settings → Secrets and variables → Actions**. - -| Workflow | Required secret(s) | Vendor | -|---|---|---| -| Endor Labs | `ENDOR_API_CREDENTIALS_KEY`, `ENDOR_API_CREDENTIALS_SECRET` **and** the `namespace` input must be set to the real tenant instead of the template default `example` | Endor Labs | -| Debricked | `DEBRICKED_TOKEN` | Debricked (OpenText) | - -The Endor Labs workflow additionally ships with `namespace: "example"`, a -placeholder from the vendor template. Even with credentials it cannot work until -that is replaced with the real tenant namespace. - -### Choose one, don't run them all - -Overlapping SCA/SAST products scanning the same ~4 kloc is redundant and mostly -a way to keep checks red. On **2026-11-05** five were removed (Black Duck, -Synopsys, CxFlow, Checkmarx One, CodeScan). Endor Labs and Debricked remain — -pick whichever the school's security budget covers, delete the other, and keep -CodeQL as the always-on baseline: - -```bash -# Example: keep CodeQL only (removes the two remaining vendor scanners). -git rm .github/workflows/{endorlabs,debricked}.yml -``` - -Deleting a workflow does not delete historical alerts, but it does stop the -failing checks. +The seven paid vendor scanners — Black Duck, Synopsys, CxFlow, Checkmarx One, +CodeScan, Endor Labs and Debricked — were removed on **2026-11-05**. They +overlapped heavily on the same ~4 kloc and, lacking vendor credentials, only ever +produced red authentication-error checks, never a real finding. Deleting a +workflow does not delete historical alerts, but it stops the failing checks. If +the school later provisions a vendor account, re-add that one scanner +deliberately rather than restoring all seven. ## Dependency advisories