Spaces:
Running
Running
Commit History
Today
-
security(cfskill-run3): deep audit fixes + SonarCloud quality pass
Z UserAudit (cloudflare/security-audit-skill, 7 coverage units, 5 hunter waves): - cache: Redis delPattern prefix->glob — settings/approval-gate invalidation was a silent no-op under Redis (stale contact info + delayed gate close) - jwt/approval: remove hardcoded dev APP_SECRET fallback (public repo secret) - boot: production fatal log when EDGE_HOST_ENFORCE unset (fail-loud) - yt-sync: GET /state now bound to x-sync-ts window (eternal replay lane gone) - paymob webhook: signed currency actually passed to verifyPaymobAmount; promo quota released on terminal FAILED events (+ idempotent re-consume when a later event completes the same order) - push: endpoint rows can no longer be re-bound/cross-deleted between users - sessions: bounded device-metadata strings (column widths) - notification links: protocol-relative URLs rejected; noopener unified; Paymob redirect pinned to accept.paymob.com - deploy.sh: secret gate covers re_/gsk_/nvapi-/modal-/mysql:// families SonarCloud (194 open ->…700d33c
Yesterday
-
fix(mobile+load): full platform review — phone cropping, boot race, hung-provider stalls
Z UserMOBILE (owner report 2026-12-02: admin Users tab clipped on phone): - Users tab approvals rows: min-w-0 + flex-1 on the text block and break-all on the email line — a long unbreakable email token pushed the row past the card edge and the card's overflow-hidden CLIPPED it (reproduced at 320px, row painted 122px off-screen; now wraps inside the row) - Global safety net: html/body overflow-x clip (clip, not hidden — sticky keeps working) so one unbreakable token can never widen the page again - Grid auto-track blowout: 34 grids across 9 files declared cols only at sm/lg (grid gap-4 lg:grid-cols-N) — the implicit auto track sized to max-content, so nowrap content inflated tracks to 715px on a 320px screen (dashboard Recent Activity). Base grid-cols-1 added everywhere - Dialog/AlertDialog primitives: grid-cols-1 on the content grid — the bare shadcn `grid` sized its implicit track to max-content, so dialogs hosting truncate/nowrap rows (lessons manager) scrolled their whol…8054c5d
3 days ago
-
fix(security): allow ONLY huggingface.co to frame the app — HF Space page visitors got a dead shell
ahmdelbaz28-uxLive embed probe (2026-11-30, headless browser): the Space page iframe got HTTP 200 for the document but Chrome refused to RENDER it — unconditional X-Frame-Options: DENY + CSP frame-ancestors 'none' block the frame outright, so zero subresources ever loaded and each visit filed a frame-ancestors csp-report. Visitors on huggingface.co/spaces saw an empty placeholder. Root cure: for embed-frame requests (sec-fetch-dest: iframe) drop XFO and emit frame-ancestors https://huggingface.co in BOTH CSP branches (nonce HTML + fallback). Every other parent origin stays blocked — their iframe documents also carry sec-fetch-dest: iframe but their origin is not huggingface.co — so clickjacking protection is unchanged for all non-embed responses. Pinned by security.frame-ancestors.test.ts (5 tests; suite green: 1404).ab8ae78 -
fix(shield): space-embed same-origin lane — HF Space page visitors got a dead shell
ahmdelbaz28-uxLive confirmation-round probe (2026-11-30) measured that the Sec-Fetch-Dest: iframe exemption lets the embed DOCUMENT load but every same-origin request the document then fires (SPA JS/CSS assets, /api/* fetches, csp-report POSTs) still arrived on the raw space host and was shield-404'd — visitors on huggingface.co/spaces saw a rendered shell with no app behind it. Root cure: exempt sec-fetch-site: same-origin subresources of *.hf.space hosts (the same browser-controlled-header trade-off the iframe exemption already documents; real closure remains the CF Worker secret header). Canonical-domain traffic keeps passing via the host allowlist, untouched. Pinned by 5 new host-gate tests (14 total in the file, suite green: 1399).df3c89a
4 days ago
-
fix(sonar): wave 5 - final in-scope sweep, 92 findings across 67 files (complete: 994/994 in-scope)
Z User- 23 two-count files + 44 one-count files: S6582/S7503/S7755/S7773/ S7780/S8786/S9382/S3776/S6759/S6819/S5906/S5976/S3863/S7763/S7785/ S8782/S4138/S7744/S6606/S4624/S7778/S7754 - google-auth-router 47->11, shield 39->6, security middleware 24->8, ForgotPassword 34->4, VerifyEmail 22->5, Courses 28->13 (DOM identical) - S9382 NOSONAR only for: Redis connection retry backoff, migration ledger order - both documented sequential necessities - contract tests re-pinned: issueSessionResponse centralization (both session paths categorize), isHostGateExempt approval-action exemption Verified: tsc clean, eslint 0 errors, vitest 1394/1394.6165987
7 days ago
-
fix(approval-loop): email Accept/Reject now executes — challenge-free links + honest db_error page
ROOT CAUSE (owner report 'قبول/رفض الإيميل مش بينفذ'): the email buttons linked to the canonical domain, whose Cloudflare managed challenge never passes for mail-app webviews/non-JS clients (measured: real-browser navigation stuck on 'Just a moment…', curl 403 cf-mitigated) — clicks carrying the owner's signed authority died at the edge and the approval circle never closed. - approval.ts: approvalActionBaseUrl() — APPROVAL_ACTION_BASE_URL (Space var, set to the raw hf.space origin) routes the buttons straight to the app; falls back to FRONTEND_URL. Signed HMAC token remains the sole authority. - shield.ts: exempt /api/approval/action from the host gate (same precedent as the paymob/yt-sync HMAC-verified paths) — clicks work from ANY host. - approval-action-route.ts: db_error is now an honest 503 retry page — it can no longer masquerade as 'تم البت في هذا الطلب مسبقاً' while nothing was written. - env.ts/.env.example: APPROVAL_ACTION_BASE_URL documented. - contract tests (45 to…263459d -
security(audit-run-3): comprehensive security audit fixes (cloudflare security-audit-skill)
Security Audit Run 3Confirmed vulnerabilities fixed: - paymob-webhook: bind SIGNED obj.order.id to stored paymobOrderId (unsigned merchant_order_id was the only correlation key — replay-with-swap class); verify the callback's own signed currency (EGP pin now two-sided); preserve the original charge reference on refund/void events - promo quota release is now transaction-atomic with the refund/reject that compensates it (webhook tx + admin reject tx) - referral reward coupon is granted at ADMIN APPROVAL instead of registration (self-referral coupon farming closed); single decision path in decideApproval - wishlist add/list leak of unpublished (draft) course metadata — existence + isPublished validation on add/toggle, publish predicate on the list join - vision image-quota reservation leak on the per-user daily-cap 429 path (refund exactly once invariant restored); vision lanes re-keyed to the AUTHENTICATED account (u<id>) instead of spoofable client headers - forgotPassword: per-RECIPIENT s…ec34781
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
13 days ago
-
fix(shield): v1.1.3 origin-gate hardening — operator lane + spoof detection
Z UserOrigin E2E audit (2026-11-20) measured HF's space router passing a client-supplied x-forwarded-host through UNCHANGED: `curl -H "x-forwarded-host: ahmedelbaz.qzz.io"` direct to the raw *.hf.space origin returned 200 for EDGE_HOST_ENFORCE-gated endpoints — the disguise is spoofable by construction (every header at the container is client-writable). Zero-breakage hardening shipped (legit traffic path unchanged): - OPERATOR LANE: timing-safe EDGE_ORIGIN_SECRET Bearer bypasses the host allowlist (monitoring + origin E2E get a legitimate path, no spoofing). Unset/short secret -> lane never opens (fail-closed, byte-identical for everyone else). Same disguise contract as health-router's operator gate. - SPOOF DETECTION: gate passes on the raw space host via a client xfh WITHOUT a Cloudflare fingerprint (cf-ray; CF injects it on every served request) -> throttled warn (5/min) with claimed/actualHost/hasCfRay. The hasCfRay field settles within a day of live traffic whether HF's r…579b21c
21 days ago
-
fix(security): Permissions-Policy camera=(self) — un-block getDisplayMedia screen share for all Chromium users
ahmdelbaz28-uxROOT CURE (live-verified 2026-11-13): the app shipped 'camera=()' in the Permissions-Policy header. Chromium gates getDisplayMedia (screen share) behind the CAMERA policy, so the chatbot's live screen-teacher lane failed for every Chrome/Edge user with 'Permissions policy violation: camera is not allowed in this document' — the share bar never went live. Local Chromium matrix (pp_matrix_test.py): camera=() -> policy violation, share fails camera=() + display-capture=(self) -> STILL violates (camera key is the gate) camera=(self) + display-capture=(self) -> NO violation (exact fix shipped here) camera=(self) only permits the permission CHECK — the app never calls getUserMedia, so the camera stays prompt-gated and effectively unused; microphone stays hard-denied. Applied consistently to every place that set the old header: api/middleware/security.ts (the live path), nginx.conf, k8s ingress, CF worker, WAF rules JSON.30aee4f -
fix(chatbot+telegram+youtube): root-cure the bot starvation, stream truncation, tier hang and blind-tick treadmill
ahmdelbaz28-uxROOT-CAUSE AUDIT 2026-11-13 (production logs + full-stack code audit): TELEGRAM BOT - chatbot-router: the anonymous 60/day-per-IP quota treated ALL Telegram DM users as ONE GitHub-Actions runner IP — after 60 DMs/day the whole bot went silent until UTC midnight while the site kept working. New fail-closed bot-worker lane: x-bot-worker-auth = HMAC(SYNC_INGEST_SECRET, "bot-worker-v1") (timing-safe; secret already provisioned on both sides) → 600/day + 60/min lane mirroring the Telegram-side caps. - telegram-worker-job: sends the derived auth header; workflow passes the existing SYNC_INGEST_SECRET — zero new secrets. - telegram-bot: DM brain retry was deadline-only (20s < one endpoint attempt) so the documented retry never ran — now attempt-counted (2 attempts, retry only after a fast failure, 150s hard cap). - telegram-bot: dmHistories/dmHourCounters grew unbounded — expired entries are now swept (piggyback + 10-min interval). CHATBOT (site bot) - chatbot-stream: the …3a6d89e
23 days ago
-
feat(yt-sync): worker cron push + ingest shield exemption — deterministic mirror
Z UserSecond sync driver: the CF worker now runs a scheduled handler (cron 13,28,43,58) that fetches the playlist on Cloudflare's clean egress and pushes it to the origin's HMAC-gated ingest — independent of GitHub Actions' unreliable scheduler (4 runs in 2 days on */15) and of the origin's fully blocked YouTube egress. - worker-v7-hardened.js: scheduled handler + ytSyncPushToOrigin — verbatim titles, placeholder filter, HMAC over the raw body (matches yt-sync-ingest.ts), fail-closed dormancy without SYNC_INGEST_SECRET, zero new HTTP routes. - deploy-cf-worker.yml: optional SYNC_INGEST_SECRET binding + schedules API registration (array form with wrapped-form fallback). - shield.ts: /api/yt-sync/* exempt from the host allowlist gate (same pattern as the Paymob webhook — the route is HMAC-verified fail-closed inside its handler, so the host gate adds nothing there; measured 2026-11-10: identical payloads 404 via hf.space while passing via other egress paths).302134a -
feat(login): cinematic muted video background — power-grid/ETAP scene
Z User- New 10s background video (public/videos/login-bg.mp4, 1.2MB, audio track fully REMOVED via ffmpeg -an + faststart for instant web start) + poster JPG fallback for slow connections / reduced motion. - Login.tsx: fixed full-screen <video> (autoplay muted loop playsInline), poster underlay, dark contrast gradient + vignette for WCAG-readable glass card, fade-in on canplay, onError fallback to poster, one frosted panel around Google + form, brand impression strip. - index.css: prefers-reduced-motion hides the looping video (static poster shown instead). - security.ts/cache.ts: mp4|webm|m4v|ogg|mp3 now classified as static assets → correct Cache-Control (1d + stale-while-revalidate) for media. - Verified: tsc clean, vite build clean, browser test desktop+mobile (video playing muted, looping, zero console errors).41b4201 -
feat(growth): six retention/conversion engines — email drip, timestamped notes, guest preview, referrals, verified testimonials, mini-player
Z User1. EDUCATIONAL EMAIL DRIP (Resend, bilingual ar/en, idempotent): - welcome on register (event-driven) + 48h nudge sweep (6h scheduler, prod-only) + completion congratulation on the exact false->true flip - emailDripLog UNIQUE(userId,kind) = zero double-sends; failed sends release their slot for retry 2. TIMESTAMPED LESSON NOTES: notes stamped at the exact video second, panel under the player, tap [m:ss] to seek back; userNotes.timestampSeconds 3. GUEST PREVIEW (generic for future paid courses): course.previewVideo serves ONLY isFree lessons of published courses to visitors (fail-closed FORBIDDEN otherwise); ETAP first lesson auto-flagged isFree; amber watch-before-you-pay banner + per-lesson preview badges 4. REFERRAL PROGRAM: /register?ref=CODE -> referrer earns a 10% coupon per joined friend, friend gets a 5% welcome coupon (both via existing promoCodes flow); lazy referralCode per user; profile card with copy link + coupons; referrals table attri…4cac0c1
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 -
merge(youtube-sync): rebase on the playlist-import + gate + dashboard work — add AUTO-sync, first-video cover, fake purge
Z UserAdopts origin's mature shared modules verbatim (single youtube-url source of truth incl. its tests, YouTubeLessonPlayer with the useWatchTracker contract, video-protection youtube branch, subscribe gate, overhauled dashboard, CF relay fetch, mobile min-w-0 fix) and adds the genuinely-new sync engine on top: - api/lib/playlist-sync.ts: planPlaylistSync (pure, 9 tests) + applyPlaylistSync — auto-import via the oEmbed-VERIFIED pipeline (placeholders dropped, titles verbatim from YouTube's own answer), retitles drifted lessons, mirrors playlist order, collapses duplicates, first-sync purge (prunedOnce) of non-playlist lessons, course cover = first video's maxres thumbnail. - watcher tick: policy-gated auto-sync every 15 min (dynamic import — no ESM cycle), never-throw, logged. - admin: youtubeSyncStatus / syncPlaylistNow (replace=true = full cleanup) / updateYoutubeSyncSettings + dashboard sync panel (status cards, buttons, 3 toggles) beside the subscribe-gate panel; lesson …b01c35f -
feat(youtube-sync): course mirrors the channel playlist — verbatim titles, first-video cover, in-site playback
Z UserThe owner's four asks, one pipeline: 1. COVER = first real playlist video's YouTube thumbnail (autoCover policy, maxresdefault with client-side hq→mq fallback chain). 2. AUTO-SYNC: the YouTube watcher tick (15 min) feeds BOTH notifications AND the course — new uploads appear as published lessons within minutes, under their EXACT YouTube titles (never invented); reorders are mirrored; a video leaving the playlist is removable via full-sync. 3. FAKE CONTENT PURGE: boot-time v14 migration deletes the old 4-course seed (power-systems-basics / protection-relay-coordination / renewable-energy-design, payment-guarded) + orphan categories; the first sync also purges non-playlist lessons once (prunedOnce), then only via explicit admin action. 4. DASHBOARD: YouTube sync panel (sync now / full sync + cleanup / auto-import / free-policy / auto-cover toggles + live status cards) and lessons dialog with YouTube badges + real thumbnails per lesson. Playback: video-protecti…d128011
29 days ago
-
feat(lessons): YouTube playlist playback embedded in-site — zero server load
Z UserTHE CONVERSION: lesson videos now stream from the channel's YouTube playlist INSIDE the site's own player screen — nothing uploaded to (or proxied by) our server. Hybrid by design: legacy R2 lessons keep the protected player. Server: - src/lib/youtube-url.ts (shared, pure): extract YouTube id from every shape (watch/shorts/youtu.be/embed/live/oembed/bare id), embed/watch/thumbnail builders — 14 unit tests. - video-protection.ts: YouTube branch BEFORE any R2 presigning (presigning a youtube URL used to throw → misleading 503); returns kind=youtube + id + youtube-nocookie embed URL. R2 path untouched (kind=r2). - security.ts CSP (both blocks): frame-src youtube-nocookie/youtube + script-src iframe_api hosts. Everything else stays locked down. - admin-courses: youtubePlaylistVideos admin query reuses the watcher's multi-source playlist pipeline for the import dialog. Client: - YouTubeLessonPlayer: embedded YT IFrame API player in the same aspect-video slot, YT controls ins…8f5b256
-
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
-
fix(e2e): make purchase→certificate journey fully work (4 real bugs)
Z UserFull local E2E (Playwright + MariaDB + HMAC-mocked Paymob gateway) exposed four production defects on the core monetization path: 1. Video lessons could never complete — the frontend never called the server's course.markWatched; only quizzes completed lessons, so any course with video lessons could never reach isCompleted and certificate.generate stayed FORBIDDEN forever. → useWatchTracker now marks the lesson complete on video 'ended' and CourseDetail refetches checkEnrollment via the new onLessonCompleted. 2. Stale enrollment state after paying — global react-query staleTime (5 min) + localStorage persister served the PRE-payment enrolled:false after the gateway redirect (even through location.reload()); paying customers saw 'Buy Now' for up to 5 minutes. → checkEnrollment now uses staleTime: 0 (always verified server-side). 3. CSP had no media-src — <video> fell back to default-src 'self', so R2 presigned URLs (https://<account>.r2.cloudflarestorage.…bc3d5a6
-
fix(security): remediate audit run-1 confirmed findings (20)
Z UserCloudflare security-audit skill, full audit of 8ea551b (quick profile, source-only): 34 coverage units, 8 hunter domains, 6 independent verifiers, 21 confirmed + 7 needs_validation records. Artifacts: security-audit-skill/elbaz-platform/run-1/{REPORT,FINDINGS-DETAIL, NEEDS-VALIDATION}.md + findings.json (schema-validated) + coverage-ledger.json. HIGH (both XSS): - chat renderer: extract pure renderer to src/lib/chat-render.ts and escape EVERY text segment before markdown transformation (was: code fences only); href attribute breakout closed; biome-ignore safety claims made true; regression tests (img/script/href-breakout/table-cell payloads) - seo-meta: jsonLdSafeStringify escapes < > U+2028/2029 so stored course titles/FAQ questions cannot break out of the JSON-LD <script> element (the nonce stamper previously re-armed the injected script); tests MEDIUM: - CSRF: same-origin gate in security middleware for POST/PUT/PATCH (Origin/ Referer must match the CORS allowlist when…e5934c3
-
feat(payments): mobile-wallet checkout via classic Accept flow (Vodafone Cash live)
Z UserProbed live against the gateway: - Intention API rejects the account's wallet integration 5647507 (UIG/online_new) with 404 'Integration ID/Name does not exist' while the card integration 5647438 works — method-name forms also rejected. - Classic Accept flow accepts the wallet end-to-end: auth -> order -> payment_keys (201) -> hosted IFRAME 1039272 renders the wallet page (iframe_wallet_sdk.js confirmed in the response). Changes: - paymob.ts: PaymobRuntimeConfig gains apiKey + walletIframeId; createLegacyWalletCheckout (auth -> order -> payment_keys -> IFRAME URL, merchant_order_id = our transactionId so the existing HMAC webhook correlates identically); isWalletMethod; summarizePaymobConfig now requires the IFRAME only when a wallet integration is configured - payments-config/core: resolve apiKey (env-only) + walletIframeId (env PAYMOB_IFRAME_ID or dashboard setting paymob_wallet_iframe) - payment-router: wallet methods dispatch to the legacy flow; cards stay on t…2cbff08
-
fix(edge): explicit host allowlist — CORS_ORIGINS contains hf.space (measured) and re-opened the door; exempt internal healthcheck + HMAC-verified paymob webhook
Z User7b84527 -
security(edge): origin-side host allowlist (measured) replaces dead HMAC path
Z UserMeasured facts (live): qzz.io is not a CF zone on this account and the domain's requests never pass through the worker — the 'cloudflare' in its response headers is HF's own edge. The HMAC edge-origin scheme had no signer in the real request path; enforcing it blocked the production domain. Replace it with a host allowlist at the origin behind EDGE_HOST_ENFORCE: - allowed hosts from FRONTEND_URL/CORS_ORIGINS + ahmedelbaz.qzz.io - Sec-Fetch-Dest: iframe exception keeps the HF Space page working - without the flag, behavior is unchanged (safe rollout) Also: temporary /api/debug-headers measurement endpoint (removed after enforcement is verified) and warning-only route check in the worker workflow documenting the missing CF zone.d810b9e -
security: enforce edge-origin auth end-to-end + close silent-degrade paths
Z User- EDGE_ORIGIN_SECRET now MANDATORY at deploy: worker workflow fails if the GitHub secret is missing/short and provisions it as a secret_text binding; Space secret set separately. Direct-to-origin traffic (hf.space) without a fresh HMAC is rejected 404; sole exception Sec-Fetch-Dest: iframe keeps the HF Space page embed functional (documented trade-off). - video-protection: fail CLOSED on R2 presign failure — the old HMAC fallback handed out raw URLs with _sig params nothing verifies. Unsigned fallback removed entirely. - db: multipleStatements disabled on the application pool; schema-init gets a dedicated pool (only consumer that legitimately needs it). - /api/health: DB failure no longer echoes raw mysql2 error text (host/port leak); detail goes to structured logs only. Verified locally: tsc -b clean, 83/83 tests.13205f6 -
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: bust stale immutable cache on public/ assets + sane cache policy
Z User- cacheMiddleware: /public/ images (stable filenames) were cached 1 year immutable — new deployments could never reach returning visitors (the new PowerFactory logo stayed broken for cached browsers). /assets/ hashed files keep 1y immutable; /public/ files now get 1 day + stale-while-revalidate - Home.tsx: ?v=20261010 on software logos to immediately bust browsers that already cached the old broken PowerFactory SVG under the old policyc96c094
-
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
-
feat: apply cyberpunk engineering UI updates and fix TS compilation errors
6ef332a
-
feat: chatbot typing cursor + auto-scroll + smooth animations, light mode icon color fixes
ahmdelbaz28-ux- Professional typing cursor (thin vertical bar with glow) - Auto-scroll during streaming and after message completion - Smooth fade-in animation for streaming text chunks - Smooth enter/exit animations for typing indicator (bouncing dots) - Fixed stacking timeout bug in typing exit animation - Added 8 new light mode icon color overrides (violet, emerald, rose, etc.) - Added placeholder colors, badge backgrounds, admin tab states10963b9
-
refactor(dry): extract duplicated getClientIp into unified helper
ahmdelbaz28-ux## Problem The client IP extraction logic (cf-connecting-ip > x-real-ip > x-forwarded-for) was duplicated across 12+ locations in 6 files: - api/middleware/shield.ts (getClientIp) - api/google-auth-router.ts (getClientIp) - api/local-auth-router.ts (getClientIpFromHeaders + 6 inline duplications) - api/chatbot-router.ts (getChatbotIp) - api/middleware.ts (inline in globalRateLimit) - api/boot.ts (inline in /__webhook/status) ## Bugs fixed 1. shield.ts: fallback IP was '127.0.1' (wrong — should be '127.0.0.1' or 'unknown'). Now returns 'unknown' consistently. 2. boot.ts: used .pop() on x-forwarded-for, which returns the LAST proxy IP, not the client IP. Now uses .shift() (first entry = original client). ## Solution Created api/lib/client-ip.ts with two exported functions: - getClientIpFromHeaders(headers: Headers): string — for tRPC context - getClientIpFromHono(c: HonoContext): string — for Hono routes Both use identical trust order: cf-connecting-ip > …ec4d838 -
fix(sonarcloud): address 26 new issues from Biome refactor
ahmdelbaz28-ux- S3626 (2x): add NOSONAR to explicit return; needed for noImplicitReturns TS strict - S8786: move NOSONAR to same line as regex (was on comment line above) - S3358 (CourseDetail): add NOSONAR for intentional 3-state price ternary - S6819 (5x): add NOSONAR for role=dialog/list/region/presentation on divs where native semantic elements have unwanted default behavior - Restore public/cache-nuke.js + public/rtl-detect.js to pre-Biome state (Biome's arrow function + 'use strict' removal caused 13 S3504/S5145/etc issues on these legacy standalone browser scripts)736cb02 -
feat(strict-checking): install Pyright + Biome, add ultra-strict tsc, fix all issues
ahmdelbaz28-ux## Pyright (Python type checker) - Installed pyright 1.1.411 as devDependency - Ran on elbaz-platform: 0 errors (project is 100% TypeScript, no Python files) ## TypeScript ultra-strict mode (tsconfig.ultracheck.json) Created new tsconfig extending tsconfig.app.json with additional strict flags: - noImplicitReturns, noImplicitOverride - allowUnusedLabels: false, allowUnreachableCode: false - forceConsistentCasingInFileNames: true - strictBindCallApply, strictFunctionTypes, strictNullChecks (all explicit) Fixed 9 errors found by ultra-strict check: - TS7030 (6x): Not all code paths return a value — added explicit 'return;' in security.ts, shield.ts, ChatBot.tsx, CookieConsent.tsx, AnimatedCounter.tsx, useWatchTracker.ts - TS4114 (3x): Missing 'override' modifier in ErrorBoundary class — added 'override' to state, componentDidCatch, render methods ## Biome 2.5.2 (strict linter) - Installed @biomejs/biome 2.5.2 as devDependency - Created biome.json with recommended preset + sensib…92398e6 -
fix(critical): root-cause fix for CDN caching 404 outages
Z UserPROBLEM: After every deploy/restart, the HF Space CDN cached bare 404 responses for /api/* routes for 5+ minutes. This caused prolonged outages where the site appeared down (API returned 404) even though the app was healthy and serving requests correctly. ROOT CAUSES (3 layers of caching, all fixed): 1. Missing app.notFound() handler: Hono's default 404 response has NO Cache-Control headers. The CDN cached this bare 404 for minutes. Fixed by adding a custom notFound handler that sets aggressive cache-busting headers on every 404. 2. Missing Surrogate-Control header: Cache-Control: no-store is respected by browsers but some CDNs (including HF Space) ignore it and only respect Surrogate-Control. Added 'Surrogate-Control: no-store' to ALL API responses, HTML responses, 404 responses, and 500 error responses. 3. PWA Service Worker was caching API 404s: vite.config.ts had NetworkFirst handler for /api/* with 5-min cache fallback. When the server returned 404 (…8b3d0a0 -
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): comprehensive security & quality fixes — 200+ issues resolved
ahmdelbaz28-uxBLOCKERS (2): - secrets:S8215 — api/local-auth-router.ts: replace hardcoded bcrypt dummy hash with a lazily-generated hash from crypto.randomBytes (no real hash disclosed in source). - json:S6418 — infra/.../access-policies.json: replace hardcoded Cloudflare service token with ${CLOUDFLARE_ZERO_TRUST_SERVICE_TOKEN_ID} placeholder. CRITICAL BUGS (16): - css:S4670 (x5) — src/index.css: remove stray backslash escapes from attribute selectors ([data-user-menu], [data-sonner-toast], [aria-current]). - typescript:S3923 (x5) — remove ternaries that returned the same value on both branches (ElectricParticles, AdminNotificationPanel x2, NotificationCenter, ForgotPassword). - typescript:S1082 (x6) — add keyboard handlers + role/tabIndex to non- interactive divs with onClick (CookieConsent, input-group, CertificateView, CourseDetail video controls + seek bar + payment modal). VULNERABILITIES (121): - docker:S6470 — Dockerfile: document that COPY . . is safe because of .dockeri…c7df2b5
-
fix(security+db+perf): pre-launch hardening — 7 critical + 4 DB + perf wins
ahmdelbaz28-uxCRITICAL SECURITY (7 fixes): - email.ts: remove recoveryLink from JSON response (account-takeover via password reset when email delivery fails) - twofa-router.ts: remove dead verifyForLogin procedure (IDOR + no rate limit) - twofa-router.ts: replace hardcoded 'elbaz-2fa-backup' HMAC key with APP_SECRET-derived key (forged backup codes possible with repo access) - review-router.ts: adminList authQuery→adminQuery, adminTogglePublish authMutation→adminMutation (any logged-in user could hide/show any review) - rate-limiter.ts: per-action auth rate limits (login=10/15min, forgotPassword=5/15min, register=10/15min, etc.) — was 1200/min shared - middleware.ts: apply globalRateLimit to authMutation + adminMutation (previously bypassed rate limiting entirely) - infra/resend-integration/env-variables.txt: replace leaked Resend + OpenRouter API keys with placeholders (keys are now rotated) CRITICAL DATABASE (4 fixes): - init-schema.sql: add 3 missing tables (userSessions, userNotes, …f46a61a
-
perf: massive speed optimization — 1-year cache, edge caching, reduced SW
ahmdelbaz28-uxPERFORMANCE OPTIMIZATIONS ========================= 1. 🚀 1-Year Cache for Static Assets (boot.ts + security.ts) ───────────────────────────────────────────────────────── Before: Cache-Control: max-age=14400 (4 hours) for all assets After: Cache-Control: public, max-age=31536000, immutable (1 year) - Assets in /assets/ (JS, CSS with content hashes) → immutable, 1 year - Images (png, jpg, webp, svg, etc.) → immutable, 1 year - Fonts (woff2, ttf, etc.) → immutable, 1 year - Critical files (sw.js, cache-nuke.js, etc.) → no-cache (unchanged) Since assets have content hashes in filenames, they're immutable. Browsers and CDNs can cache them permanently without staleness. 2. 🚀 Cloudflare Edge Caching (worker-v7-hardened.js) ──────────────────────────────────────────────────── Added CDN-Cache-Control and Cloudflare-CDN-Cache-Control headers: - Static assets: cached at Cloudflare edge for 1 year - HTML pages: cached at edge for 30 seconds (fast nav +…438fbda
-
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 -
fix(chatbot+csp): increase Modal timeout to 120s + fix CSP on custom domain
ahmdelbaz28-uxCHATBOT FIXES: - Modal timeout: 75s → 120s (GLM-5.1-FP8 is a reasoning model that needs more time for complex questions) - Modal cooldown: 60s → 15s (was too long — after one failure, Modal was unavailable for a full minute, forcing all traffic to OpenRouter) - This ensures Modal (primary) is actually used instead of always falling back to OpenRouter CSP FIX (custom domain): - The fallback CSP (for non-HTML / cached responses) now includes script-src 'self' 'unsafe-inline' instead of omitting script-src entirely. This fixes CSP violations on ahmedelbaz.qzz.io where Cloudflare CDN serves cached HTML without per-request nonces. - The primary CSP (for fresh HTML) still uses nonce-based protection. - 'unsafe-inline' is less secure but prevents the site from breaking on the custom domain. Once Cloudflare cache is properly configured to bypass HTML, we can remove this.5818870
-
Fix UI crashes, fix memory pressure check, and update professional branding
356d780
-
fix: comprehensive launch fixes — lru-cache dep, mock DB disabled in prod, promo router auth, CSP report-to header, Docker HTTP healthcheck, course thumbnail paths, shield rate limit, favicon.ico, DB SSL warning, reviews table in Drizzle schema, softwareDownloads relations, useWatchTracker cap alignment
ahmdelbaz28-uxcca2eaf -
fix: production launch readiness — Docker node:22, Zod v4 env order, Drizzle promo router, findUserByUnionId, JWT expiry, Paymob URLs, rate-limiter API, studentCount, cross-env, .env.example, components.json, seed.sql deprecation, unused auth middleware, vitest alias
ahmdelbaz28-ux8406a34 -
fix: permanent cache fixes — WBS timestamp, evictExpired safety, session double-delete, API cache headers, nginx no-store, sitemap invalidation, HTML template mtime, graceful shutdown
ahmdelbaz28-ux8738417 -
fix: Google Sign-In end-to-end - CSP, cookie overwrite, GIS script loading
ahmdelbaz28-uxRoot causes fixed: 1. CSP blocked accounts.google.com and www.googleapis.com - added to script-src, connect-src, form-action 2. google-auth-router setAuthCookies used c.header() which overwrites first cookie - changed to c.res.headers.append() 3. Login/Register GIS script loading improved - uses __loadGsi() helper, crossOrigin attribute, better retry logic Changes: - api/middleware/security.ts: Added https://accounts.google.com to script-src, https://www.googleapis.com and https://accounts.google.com to connect-src, form-action - api/google-auth-router.ts: Fixed setAuthCookies to use append() instead of header() which was overwriting the first Set-Cookie - src/pages/Login.tsx: Improved GIS loading with __loadGsi() helper and crossOrigin attribute - src/pages/Register.tsx: Same GIS loading improvements4e93b03
-
fix: critical security, performance, and code quality fixes
ahmdelbaz28-ux +1: OpenClaude (mimo-v2.5-pro)Security: - Fix SQL injection in db-init.ts seed (parameterized query for admin password) - Fix XSS in ChatBot renderMarkdown (escape quotes in HTML entities) - Fix shield.ts: reduce max payload from 1GB to 100MB for uploads - Fix shield.ts: bot filter now only blocks suspicious agents on sensitive paths Performance: - Cache SPA HTML template in memory (avoid disk read on every page load) - Cache course count for offerCount with 5-minute TTL - Cache sitemap XML with 1-hour TTL (avoid DB query per request) - Fix double process.memoryUsage() call in shield middleware Code Quality: - Remove duplicate getAllUsers from admin-router (identical to users) - Add pagination total count to admin users and payments queries - Remove unused reviews table from schema (dead code) - Fix Home.tsx: replace MutationObserver+IntersectionObserver hack with clean IO - Fix password test timeout (bcrypt is slow, increase to 15s) - Update Admin.tsx to handle new paginated response format All 83 tests pass. Z…33ce4e1
-
feat: implement 'Digital Shield' firewall with distributed rate limiting, payload protection, and bot filtering
ahmdelbaz28-uxbe7aec2 -
feat: Elite Engineering UI Modernization, Production Auth Fixes, and HF Deployment Stability
ahmdelbaz28-ux50a005c