Spaces:
Running
Running
Commit History
2 days ago
-
feat(admin): in-dashboard back navigation + approval-gate owner switch + AI panel icon fixes
ahmdelbaz28-uxOwner report 2026-12-01, three asks, all root-cured: 1) BACK NAVIGATION (phone back exited the whole site): Root cause: admin tabs were pure React state — the URL never changed, so tab switches pushed NO history entries and the browser back button left /admin entirely (or closed the tab when it was the landing page). Fix: tabs are now URL-synced (/admin + /admin/:tabId route). Every tab switch is a real history entry; phone back walks back through visited tabs and out to the previous page; tabs are deep-linkable (/admin/users...). New one-tap back arrow in the mobile top bar uses history when the SPA has entries and lands on the dashboard otherwise. 2) APPROVAL-GATE OWNER SWITCH (new capability, default ON): The owner can now enable/disable the whole gate from the Users tab. ON (default — the 2026-11-24 contract): registrations land pending and wait for approval. OFF: registrations approve themselves (decidedAt stamped), already-pending accounts en…0d070f3
8 days ago
-
chore(biome): eliminate the organizeImports class repo-wide + close every remaining biome error
Z UserThe three organizeImports errors documented on the avatar feature (review- router, CourseReviews, ChatBot) were one instance of a repo-wide class: 17 assist/source/organizeImports diagnostics across 15 files, all on untouched import blocks. biome check --write applied the safe mechanical reorder (no side-effect-only imports moved — verified against the full diff; the 1391-test suite + tsc + build all pass unchanged). Also closed so `npx biome check .` now exits clean: - email-templates.ts useTemplate: concat → template literal - chatbot-cables-kb.ts noApproximativeNumericConstant ×2: biome-ignore with justification — ac 1.442 Ω/km is measured IEC cable data, NOT the log2(e) constant the rule suspects; auto-fix would have corrupted the table - admin-learning.ts usePlaywrightValidDescribeCallback ×3: biome-ignore — `describe` there is the local error formatter (line 238) for the DB canary diagnostics, not a test-runner describe18afd52 -
feat(profile): uploadable user avatar — photo replaces the initials box, name under it
Z UserOwner request (2026-11-26): the user dashboard's avatar box showed only the first letter of the name. It now renders the user's actual profile photo (with the name displayed UNDER the photo per the layout requirement) and the user can upload/replace/remove it themselves. Why storage lives in the DB: the HF Space disk is EPHEMERAL (rebuilt on every deploy) — an uploaded file would vanish at the next push. users.avatar (MEDIUMTEXT) persists in the external MySQL and already existed for Google OAuth picture URLs; self-uploads ride the same column as small data URLs. Server: - migration v20 (db-init.ts): users.avatar TEXT→MEDIUMTEXT, idempotent INFORMATION_SCHEMA probe (re-ALTERs only while still plain TEXT) - SafeUser + AuthMeOutput widened with avatar; explicit projection updated — auth.me + session.me now deliver it to the UI (30s SafeUser cache evicted on change via evictUserAuthCache) - auth.updateAvatar mutation (local-auth-router.ts): authed-only, writes ONLY…31baaf4 -
security(owner-directives): universal admin-approval enforcement + login-only chatbot + stale-shell cache cure
ahmdelbaz28-uxRoot causes fixed: 1) APPROVAL BYPASS (pre-gate accounts): the v17 column DEFAULT grandfathered every pre-gate account as 'approved' and the gate ran ONLY at login — a pre-gate user (or his surviving 30-day session) entered and used the platform with zero admin confirmation. Fixed at THREE layers: - approvalGateVerdict: fail-closed for everything not literally 'approved' - context.loadUserFromDb: per-request gate re-check (kills live sessions of non-approved accounts on their very next request) - db-init v18 one-time idempotent backfill: pre-gate rows -> pending + tokenVersion bump (queue-approved/rejected/admins untouched) - decideApproval(approve) stamps emailVerifiedAt: the admin approval IS the email confirmation — never asked twice (owner promise) 2) CHATBOT OPEN TO GUESTS: the REST surface was intentionally anonymous (UI already redirected guests). POST /, POST /stream and feedback votes now require a session — guests get the stable 401 A…b34ee20
12 days ago
-
security(audit-cfskill-run2): root-cure round — all 8 confirmed findings fixed + 12 regression pins
Z UserCloudflare security-audit-skill scoped run-2 (delta f34855f..90c0124 + carried prior-run records). 8 confirmed (2 HIGH, 4 MEDIUM, 2 LOW), 3 needs_validation; Phase-5 record-verified with non-material remediation corrections applied. 1. HIGH settings publicQuery partition: deny-by-default PUBLIC_SETTINGS_SECTIONS allowlist in getAll (row filter) + getSection (zod refine BEFORE the cache lookup) — adminRecovery.backupHash / youtubeSync / youtubeWatch never served anonymously again; db-init claim/restore/reset2fa branches now call invalidateSettingsCache() so cached values never straddle the partition. 2. HIGH identity-endpoint projection: SafeUser narrowed from Omit<User,'passwordHash'> to a curated Pick<> of the exact 7 UI/server fields (explicit construction in loadUserFromDb — no spread); shared AuthMeOutput zod schema applied via .output() on BOTH auth.me and session.me (runtime strip) — the plaintext TOTP seed, OTP/token hashes, deviceFingerprint and pend…75bceac
20 days ago
-
fix(auth): remember-this-device session persistence — kill false-401 logout chain
ahmdelbaz28-uxUser report: closing and reopening the app always demanded a fresh login even though 'Remember this device' was checked. Three chained root causes: 1. FALSE-401 ON DB HICCUP (api/context.ts): a transient MySQL failure inside the auth pipeline was swallowed by createContext's blanket catch, the request degraded to GUEST, requireAuth threw UNAUTHORIZED, and the client destroyed the stored session. One brief DB outage (HF Space wake-up, free-tier connection reset, cold-start race) = permanent logout. CURE: loadUserFromDbWithRetry — one quick DB retry, then the failure surfaces as a retryable INTERNAL_SERVER_ERROR (5xx) instead of a guest 401. createContext rethrows TRPCError instead of swallowing it. 2. GRACE WINDOW BROKE THE 30-DAY PROMISE (api/context.ts): expired-but- signature-valid tokens were renewed only within 24h of expiry, while the remember cookie lasts 30 days — any idle gap beyond ~8 days forced a re-login. CURE: EXPIRED_TOKEN_GRACE_S = AUTH_CO…c50c1a3
22 days ago
-
security(audit-run2): close all 8 wave-1 findings + pin every fix with tests
Z UserHunters (5 isolated agents) + coverage critic over 17 units. Fixes applied by parent decision (owner pre-authorization): - twofa second-factor takeover: setup-on-enabled + regenerateBackupCodes now require proof of the CURRENT factor (TOTP or atomic backup-code consume); backup consumption is a conditional UPDATE (JSON_CONTAINS predicate) in BOTH twofa-router and the login path — concurrent redemptions can no longer double-spend a code; timingSafeEqual on the TOTP compare - notification poll: cross-site GETs (SameSite=None cookie, GET exempt from the CSRF gate) serve empty WITHOUT touching the per-user throttle bucket — third-party noise can no longer starve the victim's notification delivery - /history raw provider tag echo: persistRoundSafe stores the OPAQUE key; getChatHistory heals legacy raw rows (toOpaqueWireModel); feedback votes accept only m_* keys (raw tags dropped at the schema layer) - distillation lane: the rolling-summary output now passes finalizeReply —…1adf47a -
security(audit-run1): 7 confirmed findings fixed + chatbot architecture fixes
Z UserSecurity audit run-1 (Cloudflare security-audit-skill, 6 phases, 34 coverage units, 13 independently verified findings) + agent-architecture-audit (12-layer chatbot stack). Shipped fixes: - native-client-detection-token-disclosure (medium): token-source binding — x-renewed-token only for header-sourced tokens; body JWT requires capacitor header AND no auth cookie - promo.leftmost-xff-quota-key (medium): trust-ordered client IP for all three promo throttles; validate probe keyed userId+resolved IP - promo.usage-cap.check-then-act-race (hardening): SELECT ... FOR UPDATE on promoCodes row serializes cap checks inside the payment transaction - ai-router SSRF guard: IPv4-mapped/translated IPv6 decoded to dotted quad before range checks; NAT64 + embedded-IPv4 rejected; redirect:'error' on all key-bearing provider fetches - push-subscription SSRF: push-service host allowlist (subscribe + send time), per-user subscription cap (10), legacy-row healing - ai-diagnostics egress: no …b9b9643
24 days ago
-
security(pre-launch-audit-run-2): close HIGH session-revocation hole + chatbot abuse & prompt-leak defenses
Z UserAUTH/SESSIONS: - sessions.revoke.broken-sql (HIGH): drizzle template ${"$"}{users.tokenVersion} emitted invalid MySQL — the tokenVersion bump 500'd and the revoked JWT stayed valid. Fixed to correct interpolation in revoke + revokeAll, with a source regression guard test (api/sessions-router.sql.test.ts). - auth-cache.revocation-window: evictUserAuthCache() called at EVERY revocation site (logout, password change, reset, revoke, revokeAll) — stolen JWT no longer survives 30s in the user cache. - login.per-account-throttle: username-keyed failure bucket (20/15min) before the DB lookup — distributed/IP-rotating stuffing no longer defeats the per-IP login limit. LOG HYGIENE: - Live password-reset / email-verification URLs (working tokens) never logged — hash prefix only. User emails masked via maskEmail() everywhere. CHATBOT (full audit, 10 areas): - daily-quota (HIGH): per-IP 60/day + per-user 200/day UTC buckets gate both /api/chatbot and /api/chatbot/stream before d…07f03e8 -
security+ux(pre-launch-audit): close CORS/CSRF null-origin hole, exact-origin gate, course pagination, reviews UI, RTL+a11y sweep
Launch Audit BotSECURITY (P0, regression-tested): - Remove opaque origin 'null' from CORS + CSRF allowlists (api/boot.ts, api/middleware/security.ts) — sandboxed <iframe sandbox> attacks that ride SameSite=None cookies are now rejected 403. Electron prod loads the live origin since the session-persistence fix; native shells use Bearer tokens. - CSRF same-origin gate: exact parsed-origin comparison replaces startsWith() prefix matching (sibling-domain bypass closed). - Session grace window 30d -> 24h (api/context.ts): stolen-token effective lifetime drops from ~37d to ~8d; tokenVersion revocation unchanged. - chatbot /stream: malformed JSON now 400 INVALID_JSON instead of unhandled 500. - NEW api/middleware/security.csrf.test.ts — 8 permanent regression tests (null origin, sibling domain, legit origins, S2S no-origin, referer exactness). UX (P1): - Courses catalog: real server-side pagination (?page=N) + debounced server-side search — courses 13+ are no longer unreachable; filter chips …b9995d9
-
fix(session): complete session-persistence suite + wallet E2E contract fixes
Z UserW1/W6 diagnosis & fixes (both were TEST-HARNESS artifacts, app code intact): - W1 root cause: the PWA service worker's NetworkOnly /api/trpc handler still processes requests INSIDE the worker, and SW-handled requests bypass Playwright page.route() (documented limitation) - they hit the raw static file server which answered 404 for API paths, so auth.me died after the SW took control and every restart bounced to /login. Cookie-consent banner was NOT the culprit (dismissed correctly). Production unaffected (SW forwards to the real API). Fix: the static server now relays /api/* to the mock via a real http.client hop preserving multi Set-Cookie; consent pre-seeded. - W6 root cause: desktop-only selectors on a mobile viewport - the navbar renders a hamburger drawer below md, not the aria-label=User menu dropdown. Fix: Toggle menu -> plain Sign Out button flow. - Logout renewal race: auth.me racing the logout invalidate() re-stored the renewed token after removeStoredToke…0e8a670
-
feat(chat): persistent history via the (previously unused) chatMessages table
Z UserFor logged-in users: - Save: every user+assistant round is persisted server-side (non-streaming and streaming paths). Streaming accumulates the normalized SSE text in the piper and persists on stream end (incl. client disconnect — partial save). Error replies are never persisted. - Restore: GET /api/chatbot/history returns the last 50 rounds; the client pulls it once per login on chat open — SERVER WINS over localStorage (localStorage stays as instant cache + guest fallback). Fails open. - Rolling summary: context older than ~1 day is folded into a summary row (role='summary', coverage-tracked via metadata.coveredUntilId, regenerated only after >=12 uncovered old rounds, capped 200 sources). Injected into the system prompt for continuity without bloating the recent window. - Clear: DELETE /api/chatbot/history wired to the chat clear button so cleared rounds don't resurrect on the next open. Auth: resolveOptionalUser(req) in api/context.ts shares the tRPC auth pipelin…c969b3a -
refactor: address SonarCloud findings on new code — extract renewExpiredTokenSession helper (context.ts cognitive complexity), replace nested ternaries in ChatBot with module-level copy helpers, de-duplicate literals in task22 e2e script
Z Userb16d9e8 -
fix(auth,chat,home): session survives token expiry via grace renewal + brain-mode toggle in chat header + real ETAP cover for category card + scroll reset on navigation
Z User- auth: expired-but-valid JWTs renew transparently in createContext (30d grace matching cookie maxAge) — returning users no longer get hard-logged-out on refresh; tokenVersion revocation still enforced; 7 new unit tests - chatbot: FAB clicks during authLoading are queued and auto-resolve instead of being misrouted to /login after the deadman timer - chatbot: Thinking/Instant moved to a compact brain toggle next to the bot title — removes the full-width mode row, freeing vertical chat space - home: ETAP Software category card shows a real (non-AI) ETAP application screenshot cover (public/etap-category.jpg, LFS) - app: ScrollReset — every path change scrolls to top (hash anchors honored); fixes pages opening at the footer after mid-page navigationf60b41d
-
security: apply Cloudflare security-audit-skill findings (run-1)
Z UserConfirmed fixes: - 2FA now enforced at login (TOTP + 8-hex backup codes; UI step-up field) - promo enforcement on payment.create: course scoping + per-user cap + usage recording + usedCount bump (transactional) - logout + revokeAll bump tokenVersion (server-side invalidation); tokenVersion check now unconditional - active-enrollment gate (status+expiresAt) on lessonVideo/markWatched/heartbeat/quiz/checkEnrollment/certificate + refund webhook revokes enrollment - certificate grade floor (<70% => no certificate for quiz courses) - quiz submit: documented 3-per-10-min per-lesson quota implemented - CSV export: OWASP formula-prefix neutralization in escapeCsv - email link hosts: exact allowlist (FRONTEND_URL/CORS_ORIGINS/HF_SPACE_HOST) replaces substring trust - client IP: rightmost XFF entry (append-safe) instead of client-controlled leftmost - Google OAuth: email_verified required before linking; state cookie consumed on error exits; sessions use current DB tokenVersion - chatbot: per-me…87ead2c
-
fix: resolve all lint warnings, update hero banner image
- Replace hero-main.svg with hero-main.jpg for home banner - Remove invalid inlineCSS option from vite.config.ts - Fix node:path import in vitest.config.ts - Fix unused vars in CourseDetail.tsx and Courses.tsx - Replace any types with proper types in cache/init.ts - Add eslint-disable comments for legitimate any/set-state-in-effect patterns - Suppress react-refresh warnings in UI component files - Fix exhaustive-deps warnings in hooks All checks pass: build, tests, eslint, tsc, biome2eb93af
-
fix(sonarcloud): batch 13 — clear 374 OPEN code smells
Z UserWave 1 (mechanical): - S6819: typeof x == 'y' → typeof x === 'y' (loose equality fix) - S6582: arr.indexOf(x) !== -1 → arr.includes(x) - S7773: isNaN → Number.isNaN, isFinite → Number.isFinite - S7769: Math.sqrt(a*a + b*b) → Math.hypot(a, b) - S7762: parent.removeChild(child) → child.remove() - S7764: window.X → globalThis.X (safe props only) - S7758: charCodeAt → codePointAt, fromCharCode → fromCodePoint - S6606: x = x ?? y → x ??= y - S7748: 1.0 → 1, 0.0 → 0 - S7723: new Array() / Array() → [] - S3863: merge duplicate imports from same module - S6353: [^a-zA-Z0-9_] → \W, [0-9] → \d - S7718: rename unused catch param to error_ Wave 2 (S3358 — 73 nested ternaries): - Refactored all nested ternaries into flat form using helper variables, if/else chains, or extracted consts. 22 files touched. Wave 3 (React rules): - S6759 (32): added readonly to all Props type properties - S6481 (5): wrapped Context provider values in useMemo - S6479 (5): replaced array index keys with stable identif…d3a69df
-
fix(sonarcloud): batch 5 — S7781 replaceAll, S1128 unused imports
ahmdelbaz28-uxS7781 (65 replace→replaceAll swaps across 15 files): - Add support for both string-literal and global-regex first args. - Applied to: vite.config, scripts/seed, api/{google-auth-router,twofa-router, course-router,export-router,boot,lib/jwt.test,lib/email,queries/connection}, infra/resend-integration/email, src/pages/{Admin,CourseDetail}, src/components/{ChatBot,NotificationCenter}. S1128 (unused imports, 9 removals): - api/promo-router.ts: drop `lt`. - infra/sre-observability/distributed-tracing/tracing-instrumentation.ts: drop `context`, `propagation`, `HonoRequest`. - infra/test-automation/page-objects/{DashboardPage,SupportPage}.ts: drop `expect` (and `Locator` from DashboardPage). - infra/test-automation/tests/setup/global-setup.ts: drop `expect`. - scripts/seed.ts: drop `sql` from drizzle-orm. Tests: 83/83 pass. tsc: 4 pre-existing framer-motion errors.0a5dfb2 -
fix(sonarcloud): batch 2 — S6582 optional chain, S1854 dead stores, S3735 void, shell scripts
ahmdelbaz28-uxS6582 (optional chain, 22 swaps across 15 files): - Replace `X && X.Y` with `X?.Y` in 22 sites. - Revert 4 sites where the optional chain would have broken TypeScript narrowing in subsequent accesses (api/context.ts cached.expiry, QuizComponent questions.length, Dashboard myEnrollments/myCertificates/ payments.length) — kept as `X && X.Y` with sonar:off comment + TS18048 justification. S1854 (dead stores, 12 removals): - api/lib/chatbot.ts: remove unused retryAfter. - api/chatbot-router.ts: remove unused decoder. - api/google-auth-router.ts: remove unused clientSecret + 6x userName/ userEmail/userAvatar (only userId/username/userRole are consumed by createToken()). - src/pages/Login.tsx, Register.tsx: declare `let errorMsg: string` without initialiser (the if/else-if/else always assigns). - infra/resend-integration/email.ts: remove unused verificationExpiry. - infra/test-automation/tests/setup/global-setup.ts: drop unused response body. - scripts/seed.ts: remove unused…2d21a3e
-
feat(images): replace hero banner + generate professional course thumbnails
ahmdelbaz28-uxHERO BANNER: - Replaced hero-main.webp with professional ETAP software screenshot COURSE THUMBNAILS (all AI-generated, 1344x768, professional quality): - course-cable.jpg: high-voltage power transmission lines at golden hour - course-etap.jpg: ETAP software interface with one-line diagram - course-skm.jpg: short circuit analysis with relay coordination curves - course-powerfactory.jpg: power flow analysis with voltage profile graphs - course-pvsyst.jpg: large-scale photovoltaic solar farm, 3D isometric - course-panel.jpg: electrical control panel with breakers and wiring All images are LFS-tracked with properly cached objects.2aed803 -
✅ ETAP Expert integration + security hardening + health check enhancement
- Integrated ETAP Expert skill into chatbot system prompt (Arabic + English) - 6-Step Mandatory Workflow, 20 Critical Rules, 4 Response Templates - Internal simulation requirements, common mistakes detection - Full ETAP module directory reference - Added structured JSON logger (api/lib/logger.ts) - Added rate limiting to Google auth endpoint - Replaced all production console.log with structured logging - Enhanced health check (fixed R2 auth, Redis detection, AI provider check) - Fixed rate limiter Redis fallback to in-memory (previously disabled without Redis) - Removed deprecated clearAuthCookie function4d652d8
-
feat: Elite Engineering UI Modernization, Production Auth Fixes, and HF Deployment Stability
ahmdelbaz28-ux50a005c