Spaces:
Running
Running
Commit History
Today
-
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 -
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): 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(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
4 days ago
-
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(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 -
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 -
fix(db): repair quizQuestions column drift — admin quiz paths 500'd while student path worked
ahmdelbaz28-uxFollow-up to 61537e6: production's quizQuestions table EXISTS but is missing drizzle-declared columns. Evidence from the live sweep: - quiz.byLesson (student) 200 OK — it projects only 7 columns - admin.adminQuizByLesson / createQuizQuestion 500 — db.select() / INSERT touch ALL drizzle columns (correctIndex / sortOrder / createdAt suspects) - CREATE TABLE IF NOT EXISTS was a silent no-op on the drifted table Fix: v19 step now probes INFORMATION_SCHEMA.COLUMNS for every drizzle-declared column and ALTER-ADDs the missing ones (drift repair), then guarantees qq_lesson_idx + fk_qq_lesson_id (FK probed via REFERENTIAL_CONSTRAINTS).fc09fb3 -
fix(db): create quizQuestions table on boot — admin quiz endpoints 500'd in production
ahmdelbaz28-uxROOT FIX (admin dashboard full audit, 2026-11-25): adminQuizByLesson (and every quiz admin mutation) returned 500 on production for ANY lessonId — the quizQuestions table existed only in the drizzle schema (db/schema/courses.ts) and in drizzle-kit push, but the production boot path (api/lib/db-init.ts) never created it. Playwright sweep + live tRPC probes confirmed: SELECT on quizQuestions → unhandled DB 'table doesn't exist' error. Fix: declarative ledger migration v19-quiz-questions-table — - CREATE TABLE IF NOT EXISTS quizQuestions (exact drizzle shape: columns, defaults, qq_lesson_idx) - FK fk_qq_lesson_id → lessons(id) ON DELETE/UPDATE CASCADE, probed via INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS (FKs do not appear in STATISTICS, so indexExists() cannot see them) - idempotent: re-runs every boot, no-ops when present61537e6
9 days ago
-
fix(chatbot-gating): citation-stamp side honors the shared loading predicate — no Elsewedy stamp on suppressed Saudi-DPS answers (v3.9.2 follow-up)
ahmdelbaz28-uxLive E2E finding on the deployed v3.9.2: a Saudi-DPS load question got '[Elsewedy Electric — Power Cables Catalogue, Table 3, p16]' appended — enforceCablesCitations resolved citations from the query WITHOUT knowing the cables KB had been cross-suppressed (citation without source, stamped server-side on both the chatbot.ts success path and the chatbot-router.ts stream seam). Root cure: cablesBlockLoads(query, refsRouteActive) is now the SINGLE source of truth — the builder (prompt side) and the enforcement (stamp side) share it; the enforcement recomputes the cross-flag deterministically from the query (hasRefsIntent && routeRefsQuery(...).docs.length>0), which fixes both call sites with zero signature churn. One-way import cables→refs (no cycle; verified refs never imports cables). - Regression test: suppressed Saudi answer stays stamp-free; genuine cables question still gets its mandatory stamp. Full suite: 1301 passing.c43d59e -
fix(chatbot-gating): cross-domain suppression — Saudi-DPS/catalogue questions never drag the Elsewedy/EgyCode KB (v3.9.2)
ahmdelbaz28-uxOwner discipline 'no unimportant file reads' (2026-11-24 audit): generic load words («محركات», «إنارة», «معامل الطلب») in hasCablesIntent made a Saudi-DPS load calculation pull the Elsewedy catalogue + Egyptian-Code guiding volume (~4.6k chars of off-target tokens from the wrong source). - Cross-gating is now symmetric: refs already received cablesIntentActive (excludes elsewedy/egycode corpora); cables now receives refsRouteActive (hasRefsIntent && routeRefsQuery(...).docs.length>0, computed in chatbot.ts) and stays EMPTY unless the query names an explicit cable noun (CABLE_NOUN_RE: كابل/مقطع/السويدي/أمبيراسية/مم²/xlpe/نحاس…). - Integration preserved: 'Saudi load calc + choose cable cross-section' loads BOTH cores; suppression fires only on bare load words. - Backward compatible: calls without the flag keep the legacy behavior. - PROMPT_VERSION 3.9.2 + changelog; new contract test in chatbot-cables.test.ts; permanent audit script scripts/routing-integration-audit.ts (66…ea73420 -
fix(chatbot-docgen): EXPLICIT-REQUEST-ONLY hard gate — no unsolicited file generation, no suggestions (v3.9.1)
ahmdelbaz28-uxOwner directive (2026-11-24, absolute): the permanent file-generation capability stays, but it must NEVER fire without an explicit user request, and the bot must NEVER suggest or offer file generation. - docgenSkillAr/En: removed the auto-trigger clause («يستحق ملفاً» / 'long/tabular enough to deserve one') — long or tabular answers now stay plain prose with no docgen board; added THE FUNDAMENTAL CONDITION block (explicit request = the only key, no self-initiated generation, no suggestion/offer/hint ever, format-name-only mention → prose answer, format follows the user's request verbatim with pdf as the only default when a file IS explicitly requested but no format is named). - Removed the post-delivery offer-to-convert clause («اعرض تحويلها» / 'offer the other on request') — one file per reply, never offer another format; the user asks for it themselves. - docgenQuickAr/En (instant lane): same hard gate in condensed form. - ChatBot.tsx welcome messages (EN+AR): remove…cc06b18 -
feat(chatbot-docgen): permanent in-chat document generation — PDF/DOCX/MD (v3.9.0)
ahmdelbaz28-uxOwner directive (2026-11-24): the bot must ALWAYS be able to build real files for the user inside the chat — no external skill loading, ever. - docgen skill 'docgen-file-export' in SKILL_REGISTRY (category export, thinking+instant): routed on file/export intent, emits a ```docgen DocSpec fence with the immediate-execution contract (file in the FIRST reply, verified numbers only, mandatory citations). - api/lib/docgen/: dependency-free deterministic renderers — PDF written from scratch (Type0/Identity-H CID fonts, two embedded GNU FreeFont subsets, full Arabic presentation-form shaping + simplified UAX#9 bidi with N0 bracket-pair + N1/N2 neutral resolution, RTL tables, page footers), DOCX as stored-ZIP OOXML (bidiVisual RTL tables, w:bidi paragraphs, Word-native shaping), and GFM Markdown. - POST /api/docs/gen: public, stateless, size-capped (60k content chars), typed 422 diagnostics — the /api/diagrams/sld contract. - Chat UI: renderDocgenFence download card (format …aea6c23 -
fix(chatbot): agent-architecture audit (layers 3/6/10) — routing noise, refs ownership, block coherence, rendering contract E2E, post-deploy live probe
ahmdelbaz28-uxSkills applied: agent-architecture-audit + e2e-testing + systematic-debugging (+ the ci-cd gates pattern), per the owner's token-burn minimization mandate. AUDIT FINDINGS → FIXES (evidence-backed, code-first): 1. Layer 6 (routing discipline) — keyword hygiene: single generic words fired whole domain cores on unrelated questions ('قاطع' lit saudi+schneider on a generic breaker-vs-disconnector question; 'قصر' lit the Saadat pack on a cables question; 'كود' lit cables on a SAUDI-code question; 'kva' lit ABB on any load question; 'توليد/نقل/توزيع' lit Gilany on anything). Removed the generic tokens from the keyword lists — the specific PHRASES keep every intended contract (all skillnet tests green untouched). 2. Layer 6 (coherence) — forced co-selection: a dynamic RAG block can never ride without its protocol block anymore (getSystemPrompt force-includes saadat/cables/the exact refs skills when their context block is present). 3. Layer 3 (context routing) — refs ow…0916f03 -
fix(chatbot-refs): chassis/fixture parts must never win device selection — NON_DEVICE_RE guard + live-proof script for the references layer
ahmdelbaz28-uxLive E2E finding: the cheapest '1600A 3P' item was ENW116C3MC00H — a CHASSIS ALONE part (91,303 EGP), not a breaker. Device-kind selection now excludes chassis/chaasis/fixture/interlocking/set-of/adaptation lines (accessory kind keeps them). 44 tests green.ce629f4 -
feat(chatbot-refs): technical-references expert core — Saudi DPS-01 + ABB transformers + Schneider Egypt price list 2026 + full page index of all 7 documents
ahmdelbaz28-uxUser requirement: the bot OWNS the reference documents in its knowledge base, answers with proof from the file, picks the right catalogue ITEM (Product ID + full data + price) and routes every question through an index so tokens are never burned on wrong files. NOTHING is omitted from any document. New knowledge bases (GENERATED, cell-verified by scripts/extract_refs_kb.py): - chatbot-saudi-kb.ts — SEC DPS-01 (46p): area tables 3-6 (84/90/62/75 rows, CB bands via the +1-boundary rule verified against printed anchors), density tables 7-10, demand factors (29), coincidence factors CF(1..99), types C1-C29, 21 curated rules, printed §-index. - chatbot-abb-kb.ts — ABB catalogue (51p): 61 small + 36 medium oil designs, 6 large typical datas, 112 dry VCC/RESIBLOC loss rows, 40 IP00 dimension rows, tank glyph decode (L=▲ hermetic, G=● conservator), suspected print errors kept verbatim + flagged. - chatbot-schneider-kb.ts — price list 2026 (319p, 8 TOC parts): 3264 priced items p…14cbffb -
fix(chatbot-cables): strict type-check compliance (ultracheck) — quoted csaLabel emission, CablesHit.citationEn, widened Code data records
ahmdelbaz28-ux- generator: fmt_num now emits string values via json.dumps (csaLabel: "4" instead of bare 4 / accidental division expression for reduced-neutral labels like 25 RM / 16 RM) - CablesHit gains citationEn (EN citation prefills + enforcement) - CableAmpacityRow → Record cast via unknown (TS2352 under strict) - EgyCodeSection.data widened to admit per-key load-capacity records - test cleanups (non-null ground assert, drop stray __internal probe)25ec22e -
feat(chatbot): cables & Egyptian-Code expert core — Elsewedy KB + deterministic sizing engine + citation contract
ahmdelbaz28-uxSources saved as retrievable, citable knowledge (user requirement: the bot must reference and CITE the Egyptian Code and the Elsewedy catalogue, and size cable sections from its own verified calculations): - chatbot-cables-kb.ts (AUTO-GENERATED from Power Cables.pdf via scripts/extract_cables_kb.py + scripts/gen_cables_kb_ts.py): 20 LV/MV ampacity tables (291 rows, page-cited), short-circuit tables 14-17, voltage-drop 18-19, derating 3-13, AWG/Cu-Al conversions, the catalogue's own formulas + selection guidance. Suspect catalogue misprints preserved verbatim + flagged (sc_cu_pvc 10mm² air-touched '9', Table 11 '0.98'). - chatbot-egycode-kb.ts: 18 clause-cited sections from the Egyptian Code design volume (Ch1 loads, Ch2 lighting eq 2-1, Ch8 cable routes/trenches/ conduit fill 40%+10%/trays 50%/inspection rooms, Ch9 power factor). - chatbot-cables.ts (expert layer, Saadat pattern): bilingual intent gate, BM25 over the combined corpus (keywords-only index + Arabic prefix…51ac820