Spaces:
Running
Running
Commit History
Today
-
fix(health): db-check verdict follows control flow — throw=unhealthy, healthy return unconditional
Z UserLive-caught during the dac06da verification: the first cut kept 'result ? "healthy" : "unhealthy"' while timedDbPing() returns void, so every db check reported unhealthy with a reachable database (/api/ready 200 contradicted /api/health 503 within a minute). Source-pin regression guard added (throw=unhealthy contract, no truthiness on the void result).7917636 -
fix(pinned-dispatcher+health+honest-proofs): Node autoSelectFamily dual-contract lookup — BYOK lane, /test and the whole dynamic cascade unbroken
Z User- pinnedLookup now answers BOTH net contracts: array form under all:true (autoSelectFamily destructures addresses[0] — the old single-object form made EVERY pinned dial throw in ms: BYOK chat lane, BYOK /test oracle and the platform dynamic cascade silently fell back since the pinning change) - health: unified isOverallHealthy critical set (db+migrations only, shared by cached+fresh paths — kills the recurring public 503 windows) + 4s deadline & one retry on the db ping (was: unbounded hang) - maskApiKey: ••••last4 only (write-only contract, no key-prefix leak) - live proofs: pipefail + guarded retries (the tee-pipeline always reported success — vacuous green), origin-probe base + x-forwarded-host (edge challenge immune), probe session for the login-gated chat lanes, explicit ENV-SKIP instead of silent pass - tests: pinnedLookup dual-contract + all:true array form, health-critical semantics (7), mask last4; 1480/1480 green, tsc clean, build OK - DEPLOYMENT.md §13 docu…dac06da -
quality(sonar): S3776 paymob side-effects extraction + remaining BUG fixes
Z User- paymob webhook: refund-revocation + promo reconciliation extracted verbatim into reconcileSideEffectsAfterTransition (applyWebhookStatusTransition now far below the 15 ceiling) - CourseDetail: validatePromo().catch, isCourseCompleted && Boolean(course?.id) (S6439 leaked value), navigate NOSONAR markers (framework void|Promise) - Admin: navigate NOSONAR marker Tests 1472/1472, tsc clean, build OK.26533fc -
quality(sonar): complexity under limit + React19 SyntheticEvent migration
Z User- paymob webhook: guard chain + status transition extracted (S3776 22->low) - boot: security posture check extracted from start() (S3776 16->low) - FormEvent -> SyntheticEvent across 7 files (React 19 types: the alias is deprecated because it never matched a real DOM event class) Tests 1472/1472, tsc app+server clean, build OK.f57f434 -
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(contact+pwa): social taps always land + post-login install suggestion
ahmdelbaz28-uxMEASURED ROOT CAUSES (live production, 2026-12-03): 1) Contact save persistence WORKS: the owner's facebook share URL and gmail address are stored in siteSettings AND served by the live footer. The reported 'save reverts' predated the current deployment state. 2) Footer icon activation WORKS in normal browsers (proved via same-tab navigation: the share link lands on the owner's real Facebook page). The genuinely dead case: IN-APP WEBVIEWS (Facebook/Instagram/TikTok/ WhatsApp browsers) silently drop target=_blank activations — the user taps and nothing happens. That is what 'the icon does not navigate' felt like on a phone. FIXES: - external-links.ts: openExternal reroutes http(s) taps to the SAME tab inside in-app webviews (UA detection superset incl. TikTok/Bytedance), leaving native target=_blank untouched everywhere else; mailto:/tel: always keep OS handling. Unit-tested (18 cases). - Footer social anchors wired through openExternal. - siteSettings contac…ec94e17 -
fix(courses): free-course lessons play without enrollment — server honours canAccessLesson
ahmdelbaz28-uxOWNER CONTRACT (2026-12-03): a NON-premium course is fully watchable by any signed-in user — the client already treated it that way. Live-measured on production (etap-complete-course, premium=false, lesson 33 isFree=false): lessonVideo answered 403 FORBIDDEN 'You must be enrolled' while the UI showed a play button — a client/server contract mismatch that ended in the dead-end 'video unavailable' screen the owner reported. SERVER - course-watching.ts: lessonVideo / markWatched / heartbeat now project courses.isPremium and demand enrollment ONLY inside premium courses. lessonVideo serves isFree || !courseIsPremium. Login-first (2026-11-22) unchanged; premium courses keep the active-enrollment gate (audit run-1) untouched. TESTS - security-audit-cfskill-run2: new regression guard pins the free-course contract on all three procedures (projection + gate shape + no bare isFree gate may return).29490ad -
fix(courses): remove subscribe gate — instant playback, auto-scroll, dead-lesson self-heal
ahmdelbaz28-uxOWNER CONTRACT (2026-12-03): the subscribe-to-the-channel gate is GONE. Why: users clicking a course video hit the subscribe wall; the subscribe button did not open YouTube; most playlist videos answered 'video not available'. Root causes addressed end-to-end: SERVER - course-watching.ts: lessonVideo no longer requires a signed unlock ticket; completeSubscribeUnlock procedure deleted; SUBSCRIBE_REQUIRED cannot occur anymore. Login-first (2026-11-22) unchanged. - settings-router.ts: 'subscribeGate' dropped from the public section allowlist (deny-by-default; legacy rows stay server-side). - playlist-sync.ts: deadYouTube self-heal lane — YouTube-linked lessons whose video LEFT the playlist (broken 'الفيديو غير متاح' embeds and legacy placeholder rows) are purged automatically on trusted full-mirror syncs (gh-relay ingest / admin-manual). Throttled watcher ticks never delete. R2/manual lessons are never touched. CLIENT - CourseDetail.tsx: gate screen, settings query, unloc…889e7bd -
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
2 days ago
-
feat(notifications): one-tap deep links — every actionable notification opens its action screen
Z UserOwner directive 2026-12-01: clicking a notification must OPEN the place its action happens on (e.g. a join request lands straight on the accept/reject queue), not just flip a read flag. Root fixes: - server: approval fan-out url /admin?tab=users (renders the DASHBOARD tab under path-based routing) -> /admin/users?approvals=1; email dashboardUrl fixed the same way; approval-accepted notice /login -> /dashboard - client: src/lib/notification-link.ts — one resolver for every event (scheme safety + legacy ?tab= normalization + structured-payload fallbacks so a join request can NEVER render link-less), fully unit-tested - toast: the CARD body is clickable now (onOpen + keyboard support), join requests get a 'مراجعة الطلب' action button and 12s dwell - bell rows normalize legacy persisted urls before opening; 'افتح' affordance - push-sw: notificationclick posts the SPA path form (absolute URLs were silently dropped by the page handler) + legacy url normalization - /admin/users?a…6da4d8e -
feat(admin): one-shot bulk approve/reject + professional acceptance notification for approved users
Z UserBULK DECISIONS (owner directive 2026-12-01): the approval queue gains checkbox-per-row + select-all (up to the whole 200-row queue) and two confirm-guarded one-shot buttons. Both procedures route EVERY row through the SAME decideApproval state machine (no duplicated security logic): approve only lifts pending rows, reject skips protected admins, one bad row degrades to a skip entry instead of aborting the batch, duplicates collapse, and the batch is capped at 200 (aligned with the queue page). ACCEPTANCE NOTICE (owner directive 2026-12-01): when a user is approved they now receive a professional notification through BOTH channels that can actually reach them: 1. a dedicated bilingual acceptance email (verdict banner + one sign-in CTA, built from buildAccountApprovedEmail) riding the email_delivery_log ledger as 'approval-accepted' with one transient retry, and 2. an in-app stream event greeting them the moment they sign in. The notice rides decideApproval itself — d…264507b -
fix(spa): /admin/:tabId deep links served the soft-404 — admin tabs are real routes now
ahmdelbaz28-uxFollow-up to 0d070f3 (URL-synced admin tabs): the SPA handler's route whitelist (seo-meta) only knew the bare /admin path, so refreshing or deep-linking /admin/users answered HTTP 404 + noindex (soft-404 prevention misfiring on a brand-new valid route — caught by the post-deploy verify). - isKnownSpaRoute: /admin and /admin/<lowercase-tab> are known SPA routes. - isNoindexPath + robotsDirectiveFor: every /admin/<tab> page is owner-only — noindex, nofollow (not just the bare /admin). - Regression tests: deep links accepted, malformed paths still 404. Verified: tsc clean, build clean, 1437/1437 tests (89 files).a884b4f -
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
3 days ago
-
refactor(architecture): deep-module chat-context assembly + lane-parity guard
Z Userimprove-codebase-architecture round (top recommendation, implemented): - NEW api/lib/chatbot-context.ts — the deep module: ONE prompt-assembly recipe (assembleChatContext: signal -> saadat -> cables -> refs -> getSystemPrompt) and ONE citation composition (enforceAllCitations: pinned -> cables -> refs, appendOnly for the stream seam), behind a small named-option interface. The 13-positional-arg getSystemPrompt dance is no longer any caller's problem. - 5 hand-copied assembly sites collapse to one call each: chatbot.ts buildCascadePrompt (keeps its v3.9.2 cablesCrossGate), chatbot-stream.ts pickWorkingModel / vision pass-2 (routingFloor=true, vision=true) / BYOK lane / dynamic-router lane. - 2 hand-copied enforcement sites collapse: chatbot.ts finishSaadatCitation and chatbot-router.ts emitEnforcedCitations (appendOnly). - NEW parity test (25 cases): byte-identical systemPrompt / routingSignal / cablesIntentActive vs a verbatim copy of the historical recipe across…8ed78fa -
fix(lint): lint-all round — zero eslint warnings repo-wide
Z User- local-auth-router: cleaned verification results built explicitly (no throwaway destructured diagnostics vars); behavior identical — the non-admin response carries only success + message on both sites - Profile.tsx: session-scoped emailChangePending read via a lazy useState initializer instead of setState-in-effect (no cascading render on mount) - scripts: dropped unused bindings (streamDone IIFE inlined, t0, label param, size fn, before35ThinkingAr) - profile-email-flow regression guard tracks the equivalent cleaned return literal eslint: 11 warnings -> 0. tsc -b + ultracheck + biome stay clean.d28fca5 -
fix(sonar): wave 14b — S7503 consumeOrThrow is sync (no await inside)
security-auditd40062b -
fix(sonar): wave 14 — S3776 checkRateLimit helper + S6582 optional chain
security-audit- rate-limiter.ts S3776 (cognitive 22 > 15): the register-flood-backstop block pushed checkRateLimit over the bar. Extracted the shared limiter-rejection handling into consumeOrThrow() used by all three branches (register backstop / per-action / global) — behavior identical, each branch keeps its own user-facing message via the message builder. - local-auth-router.ts S6582: boolean-context 'user && user.passwordHash' -> 'user?.passwordHash' (same narrowing, same behavior).e1b6199 -
fix(security): security-audit wave 2026-11-30 — 6 root-cause repairs
security-auditCloudflare security-audit-skill full review (4 hunter units: auth/sessions, access-control, injection/SSRF, client+config). Confirmed findings fixed: - google-only-account-500 (low): NULL passwordHash rows surfaced a distinct, delay-free, unthrottled HTTP 500 that confirmed 'username exists with no local password'. Now routed through the dummy-hash lane -> uniform 401 + per-account throttle. - platform-cascade-dns-pinning (medium): the platform provider cascade (chat stream/non-stream + /models discovery + admin test) validated the baseUrl string only — a rebinding hostname could aim the key-bearing POST at an internal target. All three dials now go through pinnedPublicFetch (same DNS-pinned egress the BYOK lane already uses). - gis-nonce-binding (low): GIS ID tokens were accepted without a nonce, so a captured token could be replayed within its 1h validity. Login/Register now generate a CSPRNG nonce at google.accounts.id.initialize time, echo it in the POST, and t…2c0a4c0 -
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 12 — readiness follow-ups + E2E flake root fix
ahmdelbaz28-uxFollow-up wave from the 2026-11-30 production-audit re-scan: - api/boot.ts (S3776): extract runBootMigrations(), stopBackgroundWorkers() and createShutdownHandler() to module scope — start() back under the cognitive-complexity bar, behavior identical. - api/health-router.ts (S3776): extract gatherChecks() — the /health route now only decides cache-vs-fresh, overall status and the payload. - scripts/ui-test-server.mjs (S3776): extract readTrpcPostBody() — the tRPC stub router loses its nested stream-callback complexity. - deploy.sh (S7689): drop shell-style backticks inside the staging banner. - tests/e2e/features/payment-funnel.spec.ts (S5906): toHaveLength(1) instead of a generic equality assertion. - tests/e2e/features/desktop-recovery.spec.ts (FLAKE ROOT FIX): loadCount() raced the recovery-flow reload — a destroyed execution context failed the whole expect.poll cycle (~1-in-3..6 repeats, proven pre-existing on HEAD: 2/6 failures without any wave-12 change). Context…78d1cd7 -
fix(readiness): production-audit wave 2026-11-30 — launch-readiness repairs
ahmdelbaz28-uxRoot-cause fixes from the e2e-testing + production-audit tour: 1. db-init.ts (v19 destructive migration): refuse DROP TABLE quizQuestions when a runtime COUNT(*) shows rows — the old drop trusted an authoring-time 'verified empty' claim and would have silently destroyed student quiz data on future schema drift. Migration outcome is now tracked (getMigrationOutcome) and failures reset migrationDone so boot retries are real retries. 2. boot.ts: migration retry loop (3 attempts, backoff) + completed graceful shutdown — stop Telegram poller / YouTube watcher / email-drip scheduler, bounded close (4s keep-alive eviction, 8s forced exit), drain both MySQL pools. SIGTERM teardown no longer hangs until the platform kill timeout. 3. health-router.ts: new checks.migrations — a failed boot migration is now VISIBLE (unhealthy -> 503 -> orchestrator restart) instead of a silent warn. 4. payment-router.ts: (a) production refuses Paymob intents while a *_test_* secret k…5cc2c97 -
fix(sonar): wave 8 - final sweep, all 21 remaining live findings
Z User- S8689/S5144: documented sanitizer/authority invariants (redact() contract, fixed-hostname + origin-form) - taint-model blind spots, NOSONAR justified - S3776 x3: extract collectNormalizedMessages, verifyRightsAndSweep, ReviewsHeader (16 -> <=15 each) - S8786/S5843: extract_refs_kb trailing-number + kW token validators (differential-fuzz equivalent: 0 mismatches / 200k cases), redact() regex linearized in both probe scripts, HEAD_RE_PARTS regrouped (0/60k) - css:S7924 x2: cyan-500 -> cyan-400 at the flagged rules (4.5:1 cleared) - S7503/S3626 write-strategies, S6582 worker, S4323 cables aliases, S7786 TypeError, S2486 comment style Verified: tsc clean, eslint clean, vitest 1394/1394, py_compile clean.5632e3b -
fix(sonar): wave 7 - cleanup round from live scan (93 findings across 65 files)
Z User- 34 in-scope follow-ups exposed by the 17:59 scan (refactor residuals: S3776 helper splits, S4323 type aliases, S6759 readonly on extracted components, S8786 bounded-regex justifications, S6551 scrub patterns, S9440/S7924 CSS at new positions) - python leftovers: 29x S1481 positional _, S8786 regex canonicalization (fuzz-verified), S3776 task24 step-fn hoisting, S1192 dialog/content-type consts - operator tooling: S9382 documented NOSONARs for deliberate poll/throttle loops + Promise.all for independent probes, S8689 second log site routed through redact(), S5144 second fetch site behind UPSTREAM_HOST_ALLOWLIST Verified: tsc clean, vitest 1394/1394, node --check + py_compile on touched scripts.6780540 -
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 -
fix(sonar): wave 4 - resolve 114 findings (payment-router, sld render/repair, chatbot-prompts, cache, Register, ArticleDetail, chat-format, user-ai-provider, image-quota, email, chatbot-errors, push-state, Footer, notes-router, local-auth, think-filter, settings/maintenance/paymob routers, youtube-watcher, referral, env)
Z User- S3776 extractions (getSystemPrompt via SystemPromptArgs, chatbot-prompts 51->15, email OTP verify flow, local-auth register/login/updateProfile) - S9382: NOSONAR only for documented sequential necessities (Redis SCAN pagination, bulkUpsert pool cap, ordered SQL dump, oEmbed concurrency pool) - S8786: credential regex de-duplicated quantifiers, email validator split, UA WebView regex preserved via differential corpus test - S6551: describeCause/JSON diagnostics; S6759 readonly props; S5906 in tests - contract tests re-pinned to helper-based equivalents (2FA helper call site, finalizeEmailVerification pendingEmail flow, changeEmailWithVerification rate-limit-inside-branch) - all runtime invariants unchanged Verified: tsc clean, eslint 0 errors, vitest 1394/1394.da57150 -
fix(sonar): wave 3 - resolve 100 findings (medium files: health-router, seo-meta, chatbot-stream, CourseDetail, docgen spec/md/font, AiProvidersPanel, SubscribeGate, spa-handler, Articles, AdminNotificationPanel, Documents, NotificationCenter, playlist-sync, approval, chatbot-feedback, chatbot-byok, boot)
Z User- S3776 extractions across components and lib (NotificationCenter push flow 55->11, Articles 41->6, AdminNotificationPanel 22->1, playlist-sync 34->7) - S3358 nested ternaries -> module helpers/sub-components - S9382: Promise.all for independent writes; NOSONAR only for the notify-cap throttle in playlist-sync - S8786: trailing-slash regexes -> shared stripTrailingSlashes loop - S6551: JSON diagnostics; S4782/S6564/S6660/S7737/S7773/S7503/S7737 - approval contract test adapted to Promise.all admin fan-out (same pins) Verified: tsc clean, eslint 0 errors, vitest full suite green.caa8f36 -
fix(sonar): wave 2 - resolve 112 findings (CourseReviews, telegram-bot, saudi-kb, chatbot, shape, css, refs.test)
Z User- CourseReviews: S3776 40->14 via label helpers, S3358, S6759 readonly props - telegram-bot: S3776 extractions (splitForTelegram, handlePrivateMessage, pollLoop, supervisorBody), S9382 throttle NOSONARs, S7503 de-async, S4782, S6582; retry_after sleep removed from loop - chatbot-saudi-kb: S7780 String.raw x12 - chatbot.ts: S3776 cascade/sweep extractions, S107 bundle, S4123 sync validators, S6551 JSON.stringify diagnostics - docgen/shape.ts: bidiRuns decomposed (95->~2), S3358/S4323/S7755, docgen output pinned by existing tests - index.css + elite-animations.css: S9440 consolidated prefers-reduced-motion blocks, S9449 explicit transition properties, S4666 merged duplicate selectors, S9450, S7924 contrast fixes - chatbot-refs.test.ts: S5906 toHaveLength assertions Verified: tsc clean, eslint 0 errors, biome clean, vitest 1394/1394.c2dde89 -
fix(sonar): wave 1 - resolve 511 in-scope findings across 15 app files
Z UserRoot-cause refactors per SonarCloud rules (behavior-preserving): - S3776 cognitive complexity: extracted cohesive helpers in ai-router, chatbot-router, chatbot-refs, chatbot-cables, Admin, ChatBot, skillnet, saadat, pdf, db-init, chat-render, Profile - S3358 nested ternaries -> Record lookups / if-chains / bilingual helper - S7780 String.raw for regex-source literals; S7781 replaceAll - S6594 match->exec / matchAll; S6557 startsWith/endsWith; S7755 .at() - S8786 backtracking: split overlapping-quantifier regexes (citation, refusal, promise/delivery detectors), linear rewrites, documented bounded-pattern NOSONARs where grammar is provably linear - S9382: Promise.all for independent DB upserts; documented NOSONAR for order-dependent/throttled loops only - S3923 real bug: identical-branch ternary in chatbot-cables depthFactor - S6551: honest typed rows instead of String(object) in db-init/sld fence - Source-contract tests re-pinned to the refactored equivalents (admission-gate…9ce5991
7 days ago
-
test(chatbot): instant-lane Groq expectation follows the refreshed catalog head
ahmdelbaz28-uxGROQ_MODELS now leads with openai/gpt-oss-120b (current production reasoning id) — the instant routing test's first-live-id winner is the new head, not the old llama-3.3-70b-versatile.a684df8 -
fix(chatbot): NVIDIA legacy cascade + honest failure logs + Groq catalog refresh
ahmdelbaz28-uxROOT CURE (owner report 'الشات بوت يرجع 503 — كل المزودات فشلت' / deploy live-probe red 9/12 with UPSTREAM_EXHAUSTED since the 2026-11-26 build): Diagnosed live (Space logs 14:19-16:25 UTC + provider-probe run #37): - kilo (PRIMARY gateway): HTTP 401 'Your authentication token is invalid' — key rejected BOTH on GitHub mirror and the Space (owner rotation needed). - NVIDIA legacy lane: dialled ONE hardcoded id (minimaxai/minimax-m3) whose catalog entry drifted; every failure was non-auth (!ok) and SILENT (no log), driving nvidiaConsecFails past the breaker so the tier sat in permanent 2-minute cooldowns with ZERO log evidence. - OpenRouter: key healthy; daily free-quota breaker + HTTP 402 on the paid web plugin — account credits exhausted (resets UTC-midnight / owner top-up). - Groq: key healthy; sweep led with ids Groq deprecated (qwen3-32b + llama-4-scout per the 2026-06-17 deprecation email) or superseded. Fixes: - chatbot.ts: NVIDIA_MODEL single id -> NVIDIA_MODELS liv…b869b30 -
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 -
fix(owner-contact): correct owner email handle everywhere — ahmedelbaz28 → ahmdelbaz28
The admin-approval alert fallback (api/lib/approval.ts adminAlertEmail()), the live-e2e/log-proof probe docs, the perf probe BASE URL (dead host ahmedelbaz28-ahmdrtap.hf.space → ahmdelbaz28-ahmdrtap.hf.space) and the DEPLOYMENT.md owner handle all carried a one-letter typo ('e' after 'ahmd'). The Space secret ADMIN_ALERT_EMAIL was overwritten with the correct inbox in the same round (values live outside the repo by policy).621f56a -
feat(email): delivery verdicts surface in the dashboard — silent alert failures impossible
Z UserOwner report: 'the registration-approval email never reached my inbox and nothing ever told me.' Root cause: sends are best-effort and the outcome lived only in server logs the owner cannot read. - migration v22: bounded email_delivery_log ledger (class, masked recipient, ok, provider status, safe reason; 14-day prune) - email.ts: every send outcome recorded best-effort (config/network/4xx/5xx classes); network errors now a classified, ledgered failure instead of an unhandled rejection - approval.ts: alert email sends FIRST with ONE transient retry (network / 5xx only), then the in-app admin notification carries the real verdict — 'sent to your inbox' or the exact provider reason + approve-from-dashboard guidance - admin-users.ts: emailDeliveryLog query (last 10 outcomes, last approval alert, from address) — degrades to empty pre-migration - Admin.tsx: approval card shows a green/red verdict banner with the provider reason + one-click re-send, plus a mini delivery ledg…37e6657 -
chore(lint): restore import order in db-init.ts after audit run-3 merge
Z UserBiome organizeImports flagged the eviction import the security agent appended at the bottom of the block. Safe fix only: the import (with its SECURITY FIX comment, kept verbatim) moves into its sorted position. No semantic change. Verified on the merged state: biome 0 errors, tsc clean, eslint 0 errors, vitest 1391/1391, vite build OK, runtime probes 12/12 + 26/26.12a144f -
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 -
fix(approval-gate): verified ≠ approved — the admin dashboard now shows the REAL entry state everywhere
Z UserOwner report (2026-11-26): "a user complains that despite being logged in and his email confirmed by the admin, every visit asks him to log in again — the platform does not remember him." ROOT CAUSE (code + live server logs): The admin approval gate (owner directive 2026-11-24, "لا يدخل أحد للمنصة بدون تأكيد الإيميل من الأدمن") fail-closes EVERY session issuance on users.approvalStatus === 'approved' — local login, Google OAuth callback, AND every live request (context.ts loadUserFromDb). "Email confirmation" (emailVerifiedAt — the self-service link/OTP flow) is a fully independent milestone that NEVER touches approvalStatus. The live log captured the exact victim: [GoogleAuth/OAuth] "Sign-in refused by approval gate — userId 5, gate: pending" minutes after the last deploy. The account was verified but never admin-approved → every login attempt bounces → "asks me to log in every time". The session pipeline itself (30-day sliding cookies, grace-window renewal, flag-cookie self-heal) wa…d28c7f4 -
feat(avatar): profile photo now surfaces in chat bubbles and course reviews
Z UserOwner request (2026-11-26): the photo uploaded from the profile page (31baaf4) should follow the user across every social surface — chat messages and course reviews — not just the profile/navbar. Server: - review-router.listByCourse now projects userAvatar (users.avatar) with each published review; the sibling lesson-comments router already returned it, so the review list was the odd one out. Client: - CourseReviews.tsx: reviewer avatar circle renders the real photo when set (lazy/async, cover-cropped), initials circle stays the fallback for reviewers without a photo — identical geometry, no layout shift. - ChatBot.tsx: MessageBubble gains a stable userAvatar prop (memo-safe — changes only when the user actually changes their photo); user bubbles wear the real photo in place of the generic User icon chip, icon chip remains the fallback. Assistant bubbles keep the site logo. Admin moderation tables intentionally keep compact initials (moderation rows…2e6a64d -
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 -
fix(notifications): compact mobile toast cards — YouTube bursts no longer wall off the screen
Z UserOwner report (2026-11-26): the YouTube new-episode toast shown on platform entry rendered a very tall card on phones; a multi-event burst stacked up to four of them and covered the entire screen. Root cause (measured): two independent inflators — 1. the broadcast copy carried a ~200-char marketing tail, so one card rendered ~7 text lines ≈ 220px tall 2. the card was a fixed 320px-wide, unclamped box and the stack allowed 4 toasts on every viewport; on a phone that is 800px+ of glass Fix — client (NotificationToast.tsx): - card is fluid-width on mobile (full width minus 32px margins), p-3, 28px icon, message line-clamp-2, title line-clamp-1; ≥sm unchanged (320px, p-4, message line-clamp-3) - responsive stack cap via matchMedia (jsdom-safe fallback): max 2 toasts on mobile, 4 on desktop; displaced events stay in the bell history — a toast is not an inbox - container gains left+right margins on mobile (no overflow on narrow screens) and pointer-ev…2c2b16c -
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 -
security(audit-run1): fix all 9 confirmed findings + harden both needs_validation leads
ahmdelbaz28-uxConfirmed fixes (each with regression tests): - quiz.submit duplicate-questionId score inflation: zod refine rejects duplicates + pure deduplicating scorer (quiz-scoring.ts) + 100% clamp [M] - vision daily quota check-then-increment race: atomic reserve-then-refund (SELECT...FOR UPDATE tx + refund on every failure path) [M] - certificate grade gate passed-only denominator: average now runs over EVERY published quiz lesson (missing attempts = 0) - quiz read/submit missing course-level publish gate (join courses) - comments.list lifecycle drift (lesson+course publish joins) - last-admin guard race-to-zero-admins: conditional atomic demote (guard travels with the write; derived-table count) - yt-sync legacy body-only HMAC lane retired (STEP 2): auth extracted to unit-tested lib/yt-sync-auth.ts; requests without x-sync-ts hard-401 - push subscription cap TOCTOU: cap check + insert in one FOR UPDATE tx - Dockerfile: base image pinned to immutable digest Hardening (needs_validatio…2329257 -
feat(email): monitored Reply-To on every outbound mail — deliverability + real reply path
ahmdelbaz28-uxMailbox providers score no-reply senders with no answer path worse; setting reply_to = ADMIN_ALERT_EMAIL (when configured) both raises trust and routes genuine replies to the owner's inbox. No behavior change when the variable is unset.607a211 -
fix(db): parse mysql2 result TUPLE in quizQuestions probes — drift block never executed
ahmdelbaz28-uxc.execute() returns [rows, fieldPackets]; casting the TUPLE as the rows array made .cnt always undefined, so tableExists/lessonsExists/fkExists were permanently false: the DROP+rebuild never fired, CREATE IF NOT EXISTS was a silent no-op on the drifted table, and the FK was never added. rowsOf() now unwraps the tuple (same bug shape db-migrations.firstResultRow already documented). With correct parsing, the extra legacy correctOptionIndex column triggers the rebuild and admin INSERTs recover.3ecba8a -
fix(db): detect EXTRA legacy columns in quizQuestions — correctOptionIndex blocked every INSERT
ahmdelbaz28-uxquizStorageSelfTest revealed the true cause: ER_NO_DEFAULT_FOR_FIELD (1364) on 'correctOptionIndex' — a legacy column NOT in the drizzle schema, NOT NULL without a default. Previous repairs added missing declared columns (healing SELECTs) but the extra column kept ER_NO_DEFAULT_FOR_FIELD killing every INSERT. v19 drift detection now rebuilds when the column set differs in EITHER direction (missing OR extra) or id lacks AUTO_INCREMENT.87a5b16 -
feat(admin): quizStorageSelfTest surfaces mysql2 cause chain (code/errno/sqlMessage)
ahmdelbaz28-uxdrizzle wraps driver errors in 'Failed query: ...' — the diagnostic must report code/errno/sqlState/sqlMessage from err.cause, not just the wrapper.37908e8 -
feat(admin): quizStorageSelfTest — canary INSERT/SELECT/DELETE with raw driver errors
ahmdelbaz28-uxAdmin quiz paths return generic 500s; the audit trail stores no error text and HF logs are not operator-accessible. This admin-gated diagnostic runs the full write path against quizQuestions with a real-lesson canary and returns the underlying driver message per step, so storage drift is diagnosed from the dashboard instead of guessed.50b76a6 -
fix(db): drop+rebuild drifted quizQuestions table — deterministic repair, verified empty
ahmdelbaz28-uxThe AUTO_INCREMENT MODIFY (60b6869) did not heal admin.createQuizQuestion: the legacy table's exact shape stays unknown (SELECT healed, INSERT still 500s). Live probes across ALL 7 lessons confirm quizQuestions holds ZERO rows — the admin INSERT path never worked, so nothing was ever persisted. v19 now: probes columns+EXTRA, and on ANY drift (missing declared column OR id without AUTO_INCREMENT) DROPs and recreates the table in the exact drizzle shape, then guarantees qq_lesson_idx + fk_qq_lesson_id. Lossless on an empty table, and idempotent on future boots (perfect shape = no-op).821916c -
fix(db): quizQuestions.id AUTO_INCREMENT drift — INSERT path still 500'd after column repair
ahmdelbaz28-uxadminQuizByLesson (SELECT) healed by fc09fb3, but createQuizQuestion (INSERT omitting id) still 500'd: the drifted table's id PRIMARY KEY lacks AUTO_INCREMENT ('Field id does not have a default value' in strict mode). v19 now probes INFORMATION_SCHEMA.COLUMNS.EXTRA for quizQuestions.id and MODIFYs it to AUTO_INCREMENT when absent.60b6869