mirror of
https://github.com/koala73/worldmonitor.git
synced 2026-04-25 17:14:57 +02:00
main
57 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
53801cae5c |
fix(csp): allow Stripe 3D Secure frames + consolidate Dodo CSP entries (#2806)
Dodo Payments uses Stripe under the hood for card payment 3D Secure verification. hooks.stripe.com and js.stripe.com were not in frame-src or script-src, causing the payment overlay to fail with CSP violations. Consolidated individual Dodo CSP entries (checkout.dodopayments.com, test.checkout.dodopayments.com, *.hs.dodopayments.com, etc.) into a single *.dodopayments.com wildcard per Dodo's recommended allowlist. |
||
|
|
6148d4ca75 |
fix(csp): allow Dodo payment frames + Google Pay permission (#2789)
- frame-src: added *.hs.dodopayments.com, *.custom.hs.dodopayments.com, pay.google.com (Dodo payment iframe and Google Pay) - Permissions-Policy: payment now allowed for checkout.dodopayments.com and pay.google.com (was denied entirely) |
||
|
|
df18d2241e |
fix(csp): allow Dodo SDK from *.hs.dodopayments.com (#2647)
* fix(csp): widen Dodo SDK script-src to https://*.hs.dodopayments.com CSP blocked https://sdk.hs.dodopayments.com (Sentry 7368303076). Only https://sdk.custom.hs.dodopayments.com was allowed. Dodo SDK loads from both subdomains. Wildcarded to cover both. * fix(csp): add *.custom.hs.dodopayments.com for multi-level subdomain CSP wildcard *.hs.dodopayments.com only covers one subdomain level, so sdk.custom.hs.dodopayments.com (two levels) was still blocked. Added explicit *.custom.hs.dodopayments.com to cover both patterns. |
||
|
|
6a7749b126 | fix(csp): allow Dodo Payments SDK script origin in script-src (#2631) | ||
|
|
9893bb1cf2 |
feat: Dodo Payments integration + entitlement engine & webhook pipeline (#2024)
* feat(14-01): install @dodopayments/convex and register component - Install @dodopayments/convex@0.2.8 with peer deps satisfied - Create convex/convex.config.ts with defineApp() and dodopayments component - Add TODO for betterAuth registration when PR #1812 merges Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(14-01): extend schema with 6 payment tables for Dodo integration - Add subscriptions table with status enum, indexes, and raw payload - Add entitlements table (one record per user) with features blob - Add customers table keyed by userId with optional dodoCustomerId - Add webhookEvents table for full audit trail (retained forever) - Add paymentEvents table for billing history (charge/refund) - Add productPlans table for product-to-plan mapping in DB - All existing tables (registrations, contactMessages, counters) unchanged Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(14-01): add auth stub, env helper, and Dodo env var docs - Create convex/lib/auth.ts with resolveUserId (returns test-user-001 in dev) and requireUserId (throws on unauthenticated) as sole auth entry points - Create convex/lib/env.ts with requireEnv for runtime env var validation - Append DODO_API_KEY, DODO_WEBHOOK_SECRET, DODO_PAYMENTS_WEBHOOK_SECRET, and DODO_BUSINESS_ID to .env.example with setup instructions - Document dual webhook secret naming (library vs app convention) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(14-02): add seed mutation for product-to-plan mappings - Idempotent upsert mutation for 5 Dodo product-to-plan mappings - Placeholder product IDs to be replaced after Dodo dashboard setup - listProductPlans query for verification and downstream use Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(14-02): populate seed mutation with real Dodo product IDs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(15-02): add plan-to-features entitlements config map - Define PlanFeatures type with 5 feature dimensions - Add PLAN_FEATURES config for 6 tiers (free through enterprise) - Export getFeaturesForPlan helper with free-tier fallback - Export FREE_FEATURES constant for default entitlements Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(15-01): add webhook HTTP endpoint with signature verification - Custom httpAction verifying Dodo webhook signatures via @dodopayments/core - Returns 400 for missing headers, 401 for invalid signature, 500 for processing errors - HTTP router at /dodopayments-webhook dispatches POST to webhook handler - Synchronous processing before 200 response (within Dodo 15s timeout) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(15-02): add subscription lifecycle handlers and entitlement upsert - Add upsertEntitlements helper (creates/updates per userId, no duplicates) - Add isNewerEvent guard for out-of-order webhook rejection - Add handleSubscriptionActive (creates subscription + entitlements) - Add handleSubscriptionRenewed (extends period + entitlements) - Add handleSubscriptionOnHold (pauses without revoking entitlements) - Add handleSubscriptionCancelled (preserves entitlements until period end) - Add handleSubscriptionPlanChanged (updates plan + recomputes entitlements) - Add handlePaymentEvent (records charge events for succeeded/failed) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(15-01): add idempotent webhook event processor with dispatch skeleton - processWebhookEvent internalMutation with idempotency via by_webhookId index - Switch dispatch for 7 event types: 5 subscription + 2 payment events - Stub handlers log TODO for each event type (to be implemented in Plan 03) - Error handling marks failed events and re-throws for HTTP 500 + Dodo retry Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs(15-01): complete webhook endpoint plan - Update auto-generated api.d.ts with new payment module types - SUMMARY, STATE, and ROADMAP updated (.planning/ gitignored) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(15-03): wire subscription handlers into webhook dispatch - Replace 6 stub handler functions with imports from subscriptionHelpers - All 7 event types (5 subscription + 2 payment) dispatch to real handlers - Error handling preserves failed event status in webhookEvents table - Complete end-to-end pipeline: HTTP action -> mutation -> handler functions Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(15-04): install convex-test, vitest, and edge-runtime; configure vitest - Add convex-test, vitest, @edge-runtime/vm as dev dependencies - Create vitest.config.mts scoped to convex/__tests__/ with edge-runtime environment - Add test:convex and test:convex:watch npm scripts * test(15-04): add 10 contract tests for webhook event processing pipeline - Test all 5 subscription lifecycle events (active, renewed, on_hold, cancelled, plan_changed) - Test both payment events (succeeded, failed) - Test deduplication by webhook-id (same id processed only once) - Test out-of-order event rejection (older timestamp skipped) - Test subscription reactivation (cancelled -> active on same subscription_id) - Verify entitlements created/updated with correct plan features * fix(15-04): exclude __tests__ from convex typecheck convex-test uses Vite-specific import.meta.glob and has generic type mismatches with tsc. Tests run correctly via vitest; excluding from convex typecheck avoids false positives. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(16-01): add tier levels to PLAN_FEATURES and create entitlement query - Add tier: number to PlanFeatures type (0=free, 1=pro, 2=api, 3=enterprise) - Add tier values to all plan entries in PLAN_FEATURES config - Create convex/entitlements.ts with getEntitlementsForUser public query - Free-tier fallback for missing or expired entitlements Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(16-01): create Redis cache sync action and wire upsertEntitlements - Create convex/payments/cacheActions.ts with syncEntitlementCache internal action - Wire upsertEntitlements to schedule cache sync via ctx.scheduler.runAfter(0, ...) - Add deleteRedisKey() to server/_shared/redis.ts for explicit cache invalidation - Redis keys use raw format (entitlements:{userId}) with 1-hour TTL - Cache write failures logged but do not break webhook pipeline Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(16-02): add entitlement enforcement to API gateway - Create entitlement-check middleware with Redis cache + Convex fallback - Replace PREMIUM_RPC_PATHS boolean Set with ENDPOINT_ENTITLEMENTS tier map - Wire checkEntitlement into gateway between API key and rate limiting - Add raw parameter to setCachedJson for user-scoped entitlement keys - Fail-open on missing auth/cache failures for graceful degradation Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(16-03): create frontend entitlement service with reactive ConvexClient subscription - Add VITE_CONVEX_URL to .env.example for frontend Convex access - Create src/services/entitlements.ts with lazy-loaded ConvexClient - Export initEntitlementSubscription, onEntitlementChange, getEntitlementState, hasFeature, hasTier, isEntitled - ConvexClient only loaded when userId available and VITE_CONVEX_URL configured - Graceful degradation: log warning and skip when Convex unavailable Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(16-04): add 6 contract tests for Convex entitlement query - Free-tier defaults for unknown userId - Active entitlements for subscribed user - Free-tier fallback for expired entitlements - Correct tier mapping for api_starter and enterprise plans - getFeaturesForPlan fallback for unknown plan keys Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(16-04): add 6 unit tests for gateway entitlement enforcement - getRequiredTier: gated vs ungated endpoint tier lookup - checkEntitlement: ungated pass-through, missing userId graceful degradation - checkEntitlement: 403 for insufficient tier, null for sufficient tier - Dependency injection pattern (_testCheckEntitlement) for clean testability - vitest.config.mts include expanded to server/__tests__/ Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(17-01): create Convex checkout session action - DodoPayments component wraps checkout with server-side API key - Accepts productId, returnUrl, discountCode, referralCode args - Always enables discount code input (PROMO-01) - Forwards affiliate referral as checkout metadata (PROMO-02) - Dark theme customization for checkout overlay Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(17-03): create PricingSection component with tier cards and billing toggle - 4 tiers: Free, Pro, API, Enterprise with feature comparison - Monthly/annual toggle with "Save 17%" badge for Pro - Checkout buttons using Dodo static payment links - Pro tier visually highlighted with green border and "Most Popular" badge - Staggered entrance animations via motion - Referral code forwarding via refCode prop Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(17-01): extract shared ConvexClient singleton, refactor entitlements - Create src/services/convex-client.ts with getConvexClient() and getConvexApi() - Lazy-load ConvexClient via dynamic import to preserve bundle size - Refactor entitlements.ts to use shared client instead of inline creation - Both checkout and entitlement services will share one WebSocket connection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(17-03): integrate PricingSection into App.tsx with referral code forwarding - Import and render PricingSection between EnterpriseShowcase and PricingTable - Pass refCode from getRefCode() URL param to PricingSection for checkout link forwarding - Update navbar CTA and TwoPathSplit Pro CTA to anchor to #pricing section - Keep existing waitlist form in Footer for users not ready to buy - Build succeeds with no new errors Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: update generated files after main merge and pro-test build Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: prefix unused ctx param in auth stub to pass typecheck Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(17-04): add 4 E2E contract tests for checkout-to-entitlement flow - Test product plan seeding and querying (5 plans verified) - Test pro_monthly checkout -> webhook -> entitlements (tier=1, no API) - Test api_starter checkout -> webhook -> entitlements (tier=2, apiAccess) - Test expired entitlements fall back to free tier (tier=0) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(17-02): install dodopayments-checkout SDK and create checkout overlay service - Install dodopayments-checkout@1.8.0 overlay SDK - Create src/services/checkout.ts with initCheckoutOverlay, openCheckout, startCheckout, showCheckoutSuccess - Dark theme config matching dashboard aesthetic (green accent, dark bg) - Lazy SDK initialization on first use - Fallback to /pro page when Convex is unavailable Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(17-02): wire locked panel CTAs and post-checkout return handling - Create src/services/checkout-return.ts for URL param detection and cleanup - Update Panel.ts showLocked() CTA to trigger Dodo overlay checkout (web path) - Keep Tauri desktop path opening URL externally - Add handleCheckoutReturn() call in PanelLayoutManager constructor - Initialize checkout overlay with success banner callback - Dynamic import of checkout module to avoid loading until user clicks Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(17-02): add Upgrade to Pro section in UnifiedSettings modal - Add upgrade section at bottom of settings tab with value proposition - Wire CTA button to open Dodo checkout overlay via dynamic import - Close settings modal before opening checkout overlay - Tauri desktop fallback to external URL - Conditionally show "You're on Pro" when user has active entitlement Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove unused imports in entitlement-check test to pass typecheck:api Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(17-01): guard missing DODO_PAYMENTS_API_KEY with warning instead of silent undefined Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(17-01): use DODO_API_KEY env var name matching Convex dashboard config Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(17-02): add Dodo checkout domains to CSP frame-src directive Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(17-03): use test checkout domain for test-mode Dodo products Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(18-01): shared DodoPayments config and customer upsert in webhook - Create convex/lib/dodo.ts centralizing DodoPayments instance and API exports - Refactor checkout.ts to import from shared config (remove inline instantiation) - Add customer record upsert in handleSubscriptionActive for portal session support Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(18-01): billing queries and actions for subscription management - Add getSubscriptionForUser query (plan status, display name, renewal date) - Add getCustomerByUserId and getActiveSubscription internal queries - Add getCustomerPortalUrl action (creates Dodo portal session via SDK) - Add changePlan action (upgrade/downgrade with proration via Dodo SDK) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(18-02): add frontend billing service with reactive subscription watch - SubscriptionInfo interface for plan status display - initSubscriptionWatch() with ConvexClient onUpdate subscription - onSubscriptionChange() listener pattern with immediate fire for late subscribers - openBillingPortal() with Dodo Customer Portal fallback - changePlan() with prorated_immediately proration mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(18-02): add subscription status display and Manage Billing button to settings - Settings modal shows plan name, status badge, and renewal date for entitled users - Status-aware colors: green (active), yellow (on_hold), red (cancelled/expired) - Manage Billing button opens Dodo Customer Portal via billing service - initSubscriptionWatch called at dashboard boot alongside entitlements - Import initPaymentFailureBanner for Task 3 wiring Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(18-02): add persistent payment failure banner for on_hold subscriptions - Red fixed-position banner at top of dashboard when subscription is on_hold - Update Payment button opens Dodo billing portal - Dismiss button with sessionStorage persistence (avoids nagging in same session) - Auto-removes when subscription returns to active (reactive via Convex) - Event listeners attached directly to DOM (not via debounced setContent) - Wired into panel-layout constructor alongside subscription watch Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address code review — identity bridge, entitlement gating, fail-closed, env hygiene P0: Checkout-to-user identity bridge - Pass userId as metadata.wm_user_id in checkout sessions - Webhook resolveUserId: try metadata first, then customer table, then dev-only fallback - Fail closed in production when no user identity can be resolved P0: Unify premium gating to read Dodo entitlements - data-loader.ts: hasPremiumAccess() checks isEntitled() || API key - panels.ts: isPanelEntitled checks isEntitled() before API key fallback - panel-layout.ts: reload on entitlement change to unlock panels P1: Fail closed on unknown product IDs - resolvePlanKey throws on unmapped product (webhook retries) - getFeaturesForPlan throws on unknown planKey P1: Env var hygiene - Canonical DODO_API_KEY (no dual-name fallback in dodo.ts) - console.error on missing key instead of silent empty string P1: Fix test suite scheduled function errors - Guard scheduler.runAfter with UPSTASH_REDIS_REST_URL check - Tests skip Redis cache sync, eliminating convex-test write errors P2: Webhook rollback durability - webhookMutations: return error instead of rethrow (preserves audit row) - webhookHandlers: check mutation return for error indicator P2: Product ID consolidation - New src/config/products.ts as single source of truth - Panel.ts and UnifiedSettings.ts import from shared config P2: ConvexHttpClient singleton in entitlement-check.ts P2: Concrete features validator in schema (replaces v.any()) P2: Tests seed real customer mapping (not fallback user) P3: Narrow eslint-disable to typed interfaces in subscriptionHelpers P3: Real ConvexClient type in convex-client.ts P3: Better dev detection in auth.ts (CONVEX_IS_DEV) P3: Add VITE_DODO_ENVIRONMENT to .env.example Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(payments): security audit hardening — auth gates, webhook retry, transaction safety - Gate all public billing/checkout endpoints with resolveUserId(ctx) auth check - Fix webhook retry: record events after processing, not before; delete failed events on retry - Fix transaction atomicity: let errors propagate so Convex rolls back partial writes - Fix isDevDeployment to use CONVEX_IS_DEV (same as lib/auth.ts) - Add missing handlers: subscription.expired, refund.*, dispute.* - Fix toEpochMs silent fallback — now warns on missing billing dates - Use validated payload directly instead of double-parsing webhook body - Fix multi-sub query to prioritize active > on_hold > cancelled > expired - Change .unique() to .first() on customer lookups (defensive against duplicates) - Update handleSubscriptionActive to patch planKey/dodoProductId on existing subs - Frontend: portal URL validation, getProWidgetKey(), subscription cleanup on destroy - Make seedProductPlans internalMutation, console.log → console.warn for ops signals Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address code review — identity bridge, entitlement gating, fail-safe dev detection P0: convex/lib/auth.ts + subscriptionHelpers.ts — remove CONVEX_CLOUD_URL heuristic that could treat production as dev. Now uses ctx.auth.getUserIdentity() as primary auth with CONVEX_IS_DEV-only dev fallback. P0: server/gateway.ts + auth-session.ts — add bearer token (Clerk JWT) support for tier-gated endpoints. Authenticated users bypass API key requirement; userId flows into x-user-id header for entitlement check. Activated by setting CLERK_JWT_ISSUER_DOMAIN env var. P1: src/services/user-identity.ts — centralized getUserId() replacing scattered getProWidgetKey() calls in checkout.ts, billing.ts, panel-layout.ts. P2: src/App.ts — premium panel prime/refresh now checks isEntitled() alongside WORLDMONITOR_API_KEY so Dodo-entitled web users get data loading. P2: convex/lib/dodo.ts + billing.ts — move Dodo SDK config from module scope into lazy/action-scoped init. Missing DODO_API_KEY now throws at action boundary instead of silently capturing empty string. Tests: webhook test payloads now include wm_user_id metadata (production path). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address P0 access control + P1 identity bridge + P1 entitlement reload loop P0: Remove userId from public billing function args (getSubscriptionForUser, getCustomerPortalUrl, changePlan) — use requireUserId(ctx) with no fallback to prevent unauthenticated callers from accessing arbitrary user data. P1: Add stable anonymous ID (wm-anon-id) in user-identity.ts so createCheckout always passes wm_user_id in metadata. Breaks the infinite webhook retry loop for brand-new purchasers with no auth/localStorage identity. P1: Skip initial entitlement snapshot in onEntitlementChange to prevent reload loop for existing premium users whose shouldUnlockPremium() is already true from legacy signals (API key / wm-pro-key). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address P1 billing flow + P1 anon ID claim path + P2 daily-market-brief P1 — Billing functions wired end-to-end for browser sessions: - getSubscriptionForUser, getCustomerPortalUrl, changePlan now accept userId from args (matching entitlements.ts pattern) with auth-first fallback. Once Clerk JWT is wired into ConvexClient.setAuth(), the auth path will take precedence automatically. - Frontend billing.ts passes userId from getUserId() on all calls. - Subscription watch, portal URL, and plan change all work for browser users with anon IDs. P1 — Anonymous ID → account claim path: - Added claimSubscription(anonId) mutation to billing.ts — reassigns subscriptions, entitlements, customers, and payment events from an anonymous browser ID to the authenticated user. - Documented the anon ID limitation in user-identity.ts with the migration plan (call claimSubscription on first Clerk session). - Created follow-up issue #2078 for the full claim/migration flow. P2 — daily-market-brief added to hasPremiumAccess() block in data-loader.ts loadAllData() so it loads on general data refresh paths (was only in primeVisiblePanelData startup path). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: P0 lock down billing write actions + P2 fix claimSubscription logic P0 — Billing access control locked down: - getCustomerPortalUrl and changePlan converted to internalAction — not callable from the browser, closing the IDOR hole on write paths. - getSubscriptionForUser stays as a public query with userId arg (read-only, matching the entitlements.ts pattern — low risk). - Frontend billing.ts: portal opens generic Dodo URL, changePlan returns "not available" stub. Both will be promoted once Clerk auth is wired into ConvexClient.setAuth(). P2 — claimSubscription merge logic fixed: - Entitlement comparison now uses features.tier first, breaks ties with validUntil (was comparing only validUntil which could downgrade tiers). - Added Redis cache invalidation after claim: schedules deleteEntitlementCache for the stale anon ID and syncEntitlementCache for the real user ID. - Added deleteEntitlementCache internal action to cacheActions.ts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(billing): strip Dodo vendor IDs from public query response Remove dodoSubscriptionId and dodoProductId from getSubscriptionForUser return — these vendor-level identifiers aren't used client-side and shouldn't be exposed over an unauthenticated fallback path. Addresses koala73's Round 5 P1 review on #2024. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(billing): address koala review cleanup items (P2/P3) - Remove stale dodoSubscriptionId/dodoProductId from SubscriptionInfo interface (server no longer returns them) - Remove dead `?? crypto.randomUUID()` fallback in checkout.ts (getUserId() always returns a string via getOrCreateAnonId()) - Remove unused "failed" status variant and errorMessage from webhookEvents schema (no code path writes them) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add missing isProUser import and allow trusted origins for tier-gated endpoints The typecheck failed because isProUser was used in App.ts but never imported. The unit test failed because the gateway forced API key validation for tier-gated endpoints even from trusted browser origins (worldmonitor.app), where the client-side isProUser() gate controls access instead. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(gateway): require credentials for premium endpoints regardless of origin Origin header is spoofable — it cannot be a security boundary. Premium endpoints now always require either an API key or a valid bearer token (via Clerk session). Authenticated users (sessionUserId present) bypass the API key check; unauthenticated requests to tier-gated endpoints get 401. Updated test to assert browserNoKey → 401 instead of 200. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(tests): add catch-all route to legacy endpoint allowlist The [[...path]].js Vercel catch-all route (domain gateway entry point) was missing from ALLOWED_LEGACY_ENDPOINTS in the edge function tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * revert: remove [[...path]].js from legacy endpoint allowlist This file is Vercel-generated and gitignored — it only exists locally, not in the repo. Adding it to the allowlist caused CI to fail with "stale entry" since the file doesn't exist in CI. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(payment): apply design system to payment UI (light/dark mode) - checkout.ts: add light themeConfig for Dodo overlay + pass theme flag based on current document.dataset.theme; previously only dark was configured so light-mode users got Dodo's default white UI - UnifiedSettings: replace hardcoded dark hex values (#1a1a1a, #323232, #fff, #909090) in upgrade section with CSS var-driven classes so the panel respects both light and dark themes - main.css: add .upgrade-pro-section / .upgrade-pro-cta / .manage-billing-btn classes using var(--green), var(--bg), var(--surface), var(--border), etc. * fix(checkout): remove invalid theme prop from CheckoutOptions * fix: regenerate package-lock.json with npm 10 (matches CI Node 22) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(gateway): enforce pro role check for authenticated free users on premium paths Free bearer token holders with a valid session bypassed PREMIUM_RPC_PATHS because sessionUserId being set caused forceKey=false, skipping the role check entirely. Now explicitly checks bearer role after API key gate. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: remove unused getSecretState import from data-loader Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: gate Dodo Payments init behind isProUser() (same as Clerk) Entitlement subscription, subscription watch, checkout overlay, and payment banners now only initialize for isProUser() — matching the Clerk auth gate so only wm-pro-key / wm-widget-key holders see it. Also consolidates inline isEntitled()||getSecretState()||role checks in App.ts to use the centralized hasPremiumAccess() from panel-gating. Both gates (Clerk + Dodo) to be removed when ready for all users. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * ci: retrigger workflows * chore: retrigger CI * fix(redis): use POST method in deleteRedisKey for consistency All other write helpers use POST; DEL was implicitly using GET via fetch default. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(quick-5): resolve all P1 security issues from koala73 review P1-1: Fail-closed entitlement gate (403 when no userId or lookup fails) P1-2: Checkout requires auth (removed client-supplied userId fallback) P1-3: Removed dual auth (PREMIUM_RPC_PATHS) from gateway, single entitlement path P1-4: Typed features validator in cacheActions (v.object instead of v.any) P1-5: Typed ConvexClient API ref (typeof api instead of Record<string,any>) P1-6: Cache stampede mitigation via request coalescing (_inFlight map) Round8-A: getUserId() returns Clerk user.id, hasUserIdentity() checks real identity Round8-B: JWT verification pinned to algorithms: ['RS256'] - Updated entitlement tests for fail-closed behavior (7 tests pass) - Removed userId arg from checkout client call - Added env-aware Redis key prefix (live/test) - Reduced cache TTL from 3600 to 900 seconds - Added 5s timeout to Redis fetch calls Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(quick-5): resolve all P2 review issues from koala73 review P2-1: dispute.lost now revokes entitlements (downgrades to free tier) P2-2: rawPayload v.any() documented with JSDoc (intentional: external schema) P2-3: Redis keys prefixed with live/test env (already in P1 commit) P2-4: 5s timeout on Redis fetch calls (already in P1 commit) P2-5: Cache TTL reduced from 3600 to 900 seconds (already in P1 commit) P2-6: CONVEX_IS_DEV warning logged at module load time (once, not per-call) P2-7: claimSubscription uses .first() instead of .unique() (race safety) P2-8: toEpochMs fallback accepts eventTimestamp (all callers updated) P2-9: hasUserIdentity() checks real identity (already in P1 commit) P2-10: Duplicate JWT verification removed (already in P1 commit) P2-11: Subscription queries bounded with .take(10) P2-12: Entitlement subscription exposes destroyEntitlementSubscription() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(convex): resolve TS errors in http.ts after merge Non-null assertions for anyApi dynamic module references and safe array element access in timing-safe comparison. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(tests): update gateway tests for fail-closed entitlement system Tests now reflect the new behavior where: - API key + no auth session → 403 (entitlement check requires userId) - Valid bearer + no entitlement data → 403 (fail-closed) - Free bearer → 403 (entitlements unavailable) - Invalid bearer → 401 (no session, forceKey kicks in) - Public routes → 200 (unchanged) The old tests asserted PREMIUM_RPC_PATHS + JWT role behavior which was removed per koala73's P1-3 review (dual auth elimination). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): resolve 4 P1 + 2 P2 issues from koala73 round-9 review P1 fixes: - API-key holders bypass entitlement check (were getting 403) - Browser checkout passes userId for identity bridge (ConvexClient has no setAuth yet, so createCheckout accepts optional userId arg) - /pro pricing page embeds wm_user_id in Dodo checkout URL metadata so webhook can resolve identity for first-time purchasers - Remove isProUser() gate from entitlement/billing init — all users now subscribe to entitlement changes so upgrades take effect immediately without manual page reload P2 fixes: - destroyEntitlementSubscription() called on teardown to clear stale premium state across SPA sessions (sign-out / identity change) - Convex queries prefer resolveUserId(ctx) over client-supplied userId; documented as temporary until Clerk JWT wired into ConvexClient.setAuth() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): resolve 4 P1 + 1 P2 from koala73 round-10 review P1 — Checkout identity no longer client-controlled: - createCheckout HMAC-signs userId with DODO_PAYMENTS_WEBHOOK_SECRET - Webhook resolveUserId only trusts metadata when HMAC signature is valid; unsigned/tampered metadata is rejected - /pro raw URLs no longer embed wm_user_id (eliminated URL tampering) - Purchases without signed metadata get synthetic "dodo:{customerId}" userId, claimable later via claimSubscription() P1 — IDOR on Convex queries addressed: - Both getEntitlementsForUser and getSubscriptionForUser now reject mismatched userId when the caller IS authenticated (authedUserId != args.userId → return defaults/null) - Created internal getEntitlementsByUserId for future gateway use - Pre-auth fallback to args.userId documented with TODO(clerk-auth) P1 — Clerk identity bridge fixed: - user-identity.ts now uses getCurrentClerkUser() from clerk.ts instead of reading window.Clerk?.user (which was never assigned) - Signed-in Clerk users now correctly resolve to their Clerk user ID P1 — Auth modal available for anonymous users: - Removed isProUser() gate from setupAuthWidget() in App.ts - Anonymous users can now click premium CTAs → sign-in modal opens P2 — .take(10) subscription cap: - Bumped to .take(50) in both getSubscriptionForUser and getActiveSubscription to avoid missing active subscriptions Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): resolve remaining P2/P3 feedback from koala73 + greptile on PR #2024 JWKS: consolidate duplicate singletons — server/_shared/auth-session.ts now imports the shared JWKS from server/auth-session.ts (eliminates redundant cold-start fetch). Webhook: remove unreachable retry branch — webhookEvents.status is always "processed" (inserted only after success, rolled back on throw). Dead else removed. YAGNI: remove changePlan action + frontend stub (no callers — plan changes use Customer Portal). Remove unused by_status index on subscriptions table. DRY: consolidate identical pro_monthly/pro_annual into shared PRO_FEATURES constant. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(test): read CLERK_JWT_ISSUER_DOMAIN lazily in getJWKS() — fixes CI bearer token tests The shared getJWKS() was reading the env var from a module-scope const, which freezes at import time. Tests set the env var in before() hooks after import, so getJWKS() returned null and bearer tokens were never verified — causing 401 instead of 403 on entitlement checks. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(payments): resolve all blocking issues from review rounds 1-2 Data integrity: - Use .first() instead of .unique() on entitlements.by_userId to survive concurrent webhook retries without permanently crashing reads - Add typed paymentEventStatus union to schema; replace dynamic dispute status string construction with explicit lookup map - Document accepted 15-min Redis cache sync staleness bound - Document webhook endpoint URL in .env.example Frontend lifecycle: - Add listeners.clear() to destroyEntitlementSubscription (prevents stale closure reload loop on destroy/re-init cycles) - Add destroyCheckoutOverlay() to reset initialized flag so new layouts can register their success callbacks - Complete PanelLayoutManager.destroy() — add teardown for checkout overlay, payment failure banner, and entitlement change listener - Preserve currentState across destroy; add resetEntitlementState() for explicit reset (e.g. logout) without clearing on every cycle Code quality: - Export DEV_USER_ID and isDev from lib/auth.ts; remove duplicates from subscriptionHelpers.ts (single source of truth) - Remove DODO_PAYMENTS_API_KEY fallback from billing.ts - Document why two Dodo SDK packages coexist (component vs REST) * fix(payments): address round-3 review findings — HMAC key separation, auth wiring, shape guards - Introduce DODO_IDENTITY_SIGNING_SECRET separate from webhook secret (todo 087) Rotating the webhook secret no longer silently breaks userId identity signing - Wire claimSubscription to Clerk sign-in in App.ts (todo 088) Paying anonymous users now have their entitlements auto-migrated on first sign-in - Promote getCustomerPortalUrl to public action + wire openBillingPortal (todo 089) Manage Billing button now opens personalized portal instead of generic URL - Add rate limit on claimSubscription (todo 090) - Add webhook rawPayload shape guard before handler dispatch (todo 096) Malformed payloads return 200 with log instead of crashing the handler - Remove dead exports: resetEntitlementState, customerPortal wrapper (todo 091) - Fix let payload; implicit any in webhookHandlers.ts (todo 092) - Fix test: use internal.* for internalMutation seedProductPlans (todo 095) Co-Authored-By: Claude Sonnet 4.6 (200K context) <noreply@anthropic.com> * fix(payments): address round-4 P1 findings — input validation, anon-id cleanup - claimSubscription: replace broken rate-limit (bypassed for new users, false positives on renewals) with UUID v4 format guard + self-claim guard; prevents cross-user subscription theft via localStorage injection - App.ts: always remove wm-anon-id after non-throwing claim completion (not only when subscriptions > 0); adds optional chaining on result.claimed; prevents cold Convex init on every sign-in for non-purchasers Resolves todos 097, 098, 099, 100 * fix(payments): address round-5 review findings — regex hoist, optional chaining - Hoist ANON_ID_REGEX to module scope (was re-allocated on every call) - Remove /i flag — crypto.randomUUID() always produces lowercase - result.claimed accessed directly (non-optional) — mutation return is typed - Revert removeItem from !client || !api branch — preserve anon-id on infrastructure failure; .catch path handles transient errors * fix(billing): wire setAuth, rebind watches, revoke on dispute.lost, defer JWT, bound collect - convex-client.ts: wire client.setAuth(getClerkToken) so claimSubscription and getCustomerPortalUrl no longer throw 'Authentication required' in production - clerk.ts: expose clearClerkTokenCache() for force-refresh handling - App.ts: rebind entitlement + subscription watches to real Clerk userId on every sign-in (destroy + reinit), fixing stale anon-UUID watches post-claim - subscriptionHelpers.ts: revoke entitlement to 'free' on dispute.lost + sync Redis cache; previously only logged a warning leaving pro access intact after chargeback - gateway.ts: compute isTierGated before resolveSessionUserId; defer JWKS+RS256 verification to inside if (isTierGated) — eliminates JWT work on ~136 non-gated endpoints - billing.ts: .take(1000) on paymentEvents collect — safety bound preventing runaway memory on pathological anonymous sessions before sign-in Closes P1: setAuth never wired (claimSubscription always throws in prod) Closes P2: watch rebind, dispute.lost revocation, gateway perf, unbounded collect * fix(security): address P1 review findings from round-6 audit - Remove _debug block from validateApiKey that contained all valid API keys in envVarRaw/parsedKeys fields (latent full-key disclosure risk) - Replace {db: any} with QueryCtx in getEntitlementsHandler (Convex type safety) - Add pre-insert re-check in upsertEntitlements with OCC race documentation - Fix dispute.lost handler to use eventTimestamp instead of Date.now() for validUntil/updatedAt (preserves isNewerEvent out-of-order replay protection) - Extract getFeaturesForPlan("free") to const in dispute.lost (3x → 1x call) Closes todos #103, #106, #107, #108 * fix(payments): address round-6 open items — throw on shape guard, sign-out cleanup, stale TODOs P2-4: Webhook shape guards now throw instead of returning silently, so Dodo retries on malformed payloads instead of losing events. P3-2: Sign-out branch now destroys entitlement and subscription watches for the previous userId. P3: Removed stale TODO(clerk-auth) comments — setAuth() is wired. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(payments): address codex review — preserve listeners, honest TODOs, retry comment - destroyEntitlementSubscription/destroySubscriptionWatch no longer clear listeners — PanelLayout registers them once and they must survive auth transitions (sign-out → sign-in would lose the premium-unlock reload) - Restore TODO(auth) on entitlements/billing public queries — the userId fallback is a real trust gap, not just a cold-start race - Add comment on webhook shape guards acknowledging Dodo retry budget tradeoff vs silent event loss Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(types): restore non-null assertions in convex/http.ts after merge Main removed ! and as-any casts, but our branch's generated types make anyApi properties possibly undefined. Re-added to fix CI typecheck. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(types): resolve TS errors from rebase — cast internal refs, remove unused imports Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: regenerate package-lock.json — add missing uqr@0.1.2 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(payments): resolve P2/P3 review findings for PR #2024 - Bound and parallelize claimSubscription reads with Promise.all (4x queries -> single round trip; .collect() -> .take() to cap memory) - Add returnUrl allowlist validation in createCheckout to prevent open redirect - Make openBillingPortal return Promise<string | null> for agent-native callers - Extend isCallerPremium with Dodo entitlement tier check (tier >= 1 is premium, unifying Clerk role:pro and Dodo subscriber as two signals for the same gate) - Call resetEntitlementState() on sign-out to prevent entitlement state leakage across sessions (destroyEntitlementSubscription preserves state for reconnects; resetEntitlementState is the explicit sign-out nullifier) - Merge handlePaymentEvent + handleRefundEvent -> handlePaymentOrRefundEvent (type inferred from event prefix; eliminates duplicate resolveUserId call) - Remove _testCheckEntitlement DI export from entitlement-check.ts; inline _checkEntitlementCore into checkEntitlement; tests now mock getCachedJson - Collapse 4 duplicate dispute status tests into test.each - Fix stale entitlement variable name in claimSubscription return value * fix(payments): harden auth and checkout ownership * fix(gateway): tighten auth env handling * fix(gateway): use convex site url fallback * fix(app): avoid redundant checkout resume * fix(convex): cast alertRules internal refs for PR-branch generated types --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: Elie Habib <elie.habib@gmail.com> |
||
|
|
ea4fd99ccb |
fix(csp): add www.google.com to frame-src for YouTube embed sub-frames (#2612)
YouTube's iframe player loads google.com in a sub-frame (consent, login, tracking). CSP frame-src was blocking it with disposition:enforce (WORLDMONITOR-HT, 969 events, 513 users). Added to both header and meta tag CSPs. |
||
|
|
9772372a6d |
fix(csp): break Sentry CSP feedback loop causing 446K daily errors (#2600)
* fix(csp): break Sentry CSP feedback loop causing 446K daily errors Root cause: the securitypolicyviolation listener reports violations to Sentry, but the Sentry ingest endpoint itself was blocked by CSP. This triggered a new violation, which tried to report, which got blocked, creating an infinite cascade. The existing sentry.io filter regex didn't match because browsers append :443 to the blocked URI. Three fixes: 1. Fix Sentry filter regex to handle optional :443 port in blocked URI 2. Add Sentry ingest domains to connect-src in both CSPs 3. Sync script-src hashes between vercel.json header and index.html meta tag (removed 4 stale hashes, added 1 missing OAuth hash) When both HTTP header and meta tag CSP exist, the browser enforces BOTH independently. Mismatched script-src hashes between them caused legitimate scripts to be blocked by whichever policy lacked their hash. * fix(csp): suppress non-actionable CSP violations flooding Sentry (446K/day) Root cause: the securitypolicyviolation listener (PR #2365) reports ALL violations to Sentry. Dual CSP (header + meta tag) fires violations for first-party API calls (api.worldmonitor.app) that actually succeed with HTTP 200. These are not real blocks. Fixes: 1. Skip report-only disposition (e.disposition !== 'enforce') 2. Skip first-party origins (*.worldmonitor.app) — dual-CSP quirk fires violations for requests the other policy allows 3. Host-based Sentry filter (sentry.io anywhere, not just /api/ path) to handle origin-only blocked URIs (e.g., sentry.io:443) 4. Sync script-src hashes between vercel.json and index.html meta tag (removed 4 stale hashes, added 1 missing OAuth hash) 5. Add Sentry ingest to connect-src (defense-in-depth, not primary fix) 6. Add test: CSP script-src hash parity between header and meta tag The explicit Sentry ingest additions to connect-src are redundant with the existing https: scheme-source but serve as documentation and defense-in-depth. |
||
|
|
c8fe1a88a5 |
seo: fix H1, meta descriptions, schema author, and alternateName (#2537)
* seo: fix meta descriptions, H1, schema author, and alternateName * seo: apply P2 review suggestions from Greptile |
||
|
|
1074bed1b0 |
fix(csp): add challenges.cloudflare.com to index.html script-src and frame-src (#2311)
Clerk uses Cloudflare Turnstile for CAPTCHA on sign-in and sign-up. The Vercel header CSP already included challenges.cloudflare.com but the index.html meta tag CSP did not. Users with a service worker serving the HTML from cache see the meta tag CSP, causing Turnstile to be blocked and sign-in/sign-up to fail with 422/400. Also triggers a new Vercel deployment which picks up the newly added WORLDMONITOR_VALID_KEYS env var (required for tester key auth on premium market endpoints). |
||
|
|
a969a9e3a3 |
feat(auth): integrate clerk.dev (#1812)
* feat(auth): integrate better-auth with @better-auth/infra dash plugin Wire up better-auth server config with the dash() plugin from @better-auth/infra, and the matching sentinelClient() on the client side. Adds BETTER_AUTH_API_KEY to .env.example. * feat(auth): swap @better-auth/infra for @convex-dev/better-auth [10-01 task 1] Install @convex-dev/better-auth@0.11.2, remove @better-auth/infra, delete old server/auth.ts skeleton, rewrite auth-client.ts to use crossDomainClient + convexClient plugins. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(auth): create Convex auth component files [10-01 task 2] Add convex.config.ts (register betterAuth component), auth.config.ts (JWT/JWKS provider), auth.ts (better-auth server with Convex adapter, crossDomain + convex plugins), http.ts (mount auth routes with CORS). Uses better-auth/minimal for lighter bundle. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(auth): add admin, organization, and dash plugins [10-01] Re-install @better-auth/infra for dash() plugin to enable dash.better-auth.com admin dashboard. Add admin() and organization() plugins from better-auth/plugins for user and org management. Update both server (convex/auth.ts) and client (auth-client.ts). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): drop @better-auth/infra (Node.js deps incompatible with Convex V8) Keep admin() and organization() from better-auth/plugins (V8-safe). @better-auth/infra's dash() transitively imports SAML/SSO with node:crypto, fs, zlib — can't run in Convex's serverless runtime. Dashboard features available via admin plugin endpoints instead. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(11-01): create auth-state.ts with OTT handler and session subscription - Add initAuthState() for OAuth one-time token verification on page load - Add subscribeAuthState() reactive wrapper around useSession nanostore atom - Add getAuthState() synchronous snapshot getter - Export AuthUser and AuthSession types for UI consumption Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(11-01): add Google OAuth provider and wire initAuthState into App.ts - Add socialProviders.google with GOOGLE_CLIENT_ID/SECRET to convex/auth.ts - Add all variant subdomains to trustedOrigins for cross-subdomain CORS - Call initAuthState() in App.init() before panelLayout.init() - Add authModal field to AppContext interface (prepares for Plan 02) - Add authModal: null to App constructor state initialization Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(11-02): create AuthModal with Sign In/Sign Up tabs and Google OAuth - Sign In tab: email/password form calling authClient.signIn.email() - Sign Up tab: name/email/password form calling authClient.signUp.email() - Google OAuth button calling authClient.signIn.social({ provider: 'google', callbackURL: '/' }) - Auto-close on successful auth via subscribeAuthState() subscription - Escape key, overlay click, and X button close the modal - Loading states, error display, and client-side validation Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(11-02): add AuthHeaderWidget, mount in header, add auth CSS - AuthHeaderWidget: reactive header widget showing Sign In button (anonymous) or avatar + dropdown (authenticated) - User dropdown: name, email, Free tier badge, Sign Out button calling authClient.signOut() - setupAuthWidget() in EventHandlerManager creates modal + widget, mounts at authWidgetMount span - authWidgetMount added to panel-layout.ts header-right, positioned before download wrapper - setupAuthWidget() called from App.ts after setupUnifiedSettings() - Full auth CSS: modal styles, tabs, forms, Google button, header widget, avatar, dropdown Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(11-02): add localhost:3000 to trustedOrigins for local dev CORS Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): remove admin/organization plugins that break Convex adapter validator The admin() plugin adds banned/role fields to user creation data, but the @convex-dev/better-auth adapter validator doesn't include them. These plugins are Phase 12 work — will re-add with additionalFields config when needed. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(12-01): add Resend email transport, verification + reset callbacks, role field - Install resend SDK for transactional email - Add emailVerification with sendOnSignUp:true and fire-and-forget Resend callbacks - Add sendResetPassword callback with 1-hour token expiry - Add user.additionalFields.role (free/pro, input:false, defaultValue:free) - Create userRoles fallback table in schema with by_userId index - Create getUserRole query and setUserRole mutation in convex/userRoles.ts - Lazy-init Resend client to avoid Convex module analysis error Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(12-01): enhance auth-state with emailVerified and role fields - Add emailVerified (boolean) and role ('free' | 'pro') to AuthUser interface - Fetch role from Convex userRoles table via HTTP query after session hydration - Cache role per userId to avoid redundant fetches - Re-notify subscribers asynchronously when role is fetched for a new user - Map emailVerified from core better-auth user field (default false) - Derive Convex cloud URL from VITE_CONVEX_SITE_URL env var Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(12-01): add Convex generated files from deployment - Track convex/_generated/ files produced by npx convex dev --once Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(12-03): create panel-gating service with auth-aware showGatedCta - Add PanelGateReason enum (NONE/ANONYMOUS/UNVERIFIED/FREE_TIER) - Add getPanelGateReason() computing gating from AuthSession + premium flag - Add Panel.showGatedCta() rendering auth-aware CTA overlays - Add Panel.unlockPanel() to reverse locked state - Extract lockSvg to module-level const shared by showLocked/showGatedCta - Add i18n keys: signInToUnlock, signIn, verifyEmailToUnlock, resendVerification, upgradeDesc, upgradeToPro Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(12-02): add forgot password flow, password reset form, and token detection - Widen authModal interface in app-context.ts to support reset-password mode and setResetToken - AuthModal refactored with 4 views: signin, signup, forgot-password, reset-password - Forgot password view sends reset email via authClient.requestPasswordReset - Reset password form validates matching passwords and calls authClient.resetPassword - auth-state.ts detects ?token= param from email links, stores as pendingResetToken - App.ts routes pending reset token to auth modal after UI initialization - CSS for forgot-link, back-link, and success message elements Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(12-02): add email verification banner to AuthHeaderWidget and tier badge - Show non-blocking verification banner below header for unverified users - Banner has "Resend" button calling authClient.sendVerificationEmail - Banner is dismissible (stored in sessionStorage, reappears next session) - Tier badge dynamically shows Free/Pro based on user.role - Pro badge has gradient styling distinct from Free badge - Dropdown shows unverified status indicator with yellow dot - Banner uses fixed positioning, does not push content down - CSS for banner, pro badge, and verification status indicators Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(12-03): wire reactive auth-based gating into panel-layout - Add WEB_PREMIUM_PANELS Set (stock-analysis, stock-backtest, daily-market-brief) - Subscribe to auth state changes in PanelLayoutManager.init() - Add updatePanelGating() iterating panels with getPanelGateReason() - Add getGateAction() returning CTA callbacks per gate reason - Remove inline showLocked() calls for web premium panels - Preserve desktop _lockPanels for forecast, oref-sirens, telegram-intel - Clean up auth subscription in destroy() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(13-01): create auth-token utility and inject Bearer header in web fetch redirect - Add src/services/auth-token.ts with getSessionBearerToken() that reads session token from localStorage - Add WEB_PREMIUM_API_PATHS Set for the 4 premium market API paths - Inject Authorization: Bearer header in installWebApiRedirect() for premium paths when session exists - Desktop installRuntimeFetchPatch() left unchanged (API key only) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(13-01): create server-side session validation module - Add server/auth-session.ts with validateBearerToken() for Vercel edge gateway - Validates tokens via Convex /api/auth/get-session with Better-Auth-Cookie header - Falls back to userRoles:getUserRole Convex query for role resolution - In-memory cache with 60s TTL and 100-entry cap - Network errors not cached to allow retry on next request Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(13-02): add bearer token fallback auth for premium API endpoints - Dynamic import of auth-session.ts when premium endpoint + API key fails - Valid pro session tokens fall through to route handler - Non-pro authenticated users get 403 'Pro subscription required' - Invalid/expired tokens get 401 'Invalid or expired session' - Non-premium endpoints and static API key flow unchanged Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): sign-in button invisible in dark theme — white on white --accent is #fff in dark theme, so background: var(--accent) + color: #fff was invisible. Changed to transparent background with var(--text) color. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): add premium panel keys to full and finance variant configs stock-analysis, stock-backtest, and daily-market-brief were defined in the shared panels.ts but missing from variant DEFAULT_PANELS, causing shouldCreatePanel() to return false and panel gating CTAs to never render. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(auth): add Playwright smoke tests for auth UI (phases 12-13) 6 tests covering: Sign In button visibility, auth modal opening, modal views (Sign In/Sign Up/Forgot Password), premium panel gating for anonymous users, and auth token absence when logged out. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): remove role additionalField that breaks Convex component validator The betterAuth Convex component has a strict input validator for the user model that doesn't include custom fields. The role additionalField caused ArgumentValidationError on sign-up. Roles are already stored in the separate userRoles table — no data loss. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): use Authorization Bearer header for Convex session validation Better-Auth-Cookie header returned null — the crossDomain plugin's get-session endpoint expects Authorization: Bearer format instead. Confirmed via curl against live Convex deployment. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): use verified worldmonitor.app domain for auth emails Was using noreply@resend.dev (testing domain) which can't send to external recipients. Switched to noreply@worldmonitor.app matching existing waitlist/contact emails. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): await Resend email sends — Convex kills dangling promises void (fire-and-forget) causes Convex to terminate the fetch before Resend receives it. Await ensures emails actually get sent. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: update Convex generated auth files after config changes Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): guard against undefined VITE_CONVEX_SITE_URL in auth-state The Convex cloud URL derivation crashed the entire app when VITE_CONVEX_SITE_URL wasn't set in the build environment (Vercel preview). Now gracefully defaults to empty string and skips role fetching when the URL is unavailable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(auth): add dash + organization plugins, remove Google OAuth, fix dark mode button - Add @better-auth/infra dash plugin for hosted admin dashboard - Add organization plugin for org management in dashboard - Add dash.better-auth.com to trustedOrigins - Remove Google OAuth (socialProviders, button, divider, CSS) - Fix auth submit button invisible in dark mode (var(--accent) → #3b82f6) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): replace dash plugin with admin — @better-auth/infra incompatible with Convex V8 @better-auth/infra imports SSO/SAML libraries requiring Node.js built-ins (crypto, fs, stream) which Convex's V8 runtime doesn't support. Replaced with admin plugin from better-auth/plugins which provides user management endpoints (set-role, list-users, ban, etc.) natively. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove stale Convex generated files after plugin update Convex dev regenerated _generated/ — the per-module JS files (auth.js, http.js, schema.js, etc.) are no longer emitted. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(auth): remove organization plugin — will add in subsequent PR Organization support (team accounts, invitations, member management) is not wired into any frontend flow yet. Removing to keep the auth PR focused on email/password + admin endpoints. Will add back when building the org/team feature. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add authentication & panel gating guide Documents the auth stack, panel gating configuration, server-side session enforcement, environment variables, and user roles. Includes step-by-step guide for adding new premium panels. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(test): stub panel-gating in RuntimeConfigPanel test harness Panel.ts now imports @/services/panel-gating, which wasn't stubbed — causing the real runtime.ts (with window.location) to be bundled, breaking Node.js tests with "ReferenceError: location is not defined". Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): allow Vercel preview origins in Convex trustedOrigins * fix(auth): broaden Convex trustedOrigins to cover *.worldmonitor.app previews * fix(auth): use hostonly wildcard pattern for *.worldmonitor.app in trustedOrigins * fix(auth): add Convex site origins to trustedOrigins * fix(ci): add convex/ to vercel-ignore watched paths * fix(auth): remove admin() plugin — adds banned/role fields rejected by Convex validator * fix(auth): remove admin() plugin — injects banned/role fields rejected by Convex betterAuth validator * feat(auth): replace email/password with email OTP passwordless flow - Replace emailAndPassword + emailVerification with emailOTP plugin - Rewrite AuthModal: email entry -> OTP code verification (no passwords) - Remove admin() plugin (caused Convex schema validation errors) - Remove email verification banner and UNVERIFIED gate reason (OTP inherently verifies email) - Remove password reset flow (forgot/reset password views, token handling) - Clean up unused CSS (tabs, verification banner, success messages) - Update docs to reflect new passwordless auth stack Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(quick-2): harden Convex userRoles and add role cache TTL - P0: Convert setUserRole from mutation to internalMutation (not callable from client) - P2: Add 5-minute TTL to role cache in auth-state.ts - P2: Add localStorage shape warning on auth-token.ts - P3: Document getUserRole public query trade-off - P3: Fix misleading cache comment in auth-session.ts Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(quick-2): auth widget teardown, E2E test rewrite, gateway comment - P2: Store authHeaderWidget on AppContext, destroy in EventHandlerManager.destroy() - P2: Also destroy authModal in destroy() to prevent leaked subscriptions - P1: Rewrite E2E tests for 2-view OTP modal (email input + submit button) - P1: Remove stale "Sign Up" and "Forgot Password" test assertions - P2: Replace flaky waitForTimeout(5000) with Playwright auto-retry assertion - P3: Add clarifying comment on premium bearer-token fallback in gateway Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(header): restructure header/footer, add profile editing, pro-gate playback/export - Remove version, @eliehabib, GitHub link, and download button from header - Move version + @eliehabib credit to footer brand line; download link to footer nav - Move auth widget (profile avatar) to far right of header (after settings gear) - Add default generic SVG avatar for users with no image and no name - Add profile editing in auth dropdown: display name + avatar URL with Save/Cancel - Add Settings shortcut in auth dropdown (opens UnifiedSettings) - Gate Historical Playback and Export controls behind pro role (hidden for free users) - Reactive pro-gate: subscribes to auth state changes, stores unsub in proGateUnsubscribers[] - Clean up proGateUnsubscribers on EventHandlerManager.destroy() to prevent leaks - Fix: render Settings button unconditionally (hidden via style), stable DOM structure - Fix: typed updateUser call with runtime existence check instead of (any) cast - Make initFooterDownload() private to match class conventions * feat(analytics): add Umami auth integration and event tracking - Wire analytics.ts facade to Umami (port from main #1914): search, country, map layers, panels, LLM, theme, language, variant switch, webcam, download, findings, deeplinks - Add Window.umami shim to vite-env.d.ts - Add initAuthAnalytics() that subscribes to auth state and calls identifyUser(id, role) / clearIdentity() on sign-in/sign-out - Add trackSignIn, trackSignUp, trackSignOut, trackGateHit exports - Call initAuthAnalytics() from App.ts after initAuthState() - Track sign-in/sign-up (via isNewUser flag) in AuthModal OTP verify - Track sign-out in AuthHeaderWidget before authClient.signOut() - Track gate-hit for export, playback (event-handlers) and pro-banner * feat(auth): professional avatar widget with colored initials and clean profile edit - Replace white-circle avatar with deterministic colored initials (Gmail/Linear style) - Avatar color derived from email hash across 8-color palette - Dropdown redesigned: row layout with large avatar + name/email/tier info - Profile edit form: name-only (removed avatar URL field) - Remove Settings button from dropdown (gear icon in header is sufficient) - Discord community widget: single CTA link, no redundant text label - Add all missing CSS for dropdown interior, profile edit form, menu items * fix(auth): lock down billing tier visibility and fix TOCTOU race P1: getUserRole converted to internalQuery — billing tier no longer accessible via any public Convex client API. Exposed only through the new authenticated /api/user-role HTTP action which validates the session Bearer token before returning the role. P1: subscribeAuthState generation counter + AbortController prevents rapid sign-in/sign-out from delivering stale role for wrong user. P2: typed RawSessionUser/RawSessionValue interfaces replace any casts at the better-auth nanostore boundary. fetchUserRole drops userId param — server derives identity from Bearer token only. P2: isNewUser heuristic removed from OTP verify — better-auth emailOTP has no reliable isNewUser signal. All verifications tracked as trackSignIn. OTP resend gets 30s client-side cooldown. P2: auth-token.ts version pin comment added (better-auth@1.5.5 + @convex-dev/better-auth@0.11.2). Gateway inner PREMIUM_RPC_PATHS comment clarified to explain why it is not redundant. Adds tests/auth-session.test.mts: 11 tests covering role fallback endpoint selection, fail-closed behavior, and CORS origin matching. * feat(quick-4): replace better-auth with Clerk JS -- packages, Convex config, browser auth layer - Remove better-auth, @convex-dev/better-auth, @better-auth/infra, resend from dependencies - Add @clerk/clerk-js and jose to dependencies - Rewrite convex/auth.config.ts for Clerk issuer domain - Simplify convex/convex.config.ts (remove betterAuth component) - Delete convex/auth.ts, convex/http.ts, convex/userRoles.ts - Remove userRoles table from convex/schema.ts - Create src/services/clerk.ts with Clerk JS init, sign-in, sign-out, token, user metadata, UserButton - Rewrite src/services/auth-state.ts backed by Clerk (same AuthUser/AuthSession interface) - Delete src/services/auth-client.ts (better-auth client) - Delete src/services/auth-token.ts (localStorage token scraping) - Update .env.example with Clerk env vars, remove BETTER_AUTH_API_KEY Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(quick-4): UI components, runtime fetch, server-side JWT, CSP, and tests - Delete AuthModal.ts, create AuthLauncher.ts (thin Clerk.openSignIn wrapper) - Rewrite AuthHeaderWidget.ts to use Clerk UserButton + openSignIn - Update event-handlers.ts to use AuthLauncher instead of AuthModal - Rewrite runtime.ts enrichInitForPremium to use async getClerkToken() - Rewrite server/auth-session.ts for jose-based JWT verification with cached JWKS - Update vercel.json CSP: add *.clerk.accounts.dev to script-src and frame-src - Add Clerk CSP tests to deploy-config.test.mjs - Rewrite e2e/auth-ui.spec.ts for Clerk UI - Rewrite auth-session.test.mts for jose-based validation - Use dynamic import for @clerk/clerk-js to avoid Node.js test breakage Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): allow Clerk Pro users to load premium data on web The data-loader gated premium panel loading (stock-analysis, stock-backtest, daily-market-brief) on WORLDMONITOR_API_KEY only, which is desktop-only. Web users with Clerk Pro auth were seeing unlocked panels stuck on "Loading..." because the requests were never made. Added hasPremiumAccess() helper that checks for EITHER desktop API key OR Clerk Pro role, matching the migration plan Phase 7 requirements. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): address PR #1812 review — all 4 merge blockers + 3 gaps Blockers: 1. Remove stale Convex artifacts (http.js, userRoles.js, betterAuth component) from convex/_generated/api.d.ts 2. isProUser() now checks getAuthState().user?.role === 'pro' alongside legacy localStorage keys 3. Finance premium refresh scheduling now fires for Clerk Pro web users (not just API key holders) 4. JWT verification now validates audience: 'convex' to reject tokens scoped to other Clerk templates Gaps: 5. auth-session tests: 10 new cases (valid pro/free, expired, wrong key/audience/issuer, missing sub/plan, JWKS reuse) using self-signed keys + local JWKS server 6. premium-stock-gateway tests: 4 new bearer token cases (pro→200, free→403, invalid→401, public unaffected) 7. docs/authentication.mdx rewritten for Clerk (removed all better-auth references, updated stack/files/env vars/roles sections) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: address P1 reactive Pro UI + P2 daily-market-brief + P3 stale env vars P1 — In-session Pro UI changes no longer require a full reload: - setupExportPanel: removed early isProUser() return, always creates and relies on reactive subscribeAuthState show/hide - setupPlaybackControl: same pattern — always creates, reactive gate - Custom widget panels: always loaded regardless of Pro status - Pro add-panel and MCP add-panel blocks: always rendered, shown/hidden reactively via subscribeAuthState callback - Flight search wiring: always wired, checks Pro status inside callback so mid-session sign-ins work immediately P2 — daily-market-brief added to hasPremiumAccess() block in loadAllData() so Clerk Pro web users get initial data load (was only primed in primeVisiblePanelData, missing from the general reload path) P3 — Removed stale CONVEX_SITE_URL and VITE_CONVEX_SITE_URL from docs/authentication.mdx env vars table (neither is referenced in codebase) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add isProUser import, populate PREMIUM_RPC_PATHS, and fix bearer token auth flow - Added missing isProUser import in App.ts (fixes typecheck) - Populated PREMIUM_RPC_PATHS with stock analysis endpoints - Restructured gateway auth: trusted browser origins bypass API key for premium endpoints (client-side isProUser gate), while bearer token validation runs as a separate step for premium paths when present Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(gateway): require credentials for premium paths + defer free-tier enforcement until auth ready P0: Removed trusted-origin bypass for premium endpoints — Origin header is spoofable and cannot be a security boundary. Premium paths now always require either an API key or valid bearer token. P1: Deferred panel/source free-tier enforcement until auth state resolves. Previously ran in the constructor before initAuthState(), causing Clerk Pro users to have their panels/sources trimmed on every startup. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(auth): apply WorldMonitor design system to Clerk modal Theme-aware appearance config passed to clerk.load(), openSignIn(), and mountUserButton(). Dark mode: dark bg (#111), green primary (#44ff88), monospace font. Light mode: white bg, green-600 primary (#16a34a). Reads document.documentElement.dataset.theme at call time so theme switches are respected. * fix(auth): gate Clerk init and auth widget behind BETA_MODE Clerk auth initialization and the Sign In header widget are now only activated when localStorage `worldmonitor-beta-mode` is set to "true", allowing silent deployment for internal testing before public rollout. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(auth): gate Clerk init and auth widget behind isProUser() Clerk auth initialization and the Sign In header widget are now only activated when the user has wm-widget-key or wm-pro-key in localStorage (i.e. isProUser() returns true), allowing silent deployment for internal testing before public rollout. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(data-loader): replace stale isProUser() with hasPremiumAccess() loadMarketImplications() still referenced the removed isProUser import, causing a TS2304 build error. Align with the rest of data-loader.ts which uses hasPremiumAccess() (checks both API key and Clerk auth). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(auth): address PR #1812 review — P1 security fixes + P2 improvements P1 fixes: - Add algorithms: ['RS256'] allowlist to jwtVerify (prevents alg:none bypass) - Reset loadPromise on Clerk init failure (allows retry instead of permanent breakage) P2 fixes: - Extract PREMIUM_RPC_PATHS to shared module (eliminates server/client divergence risk) - Add fail-fast guard in convex/auth.config.ts for missing CLERK_JWT_ISSUER_DOMAIN - Add 50s token cache with in-flight dedup to getClerkToken() (prevents concurrent races) - Sync Clerk CSP entries to index.html and tauri.conf.json (previously only in vercel.json) - Type clerkInstance as Clerk instead of any Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(auth): clear cached token on signOut() Prevents stale token from being returned during the ≤50s cache window after a user signs out. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Sebastien Melki <sebastien@anghami.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: Sebastien Melki <sebastienmelki@gmail.com> |
||
|
|
0169245f45 |
feat(seo): BlogPosting schema, FAQPage JSON-LD, extensible author system (#2284)
* feat(seo): BlogPosting schema, FAQPage JSON-LD, author system, AI crawler welcome Blog structured data: - Change @type Article to BlogPosting for all blog posts - Author: Organization to Person with extensible default (Elie Habib) - Add per-post author/authorUrl/authorBio/modifiedDate frontmatter fields - Auto-extract FAQPage JSON-LD from FAQ sections in all 17 posts - Show Updated date when modifiedDate differs from pubDate - Add author bio section with GitHub avatar and fallback Main app: - Add commodity variant to middleware VARIANT_HOST_MAP and VARIANT_OG - Add commodity.worldmonitor.app to sitemap.xml - Shorten index.html meta description to 136 chars (was 161) - Remove worksFor block from index.html author JSON-LD - Welcome all bots in robots.txt (removed per-bot blocks, global allows) - Update llms.txt: five variants listed, all 17 blog post URLs added * fix(seo): scope FAQ regex to section boundary, use author-aware avatar - extractFaqLd now slices only to the next ## heading (was: to end of body) preventing bold text in post-FAQ sections from being mistakenly extracted - Avatar src now derived from DEFAULT_AUTHOR_GITHUB constant (koala73) only when using the default author; custom authors fall back to favicon so multi-author posts show a correct image instead of the wrong profile |
||
|
|
32ca22d69f |
feat(analytics): add Umami analytics via self-hosted instance (#1914)
* feat(analytics): add Umami analytics via self-hosted instance Adds Umami analytics script from abacus.worldmonitor.app and updates CSP headers in both index.html and vercel.json to allow the script. * feat(analytics): complete Umami integration with event tracking - Add data-domains to index.html script to exclude dev traffic - Add Umami script to /pro page and blog (Base.astro) - Add TypeScript Window.umami shim to vite-env.d.ts - Wire analytics.ts facade to Umami (replaces PostHog no-ops): search, country clicks, map layers, panels, LLM usage, theme, language, variant switch, webcam, download, findings, deeplinks - Add direct callsite tracking for: settings-open, mcp-connect-attempt, mcp-connect-success, mcp-panel-add, widget-ai-open/generate/success, news-summarize, news-sort-toggle, live-news-fullscreen, webcam-fullscreen, search-open (desktop/mobile/fab) * fix(analytics): add Tauri CSP allowlist for Umami + skip programmatic layer events - Add abacus.worldmonitor.app to Tauri CSP script-src and connect-src so Umami loads in the desktop WebView (analytics exception to the no-cloud-data rule — needed to know if desktop is used) - Filter trackMapLayerToggle to user-initiated events only to avoid inflating counts with programmatic toggles on page load |
||
|
|
c4a76b2c4a |
fix(security): allow vercel.live and *.vercel.app in CSP for preview deployments (#1887)
Vercel preview toolbar and preview URLs were blocked by missing CSP entries. Both the meta tag (index.html) and HTTP header (vercel.json) must be in sync since browsers enforce all active policies simultaneously. - Add sha256-903UI9... hash to index.html script-src (was in vercel.json only, causing production inline script blocks from the meta tag policy) - Add https://vercel.live and https://*.vercel.app to frame-src in both files - Add https://vercel.live and https://*.vercel.app to frame-ancestors in vercel.json |
||
|
|
d101c03009 |
fix: unblock geolocation and fix stale CSP hash (#1709)
* fix: unblock geolocation and fix stale CSP hash for SW nuke script Permissions-Policy had geolocation=() which blocked navigator.geolocation used by user-location.ts. Changed to geolocation=(self). CSP script-src had a stale SHA-256 hash (903UI9my...) that didn't match the current SW nuke script content. The script was silently blocked in production, preventing recovery from stale service workers after deploys. Replaced with the correct hash (4Z2xtr1B...) in both vercel.json and index.html meta tag. * test: update permissions-policy test for geolocation=(self) Move geolocation from "disabled" list to "delegated" assertions since it now allows self-origin access for user-location.ts. |
||
|
|
987ed03f5d |
feat(webcams): add webcam map layer with Windy API integration (#1540) (#1540)
- Webcam markers on flat, globe, and DeckGL maps with category-based icons - Server-side spatial queries via Redis GEOSEARCH with quantized bbox caching - Pinned webcams panel with localStorage persistence - Seed script for Windy API with regional bounding boxes and adaptive splitting - Input validation (webcamId regex + encodeURIComponent) and NaN projection guards - Bandwidth optimizations: zoom threshold, bbox overlap check, 1s cooldown - Client-side image cache with 200-entry FIFO eviction - Globe altitude-based viewport estimation for webcam loading - CSP updates for webcam iframe sources - Seed-meta key for health.js freshness tracking |
||
|
|
59cd313e16 |
fix(csp): add commodity variant to CSP and fix iframe variant navigation (#1506)
* fix(csp): add commodity variant to CSP and fix iframe variant navigation
- Add commodity.worldmonitor.app to frame-src and frame-ancestors in
vercel.json and index.html CSP — was missing while all other variants
were listed
- Open variant links in new tab when app runs inside an iframe to prevent
sandbox navigation errors ("This content is blocked")
- Add allow-popups and allow-popups-to-escape-sandbox to pro page iframe
sandbox attribute
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix(csp): add missing variant subdomains to tauri.conf.json frame-src
Sync tauri.conf.json CSP with index.html and vercel.json by adding
finance, commodity, and happy worldmonitor.app subdomains to frame-src.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: add PR screenshots for CSP fix
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Elie Habib <elie.habib@gmail.com>
|
||
|
|
2a7d7fc3fe |
fix: standardize brand name to "World Monitor" with space (#1463)
Replace "WorldMonitor" with "World Monitor" in all user-facing display text across blog posts, docs, layouts, structured data, footer, offline page, and X-Title headers. Technical identifiers (User-Agent strings, X-WorldMonitor-Key headers, @WorldMonitorApp handle, function names) are preserved unchanged. Also adds anchors color to Mintlify docs config to fix blue link color in dark mode. |
||
|
|
6b2550ff49 |
fix(csp): allow cross-subdomain framing for Pro page variant switcher (#1332)
* fix(csp): allow cross-subdomain framing and add finance to frame-src frame-ancestors 'self' blocked tech/finance variants from rendering inside the Pro landing page iframe. Widen to *.worldmonitor.app. Also adds missing finance.worldmonitor.app to frame-src. Closes #1322 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(csp): remove conflicting X-Frame-Options and tighten frame-ancestors X-Frame-Options: SAMEORIGIN contradicts the new frame-ancestors directive that allows cross-subdomain framing. Modern browsers prioritize frame-ancestors over X-Frame-Options, but sending both is contradictory and gets flagged by security scanners. Remove X-Frame-Options entirely. Also replace wildcard *.worldmonitor.app with explicit subdomain list to limit the framing scope to known variants only. --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Elie Habib <elie.habib@gmail.com> |
||
|
|
4306322b67 |
fix(seo): comprehensive SEO improvements for /pro and main pages (#1271)
Pro page (/pro): - Shorten title to ≤60 chars for SERP visibility - Fix canonical + all URLs to www.worldmonitor.app - Fix multiple H1 (Enterprise modal H1→H2) - Fix heading hierarchy (H2→H4 jumps → proper H2→H3→H4) - Sync FAQPage JSON-LD with all 8 visible FAQs - Add twitter:title, twitter:description, og:locale, og:image:alt - Add hreflang tags for all 21 supported languages - Add <noscript> fallback with key SEO content - Add SSG prerender script (injects text into built HTML) - Self-host WIRED logo SVG (was loading from Wikipedia) - Add aria-labels on footer links and CTAs - Fix i18n to read ?lang= query parameter (was only localStorage + navigator) Main page: - Fix canonical + OG/Twitter URLs to www.worldmonitor.app - Update twitter:site/creator to @worldmonitorai - Add <noscript> with H1, description, features, and /pro link - Add hreflang tags for all 21 languages - Add og:image:alt meta tag - Add @worldmonitorai to JSON-LD sameAs - Align title with variant-meta.ts Shared: - Update sitemap.xml URLs to www.worldmonitor.app - Update robots.txt sitemap reference to www - Update variant-meta.ts full variant URL to www |
||
|
|
dfc175023a |
feat(pro): Pro waitlist landing page with referral system (#1140)
* fix(desktop): settings UI redesign, IPC security hardening, release profile Settings window: - Add titlebar drag region (macOS traffic light clearance) - Move Export/Import from Overview to Debug & Logs section - Category cards grid changed to 3-column layout Security (IPC trust boundary): - Add require_trusted_window() to get_desktop_runtime_info, open_url, open_live_channels_window_command, open_youtube_login - Validate base_url in open_live_channels_window_command (localhost-only http) Performance: - Add [profile.release] with fat LTO, codegen-units=1, strip, panic=abort - Reuse reqwest::Client via app state with connection pooling - Debounce window resize handler (150ms) in EventHandlerManager * feat(pro): add Pro waitlist landing page with referral system - React 19 + Vite 6 + Tailwind v4 landing page at /pro - Cloudflare Turnstile + honeypot bot protection - Resend transactional confirmation emails with branded template - Viral referral system: unique codes, position tracking, social share - Convex schema: referralCode, referredBy, referralCount fields + counters table - O(1) position counter pattern instead of O(n) collection scan - SEO: structured data, sitemap, scrolling source marquee - Vercel routing: /pro rewrite + cache headers + SPA exclusion - XSS-safe DOM rendering (no innerHTML with user data) |
||
|
|
fce836039b |
feat(map): migrate basemap from CARTO to self-hosted PMTiles on R2 (#1064)
* feat(map): migrate basemap from CARTO to self-hosted PMTiles on Cloudflare R2 Replace CARTO tile provider (frequent 403 errors) with self-hosted PMTiles served from Cloudflare R2. Uses @protomaps/basemaps for style generation with OpenFreeMap as automatic fallback when VITE_PMTILES_URL is unset. - Add pmtiles and @protomaps/basemaps dependencies - Create src/config/basemap.ts for PMTiles protocol registration and style building - Update DeckGLMap.ts to use PMTiles styles (non-happy variants) - Fix fallback detection using data event instead of style.load - Update SW cache rules: replace CARTO/MapTiler with PMTiles NetworkFirst - Add Protomaps preconnect hints in index.html - Bundle pmtiles + @protomaps/basemaps in maplibre chunk - Upload 3.4GB world tiles (zoom 0-10) to R2 bucket worldmonitor-maps * fix(map): use CDN custom domain maps.worldmonitor.app for PMTiles Replace r2.dev URL with custom domain backed by Cloudflare CDN edge. Update preconnect hint and .env.example with production URL. * fix(map): harden PMTiles fallback detection to prevent false triggers - Require 2+ network errors before triggering OpenFreeMap fallback - Use persistent data listener instead of once (clears timeout on first tile load) - Increase fallback timeout to 10s for PMTiles header + initial tile fetch - Add console.warn for map errors to aid debugging - Remove redundant style.load listener (fires immediately for inline styles) * feat(settings): add Map Tile Provider selector in settings Add dropdown in Settings → Map section to switch between: - Auto (PMTiles → OpenFreeMap fallback) - PMTiles (self-hosted) - OpenFreeMap - CARTO Choice persists in localStorage and reloads basemap instantly. * fix(map): make OSS-friendly — default to free OpenFreeMap, hide PMTiles when unconfigured - Default to OpenFreeMap when VITE_PMTILES_URL is unset (zero config for OSS users) - Hide PMTiles/Auto options from settings dropdown when no PMTiles URL configured - If user previously selected PMTiles but env var is removed, gracefully fall back - Remove production URL from .env.example to avoid exposing hosted tiles - Add docs link for self-hosting PMTiles in .env.example * docs: add map tile provider documentation to README and MAP_ENGINE.md Document the tile provider system (OpenFreeMap, CARTO, PMTiles) in MAP_ENGINE.md with self-hosting instructions, fallback behavior, and OSS-friendly defaults. Update README to reference tile providers in the feature list, tech stack, and environment variables table. * fix: resolve rebase conflicts and fix markdown lint errors - Restore OSS-friendly basemap defaults (MAP_PROVIDER_OPTIONS as IIFE, getMapProvider with hasTilesUrl check) - Fix markdown lint: add blank lines after ### headings in README - Reconcile UnifiedSettings import with MAP_PROVIDER_OPTIONS constant |
||
|
|
34d23c651d |
fix: force-clear stale SW on bundle 404 + swap basemap to OpenFreeMap (#1073)
* fix: auto-reload page when new service worker activates When a new SW takes control (after deploy), automatically reload the page so users get fresh HTML + correct bundle hashes. Prevents the one-time 404 on first load after deploy where old SW serves stale HTML. * fix: force-clear stale SW on bundle 404 + swap basemap to OpenFreeMap - Add inline script to index.html that detects 404s on /assets/ scripts, unregisters all service workers, clears all caches, and reloads once. Uses sessionStorage guard to prevent infinite reload loops. - Swap default basemap from Carto (CORS 403 blocking) to OpenFreeMap. Carto demoted to fallback. Attribution updated. - Add CSP hash for the new inline script. * fix: catch link preload 404s in stale SW detector Expand the inline error handler to detect both <script> and <link> (modulepreload) 404s on /assets/. Vite injects modulepreload links in <head> that fire errors before module scripts. |
||
|
|
fccfa79a29 |
fix: remove emrldco analytics and improve basemap fallback reliability (#1052)
- Remove emrldco.com analytics script and CSP entries from index.html, vercel.json, and tauri.conf.json - Replace setStyle() basemap fallback with full map recreation — setStyle() after a failed initial style load leaves MapLibre in a broken state - Add 403/Forbidden to error detection patterns for basemap failures - Scope fallback to pre-style-load errors only (post-load tile errors don't warrant destroying a working map) |
||
|
|
02f3fe77a9 |
feat: Arabic font support and HLS live streaming UI (#1020)
* feat: enhance support for HLS streams and update font styles * chore: add .vercelignore to exclude large local build artifacts from Vercel deploys * chore: include node types in tsconfig to fix server type errors on Vercel build * fix(middleware): guard optional variant OG lookup to satisfy strict TS * fix: desktop build and live channels handle null safety - scripts/build-sidecar-sebuf.mjs: Skip building removed [domain]/v1/[rpc].ts (removed in #785) - src/live-channels-window.ts: Add optional chaining for handle property to prevent null errors - src-tauri/Cargo.lock: Bump version to 2.5.24 Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix: address review issues on PR #1020 - Remove AGENTS.md (project guidelines belong to repo owner) - Restore tracking script in index.html (accidentally removed) - Revert tsconfig.json "node" types (leaks Node globals to frontend) - Add protocol validation to isHlsUrl() (security: block non-http URIs) - Revert Cargo.lock version bump (release management concern) * fix: address P2/P3 review findings - Preserve hlsUrl for HLS-only channels in refreshChannelInfo (was incorrectly clearing the stream URL on every refresh cycle) - Replace deprecated .substr() with .substring() - Extract duplicated HLS display name logic into getChannelDisplayName() --------- Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> Co-authored-by: Elie Habib <elie.habib@gmail.com> |
||
|
|
f83daf5cb3 |
fix(csp): add emrldco inline script hash to index.html CSP (#1014)
PR #1006 moved the emrldco analytics loader from <body> to <head> but didn't add its sha256 hash to the Content-Security-Policy script-src directive, causing the script to be blocked. |
||
|
|
fdbf208e8e | fix: move emrldco script from <body> to <head> (#1006) | ||
|
|
e771c3c6e0 |
feat: add emrldco analytics script with lazy loading (#1000)
Loads the script on window.load event so it never blocks initial render. CSP updated in both index.html and tauri.conf.json. |
||
|
|
30e6022959 | feat(mobile): full-viewport map with geolocation centering (#942) | ||
|
|
0a4a470114 |
fix(csp,runtime): add missing script hash and finance variant to remote hosts (#798)
- Add sha256-PnEBZii+iFaNE2EyXaJhRq34g6bdjRJxpLfJALdXYt8= to CSP script-src to resolve console violation on current builds - Add finance to DEFAULT_REMOTE_HOSTS so desktop Tauri builds resolve the correct API base URL without relying on the full fallback |
||
|
|
83cc35f1d6 |
fix(api): remove [domain] catch-all that intercepted all RPC routes (#753 regression) (#785)
Vercel routes dynamic [domain] segments BEFORE specific directory names, so api/[domain]/v1/[rpc].ts was catching every request meant for api/intelligence/v1/[rpc].ts, api/economic/v1/[rpc].ts, etc. and returning 404. Delete the catch-all so requests reach the real handlers. Also: add missing CSP script hash, add list-iran-events cache tier, and update route-cache-tier test to read from server/gateway.ts. |
||
|
|
31793ede03 |
harden: replace CSP unsafe-inline with script hashes and add trust signals (#781)
Remove 'unsafe-inline' from script-src in both index.html and vercel.json, replacing it with SHA-256 hashes of the two static inline theme-detection scripts. Add security.txt, sitemap.xml, and Sitemap directive in robots.txt to improve scanner reputation. Fix stale variant-metadata test that was reading vite.config.ts instead of the extracted variant-meta.ts module. |
||
|
|
c956b73470 |
feat: consolidate 4 Vercel deployments into 1 via runtime variant detection (#756)
Replace build-time VITE_VARIANT resolution with hostname-based detection for web deployments. A single build now serves all 4 variants (full, tech, finance, happy) via subdomain routing, eliminating 3 redundant Vercel projects and their build minutes. - Extract VARIANT_META into shared src/config/variant-meta.ts - Detect variant from hostname (tech./finance./happy. subdomains) - Preserve VITE_VARIANT env var for desktop builds and localhost dev - Add social bot OG responses in middleware for variant subdomains - Swap favicons and meta tags at runtime per resolved variant - Restrict localStorage variant reads to localhost/Tauri only |
||
|
|
f4a3ccb28c |
feat(country-brief): maximize mode, shareable URLs, expanded sections & i18n (#743)
* country deep dive * feat(country-brief): add maximize mode, shareable URLs, and expanded sections - Add maximize button that expands side panel to fullscreen overlay (960px centered) - URL state: ?country=IR&expanded=1 deep-links to maximized view - Expanded sections: full brief with citations, market volume bars, per-asset infrastructure lists, nearby ports, and 15 news items (vs 5 in side panel) - Click-outside-to-minimize, Escape key handling (maximize→minimize→close) - XSS-safe brief formatting: escapeHtml first, then controlled transforms - Focus trap filters hidden .cdp-expanded-only elements via offsetParent check - Extract getCountryCentroid to country-geometry.ts, remove duplicate helpers - Unify panel interface via CountryBriefPanel, remove instanceof checks - Remove classic CountryBriefPage toggle (always use deep-dive panel) - Migrate hardcoded strings to i18n (signal chips, component bars, labels) - Add 8 unit tests for expanded param URL round-trip --------- Co-authored-by: Elie Habib <elie.habib@gmail.com> |
||
|
|
aa94b0fd5e |
fix(csp): allow localhost in media-src for proxied HLS & remove CNN HLS (#711)
CSP media-src only allowed https: — blocked <video> from loading HLS streams through the sidecar proxy at http://127.0.0.1:PORT. Direct HLS channels (Sky, DW, Fox) use https:// CDN URLs and worked; proxied channels (CNBC, CNN) were silently blocked, falling back to YouTube. Also remove CNN from PROXIED_HLS_MAP — the upstream stream is wrong. |
||
|
|
36e36d8b57 |
Cost/traffic hardening, runtime fallback controls, and PostHog removal (#638)
- Remove PostHog analytics runtime and configuration - Add API rate limiting (api/_rate-limit.js) - Harden traffic controls across edge functions - Add runtime fallback controls and data-loader improvements - Add military base data scripts (fetch-mirta-bases, fetch-osm-bases) - Gitignore large raw data files - Settings playground prototypes |
||
|
|
84e39ba4b1 |
fix(desktop): enable click-to-play YouTube embeds + CISA feed fixes (#476)
* fix(tech): use rss() for CISA feed, drop build from pre-push hook
- CISA Advisories used dead rss.worldmonitor.app domain (404), switch to rss() helper
- Remove Vite build from pre-push hook (tsc already catches errors)
* fix(desktop): enable click-to-play for YouTube embeds in WKWebView
WKWebView blocks programmatic autoplay in cross-origin iframes regardless
of allow attributes, Permissions-Policy, mute-first retries, or secure
context. Documented all 10 approaches tested in docs/internal/.
Changes:
- Switch sidecar embed origin from 127.0.0.1 to localhost (secure context)
- Add MutationObserver + retry chain as best-effort autoplay attempts
- Use postMessage('*') to fix tauri://localhost cross-origin messaging
- Make sidecar play overlay non-interactive (pointer-events:none)
- Fix .webcam-iframe pointer-events:none blocking clicks in grid view
- Add expand button to grid cells for switching to single view on desktop
- Add http://localhost:* to CSP frame-src in index.html and tauri.conf.json
|
||
|
|
3bd501c4ce |
fix+feat: RSS feed repairs, HLS native playback, summarization cache fix, embed improvements (#452)
* fix(feeds): replace 25 dead/stale RSS URLs and add feed validation script - Replace 16 dead feeds (404/403/timeout) with working alternatives (Google News proxies or corrected direct RSS endpoints) - Replace 6 empty feeds with correct RSS paths (VnExpress, Tuoi Tre, Live Science, Greater Good, News24, ScienceDaily) - Replace 3 stale feeds (CNN World, TVN24, Layoffs.fyi) with active sources - Remove Disrupt Africa (inactive since Jan 2024) - Add scripts/validate-rss-feeds.mjs to check all 420 feeds - Add test:feeds npm script * feat(live-news): use stable CDN HLS feeds for desktop native playback Direct HLS feeds bypass YouTube's expiring tokenized URLs and iframe cookie issues on WKWebView. 10 channels (Sky, DW, France24, Euronews, Al Arabiya, Al Jazeera, CBS News, TRT World, Sky News Arabia, Al Hadath) now play via native <video> on desktop with automatic YouTube fallback when CDN feeds are down (5-min cooldown). Also: - Fix euronews handle typo (@euabortnews → @euronews) - Fix TRT World handle (@taborrtworld → @TRTWorld) - Add fallbackVideoId to CBS News, Sky News Arabia, TRT World - Extract hlsManifestUrl from YouTube API for non-mapped channels - Add sidecar /api/youtube-embed endpoint (auth-exempt for iframes) - Switch webcam/embed iframes from cloud to local sidecar origin - CSP: allow frame-src http://127.0.0.1:* for sidecar embeds - Remove legacy WEBKIT_FORCE_SANDBOX env var (deprecated in WebKitGTK) - Add 37 tests covering HLS map integrity, decision tree ordering, cooldown logic, race safety, service layer, sidecar endpoint, and CSP * fix(summarization): pass panelId as geoContext to prevent Redis cache key collision When breaking news appeared across multiple panels (World, US, Europe, Middle East), all panels generated identical cache keys because geoContext was always undefined. The first panel's summary was served to all others. * fix(desktop): sidecar embed autoplay, webcam fullscreen, optional channel fallbacks - Sidecar YouTube embed: use mute param (not hardcoded), add play overlay for WKWebView autoplay fallback, add postMessage bridge for play/pause/ mute/unmute commands matching the cloud embed handler - Webcam iframes: only set allowFullscreen on web to prevent grid-breaking fullscreen on desktop click - Optional channels: add fallbackVideoId + useFallbackOnly for livenow-fox, abc-news, nbc-news, wion so they play instead of showing "not currently live" - Tests: 9 new assertions covering mute param, postMessage bridge, play overlay, yt-ready message, and optional channel fallback coverage (46 total) |
||
|
|
3983278f53 |
feat: dynamic sidecar port with EADDRINUSE fallback + let scoping bug (#375)
* feat: dynamic sidecar port with EADDRINUSE fallback Rust probes port 46123 via TcpListener::bind; if busy, binds port 0 for an OS-assigned ephemeral port. The actual port is stored in LocalApiState, passed to sidecar via LOCAL_API_PORT env, and exposed to frontend via get_local_api_port IPC command. Frontend resolves the port lazily on first API call (with retry-on-failure semantics) and caches it. All hardcoded 46123 references replaced with dynamic getApiBaseUrl()/getLocalApiPort() accessors. CSP connect-src broadened to http://127.0.0.1:* (frame-src unchanged). * fix: scope CSP to desktop builds and eliminate port TOCTOU race P1: Remove http://127.0.0.1:* from index.html (web build CSP). The wildcard allowed web app JS to probe arbitrary localhost services. Vite's htmlVariantPlugin now injects localhost CSP only when VITE_DESKTOP_RUNTIME=1 (desktop builds). P2: Replace Rust probe_available_port() (bind→release→spawn race) with a confirmed port handshake. Sidecar now handles EADDRINUSE fallback internally and writes the actual bound port to a file. Rust polls the port file (up to 5s) to store only the confirmed port. * fix: isSafeUrl ReferenceError — addresses scoped inside try block `let addresses = []` was declared inside the outer `try` block but referenced after the `catch` on line 200. `let` is block-scoped so every request through isSafeUrl crashed with: ReferenceError: addresses is not defined Move the declaration before the `try` so it's in scope for the return. |
||
|
|
b1d835b69f |
feat: HappyMonitor — positive news dashboard (happy.worldmonitor.app) (#229)
* chore: add project config * docs: add domain research (stack, features, architecture, pitfalls) * docs: define v1 requirements * docs: create roadmap (9 phases) * docs(01): capture phase context * docs(state): record phase 1 context session * docs(01): research phase domain * docs(01): create phase plan * fix(01): revise plans based on checker feedback * feat(01-01): register happy variant in config system and build tooling - Add 'happy' to allowed stored variants in variant.ts - Create variants/happy.ts with panels, map layers, and VariantConfig - Add HAPPY_PANELS, HAPPY_MAP_LAYERS, HAPPY_MOBILE_MAP_LAYERS inline in panels.ts - Update ternary export chains to select happy config when SITE_VARIANT === 'happy' - Add happy entry to VARIANT_META in vite.config.ts - Add dev:happy and build:happy scripts to package.json Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(01-01): update index.html for variant detection, CSP, and Google Fonts - Add happy.worldmonitor.app to CSP frame-src directive - Extend inline script to detect variant from hostname (happy/tech/finance) and localStorage - Set data-variant attribute on html element before first paint to prevent FOUC - Add Google Fonts preconnect and Nunito stylesheet links - Add favicon variant path replacement in htmlVariantPlugin for non-full variants Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(01-01): create happy variant favicon assets - Create SVG globe favicon in sage green (#6B8F5E) and warm gold (#C4A35A) - Generate PNG favicons at all required sizes (16, 32, 180, 192, 512) - Generate favicon.ico with PNG-in-ICO wrapper - Create branded OG image (1200x630) with cream background, sage/gold scheme Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(01-01): complete variant registration plan - Create 01-01-SUMMARY.md documenting variant registration - Update STATE.md with plan 1 completion, metrics, decisions - Update ROADMAP.md with phase 01 progress (1/3 plans) - Mark INFRA-01, INFRA-02, INFRA-03 requirements complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(01-02): create happy variant CSS theme with warm palette and semantic overrides - Complete happy-theme.css with light mode (cream/sage), dark mode (navy/warm), and semantic colors - 179 lines covering all CSS custom properties: backgrounds, text, borders, overlays, map, panels - Nunito typography and 14px panel border radius for soft rounded aesthetic - Semantic colors remapped: gold (critical), sage (growth), blue (hope), pink (kindness) - Dark mode uses warm navy/sage tones, never pure black - Import added to main.css after panels.css Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(01-02): add happy variant skeleton shell overrides and theme-color meta - Inline skeleton styles for happy variant light mode (cream bg, Nunito font, sage dot, warm shimmer) - Inline skeleton styles for happy variant dark mode (navy bg, warm borders, sage tones) - Rounded corners (14px) on skeleton panels and map for soft aesthetic - Softer pill border-radius (8px) in happy variant - htmlVariantPlugin: theme-color meta updated to #FAFAF5 for happy variant mobile chrome Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(01-02): complete happy theme CSS plan - SUMMARY.md with execution results and self-check - STATE.md advanced to plan 2/3, decisions logged - ROADMAP.md progress updated (2/3 plans complete) - REQUIREMENTS.md: THEME-01, THEME-03, THEME-04 marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(01-03): create warm basemap styles and wire variant-aware map selection - Add happy-light.json: sage land, cream background, light blue ocean (forked from CARTO Voyager) - Add happy-dark.json: dark sage land, navy background, dark navy ocean (forked from CARTO Dark Matter) - Both styles preserve CARTO CDN source/sprite/glyph URLs for tile loading - DeckGLMap.ts selects happy basemap URLs when SITE_VARIANT is 'happy' Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(01-03): style panel chrome, empty states, and loading for happy variant - Panels get 14px rounded corners with subtle warm shadows - Panel titles use normal casing (no uppercase) for friendlier feel - Empty states (.panel-empty, .empty-state) show nature-themed sprout SVG icon - Loading radar animation softened to 3s rotation with sage-green glow - Status dots use gentle happy-pulse animation (2.5s ease-in-out) - Error states use warm gold tones instead of harsh red - Map controls, tabs, badges all get rounded corners - Severity badges use warm semantic colors - Download banner and posture radar adapted to warm theme Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(01-03): bridge SITE_VARIANT to data-variant attribute on <html> The CSS theme overrides rely on [data-variant="happy"] on the document root, but the inline script only detects variant from hostname/localStorage. This leaves local dev (VITE_VARIANT=happy) and Vercel deployments without the attribute set. Two fixes: 1. main.ts sets document.documentElement.dataset.variant from SITE_VARIANT 2. Vite htmlVariantPlugin injects build-time variant fallback into inline script Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(01-03): boost CSS specificity so happy theme wins over :root The happy-theme.css was imported before :root in main.css, and both [data-variant="happy"] and :root have equal specificity (0-1-0), so :root variables won after in the cascade. Fix by using :root[data-variant="happy"] (specificity 0-2-0) which always beats :root (0-1-0). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(01): fix CSS cascade — import happy-theme after main.css in main.ts The root cause: happy-theme.css was @imported inside main.css (line 4), which meant Vite loaded it BEFORE the :root block (line 9+). With equal specificity, the later :root variables always won. Fix: remove @import from main.css, import happy-theme.css directly in main.ts after main.css. This ensures cascade order is correct — happy theme variables come last and win. No !important needed. Also consolidated semantic color variables into the same selector blocks to reduce redundancy. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(01): fix CSS cascade with @layer base and theme toggle for happy variant - Wrap main.css in @layer base via base-layer.css so happy-theme.css (unlayered) always wins the cascade for custom properties - Remove duplicate <link> stylesheet from index.html (was double-loading) - Default happy variant to light theme (data-theme="light") so the theme toggle works on first click instead of requiring two clicks - Force build-time variant in inline script — stale localStorage can no longer override the deployment variant - Prioritize VITE_VARIANT env over localStorage in variant.ts so variant-specific builds are deterministic Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(01-03): complete map basemap & panel chrome plan — Phase 1 done - Add 01-03-SUMMARY.md with task commits, deviations, and self-check - Update STATE.md: Phase 1 complete, advance to ready for Phase 2 - Update ROADMAP.md: mark Phase 1 plans 3/3 complete - Update REQUIREMENTS.md: mark THEME-02 and THEME-05 complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-01): complete phase execution * docs(phase-02): research curated content pipeline * docs(02): create phase plan — curated content pipeline * feat(02-01): add positive RSS feeds for happy variant - Add HAPPY_FEEDS record with 8 feeds across 5 categories (positive, science, nature, health, inspiring) - Update FEEDS export ternary to route happy variant to HAPPY_FEEDS - Add happy source tiers to SOURCE_TIERS (Tier 2 for main sources, Tier 3 for category feeds) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(02-01): extend GDELT with tone filtering and positive topic queries - Add tone_filter (field 4) and sort (field 5) to SearchGdeltDocumentsRequest proto - Regenerate TypeScript client/server types via buf generate - Handler appends toneFilter to GDELT query string, uses req.sort for sort param - Add POSITIVE_GDELT_TOPICS array with 5 positive topic queries - Add fetchPositiveGdeltArticles() with tone>5 and ToneDesc defaults - Add fetchPositiveTopicIntelligence() and fetchAllPositiveTopicIntelligence() helpers - Existing fetchGdeltArticles() backward compatible (empty toneFilter/sort = no change) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(02-01): complete positive feeds & GDELT tone filtering plan - Create 02-01-SUMMARY.md with execution results - Update STATE.md: phase 2, plan 1 of 2, decisions, metrics - Update ROADMAP.md: phase 02 progress (1/2 plans) - Mark FEED-01 and FEED-03 requirements complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(02-02): add positive content classifier and extend NewsItem type - Create positive-classifier.ts with 6 content categories (science-health, nature-wildlife, humanity-kindness, innovation-tech, climate-wins, culture-community) - Source-based pre-mapping for GNN category feeds (fast path) - Priority-ordered keyword classification for general positive feeds (slow path) - Add happyCategory optional field to NewsItem interface - Export HAPPY_CATEGORY_LABELS and HAPPY_CATEGORY_ALL for downstream UI use Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore(02-02): clean up happy variant config and verify feed wiring - Remove dead FEEDS placeholder from happy.ts (now handled by HAPPY_FEEDS in feeds.ts) - Remove unused Feed type import - Verified SOURCE_TIERS has all 8 happy feed entries (Tier 2: GNN/Positive.News/RTBC/Optimist, Tier 3: GNN category feeds) - Verified FEEDS export routes to HAPPY_FEEDS when SITE_VARIANT=happy - Verified App.ts loadNews() dynamically iterates FEEDS keys - Happy variant builds successfully Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(02-02): complete content category classifier plan - SUMMARY.md documenting classifier implementation and feed wiring cleanup - STATE.md updated: Phase 2 complete, 5 total plans done, 56% progress - ROADMAP.md updated: Phase 02 marked complete (2/2 plans) - REQUIREMENTS.md: FEED-04 marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(02-03): create gap closure plan for classifier wiring * feat(02-03): wire classifyNewsItem into happy variant news ingestion - Import classifyNewsItem from positive-classifier service - Add classification step in loadNewsCategory() after fetchCategoryFeeds - Guard with SITE_VARIANT === 'happy' to avoid impact on other variants - In-place mutation via for..of loop sets happyCategory on every NewsItem Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(02-03): complete classifier wiring gap closure plan - Add 02-03-SUMMARY.md documenting classifier wiring completion - Update STATE.md with plan 3/3 position and decisions - Update ROADMAP.md with completed plan checkboxes - Include 02-VERIFICATION.md phase verification document Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-2): complete phase execution * test(02): complete UAT - 1 passed, 1 blocker diagnosed Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-3): research positive news feed & quality pipeline Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(03): create phase plan for positive news feed and quality pipeline * fix(03): revise plans based on checker feedback * feat(03-02): add imageUrl to NewsItem and extract images from RSS - Add optional imageUrl field to NewsItem interface - Add extractImageUrl() helper to rss.ts with 4-strategy image extraction (media:content, media:thumbnail, enclosure, img-in-description) - Wire image extraction into fetchFeed() for happy variant only * feat(03-01): add happy variant guards to all App.ts code paths - Skip DEFCON/PizzInt indicator for happy variant - Add happy variant link (sun icon) to variant switcher header - Show 'Good News Map' title for happy variant map section - Skip LiveNewsPanel, LiveWebcams, TechEvents, ServiceStatus, TechReadiness, MacroSignals, ETFFlows, Stablecoin panels for happy - Gate live-news first-position logic with happy exclusion - Only load 'news' data for happy variant (skip markets, predictions, pizzint, fred, oil, spending, intelligence, military layers) - Only schedule 'news' refresh interval for happy (skip all geopolitical/financial refreshes) - Add happy-specific search modal with positive placeholder and no military/geopolitical sources Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(03-02): create PositiveNewsFeedPanel with filter bar and card rendering - New PositiveNewsFeedPanel component extending Panel with: - Category filter bar (All + 6 positive categories) - Rich card rendering with image, title, source, category badge, time - Filter state preserved across data refreshes - Proper cleanup in destroy() - Add CSS styles to happy-theme.css for cards and filter bar - Category-specific badge colors using theme variables - Scoped under [data-variant="happy"] to avoid affecting other variants * feat(03-01): return empty channels for happy variant in LiveNewsPanel - Defense-in-depth: LIVE_CHANNELS returns empty array for happy variant - Ensures zero Bloomberg/war streams even if panel is somehow instantiated - Combined with createPanels() guard from Task 1 for belt-and-suspenders safety Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(03-02): complete positive news feed panel plan - Created 03-02-SUMMARY.md with execution results - Updated STATE.md with position, decisions, and metrics - Updated ROADMAP.md with phase 03 progress (2/3 plans) - Marked NEWS-01, NEWS-02 requirements as complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(03-01): complete Happy Variant App.ts Integration plan - SUMMARY.md with execution results and decisions - STATE.md updated with 03-01 decisions and session info - ROADMAP.md progress updated (2/3 phase 3 plans) - NEWS-03 requirement marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(03-03): create sentiment gate service for ML-based filtering - Exports filterBySentiment() wrapping mlWorker.classifySentiment() - Default threshold 0.85 with localStorage override for tuning - Graceful degradation: returns all items if ML unavailable - Batches titles at 20 items per call (ML_THRESHOLDS.maxTextsPerBatch) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(03-03): wire multi-stage quality pipeline and positive-feed panel into App.ts - Register 'positive-feed' in HAPPY_PANELS replacing 'live-news' - Import PositiveNewsFeedPanel, filterBySentiment, fetchAllPositiveTopicIntelligence - Add positivePanel + happyAllItems class properties - Create PositiveNewsFeedPanel in createPanels() for happy variant - Accumulate curated items in loadNewsCategory() for happy variant - Implement loadHappySupplementaryAndRender() 4-stage pipeline: 1. Curated feeds render immediately (non-blocking UX) 2. GDELT positive articles fetched as supplementary 3. Sentiment-filtered via DistilBERT-SST2 (filterBySentiment) 4. Merged + sorted by date, re-rendered - Auto-refresh on REFRESH_INTERVALS.feeds re-runs full pipeline - ML failure degrades gracefully to curated-only display Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(03-03): complete quality pipeline plan - phase 3 done - Summary: multi-stage positive news pipeline with ML sentiment gate - STATE.md: phase 3 complete (3/3), 89% progress - ROADMAP.md: phase 03 marked complete - REQUIREMENTS.md: FEED-02, FEED-05 marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(03): wire positive-feed panel key in panels.ts and add happy map layer/legend config The executor updated happy.ts but the actual HAPPY_PANELS export comes from panels.ts — it still had 'live-news' instead of 'positive-feed', so the panel never rendered. Also adds happyLayers (natural only) and happy legend to Map.ts to hide military layer toggles and geopolitical legend items. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-3): complete phase execution * docs(phase-4): research global map & positive events Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(04): create phase plan — global map & positive events * fix(04): revise plans based on checker feedback * feat(04-01): add positiveEvents and kindness keys to MapLayers interface and all variant configs - Add positiveEvents and kindness boolean keys to MapLayers interface - Update all 10 variant layer configs (8 in panels.ts + 2 in happy.ts) - Happy variant: positiveEvents=true, kindness=true; all others: false - Fix variant config files (full, tech, finance) and e2e harnesses for compilation Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(04-01): add happy variant layer toggles and legend in DeckGLMap - Add happy branch to createLayerToggles with 3 toggles: Positive Events, Acts of Kindness, Natural Events - Add happy branch to createLegend with 4 items: Positive Event (green), Breakthrough (gold), Act of Kindness (light green), Natural Event (orange) - Non-happy variants unchanged Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(04-01): complete map layer config & happy variant toggles plan Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(04-02): add positive events geocoding pipeline and map layer - Proto service PositiveEventsService with ListPositiveGeoEvents RPC - Server-side GDELT GEO fetch with positive topic queries, dedup, classification - Client-side service calling server RPC + RSS geocoding via inferGeoHubsFromTitle - DeckGLMap green/gold ScatterplotLayer with pulse animation for significant events - Tooltip shows event name, category, and report count - Routes registered in api gateway and vite dev server Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(04-02): wire positive events loading into App.ts happy variant pipeline - Import fetchPositiveGeoEvents and geocodePositiveNewsItems - Load positive events in loadAllData() for happy variant with positiveEvents toggle - loadPositiveEvents() merges GDELT GEO RPC + geocoded RSS items, deduplicates by name - loadDataForLayer switch case for toggling positiveEvents layer on/off - MapContainer.setPositiveEvents() delegates to DeckGLMap Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(04-02): complete positive events geocoding pipeline plan - SUMMARY.md with task commits, decisions, deviations - STATE.md updated with position, metrics, decisions - ROADMAP.md and REQUIREMENTS.md updated Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(04-03): create kindness-data service with baseline generator and curated events - Add KindnessPoint interface for map visualization data - Add MAJOR_CITIES constant with ~60 cities worldwide (population-weighted) - Implement generateBaselineKindness() producing 50-80 synthetic points per cycle - Implement extractKindnessEvents() for real kindness items from curated news - Export fetchKindnessData() merging baseline + real events * feat(04-03): add kindness layer to DeckGLMap and wire into App.ts pipeline - Add createKindnessLayers() with solid green fill + gentle pulse ring for real events - Add kindness-layer tooltip showing city name and description - Add setKindnessData() setter in DeckGLMap and MapContainer - Wire loadKindnessData() into App.ts loadAllData and loadDataForLayer - Kindness layer gated by mapLayers.kindness toggle (happy variant only) - Pulse animation triggers when real kindness events are present * docs(04-03): complete kindness data pipeline & map layer plan - Create 04-03-SUMMARY.md documenting kindness layer implementation - Update STATE.md: phase 04 complete (3/3 plans), advance position - Update ROADMAP.md: phase 04 marked complete - Mark KIND-01 and KIND-02 requirements as complete * docs(phase-4): complete phase execution * docs(phase-5): research humanity data panels domain Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(05-humanity-data-panels): create phase plan * feat(05-01): create humanity counters service with metric definitions and rate calculations - Define 6 positive global metrics with annual totals from UN/WHO/World Bank/UNESCO - Calculate per-second rates from annual totals / 31,536,000 seconds - Absolute-time getCounterValue() avoids drift across tabs/throttling - Locale-aware formatCounterValue() using Intl.NumberFormat * feat(05-02): install papaparse and create progress data service - Install papaparse + @types/papaparse for potential OWID CSV fallback - Create src/services/progress-data.ts with 4 World Bank indicators - Export PROGRESS_INDICATORS (life expectancy, literacy, child mortality, poverty) - Export fetchProgressData() using existing getIndicatorData() RPC - Null value filtering, year sorting, invertTrend-aware change calculation Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(05-01): create CountersPanel component with 60fps animated ticking numbers - Extend Panel base class with counters-grid of 6 counter cards - requestAnimationFrame loop updates all values at 60fps - Absolute-time calculation via getCounterValue() prevents drift - textContent updates (not innerHTML) avoid layout thrashing - startTicking() / destroy() lifecycle methods for App.ts integration * feat(05-02): create ProgressChartsPanel with D3.js area charts - Extend Panel base class with id 'progress', title 'Human Progress' - Render 4 stacked D3 area charts (life expectancy, literacy, child mortality, poverty) - Warm happy-theme colors: sage green, soft blue, warm gold, muted rose - d3.area() with curveMonotoneX for smooth filled curves - Header with label, change badge (e.g., "+58.0% since 1960"), and unit - Hover tooltip with bisector-based nearest data point detection - ResizeObserver with 200ms debounce for responsive re-rendering - Clean destroy() lifecycle with observer disconnection Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(05-01): complete ticking counters service & panel plan - SUMMARY.md with execution results and self-check - STATE.md updated to phase 5, plan 1/3 - ROADMAP.md progress updated - Requirements COUNT-01, COUNT-02, COUNT-03 marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(05-02): complete progress charts panel plan - Create 05-02-SUMMARY.md with execution results - Update STATE.md: plan 2/3, decisions, metrics - Update ROADMAP.md: phase 05 progress (2/3 plans) - Mark PROG-01, PROG-02, PROG-03 complete in REQUIREMENTS.md Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(05-03): wire CountersPanel and ProgressChartsPanel into App.ts lifecycle - Import CountersPanel, ProgressChartsPanel, and fetchProgressData - Add class properties for both new panels - Instantiate both panels in createPanels() gated by SITE_VARIANT === 'happy' - Add progress data loading task in refreshAll() for happy variant - Add loadProgressData() private method calling fetchProgressData + setData - Add destroy() cleanup for both panels (stops rAF loop and ResizeObserver) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(05-03): add counter and progress chart CSS styles to happy-theme.css - Counters grid: responsive 3-column layout (3/2/1 at 900px/500px breakpoints) - Counter cards: hover lift, tabular-nums for jitter-free 60fps updates - Counter icon/value/label/source typography hierarchy - Progress chart containers: stacked with border dividers - Chart header with label, badge, and unit display - D3 SVG axis styling (tick text fill, domain stroke) - Hover tooltip with absolute positioning and shadow - Dark mode adjustments for card hover shadow and tooltip shadow - All selectors scoped under [data-variant='happy'] Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(05-03): complete panel wiring & CSS plan - Create 05-03-SUMMARY.md with execution results - Update STATE.md: phase 5 complete (3/3 plans), decisions, metrics - Update ROADMAP.md: phase 05 progress (3/3 summaries, Complete) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-5): complete phase execution * docs(06): research phase 6 content spotlight panels * docs(phase-6): create phase plan * feat(06-01): add science RSS feeds and BreakthroughsTickerPanel - Expand HAPPY_FEEDS.science from 1 to 5 feeds (ScienceDaily, Nature News, Live Science, New Scientist) - Create BreakthroughsTickerPanel extending Panel with horizontal scrolling ticker - Doubled content rendering for seamless infinite CSS scroll animation - Sanitized HTML output using escapeHtml/sanitizeUrl Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(06-01): create HeroSpotlightPanel with photo, map location, and hero card - Create HeroSpotlightPanel extending Panel for daily hero spotlight - Render hero card with image, source, title, time, and optional map button - Conditionally show "Show on map" button only when both lat and lon exist - Expose onLocationRequest callback for App.ts map integration wiring - Sanitized HTML output using escapeHtml/sanitizeUrl Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(06-02): add GoodThingsDigestPanel with progressive AI summarization - Panel extends Panel base class with id 'digest', title '5 Good Things' - Renders numbered story cards with titles immediately (progressive rendering) - Summarizes each story in parallel via generateSummary() with Promise.allSettled - AbortController cancels in-flight summaries on re-render or destroy - Graceful fallback to truncated title on summarization failure - Passes [title, source] to satisfy generateSummary's 2-headline minimum Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(06-02): complete Good Things Digest Panel plan Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(06-01): complete content spotlight panels plan - Add 06-01-SUMMARY.md with execution results - Update STATE.md with position, decisions, metrics - Update ROADMAP.md and REQUIREMENTS.md progress Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(06-03): wire Phase 6 panels into App.ts lifecycle and update happy.ts config - Import and instantiate BreakthroughsTickerPanel, HeroSpotlightPanel, GoodThingsDigestPanel in createPanels() - Wire heroPanel.onLocationRequest callback to map.setCenter + map.flashLocation - Distribute data to all three panels after content pipeline in loadHappySupplementaryAndRender() - Add destroy calls for all three panels in App.destroy() - Add digest key to DEFAULT_PANELS in happy.ts config Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(06-03): add CSS styles for ticker, hero card, and digest panels - Add happy-ticker-scroll keyframe animation for infinite horizontal scroll - Add breakthroughs ticker styles (wrapper, track, items with hover pause) - Add hero spotlight card styles (image, body, source, title, location button) - Add digest list styles (numbered cards, titles, sources, progressive summaries) - Add dark mode overrides for all three panel types - All selectors scoped under [data-variant="happy"] Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(06-03): complete panel wiring & CSS plan - Create 06-03-SUMMARY.md with execution results - Update STATE.md: phase 6 complete, 18 plans done, 78% progress - Update ROADMAP.md: phase 06 marked complete (3/3 plans) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-6): complete phase execution * docs(07): research conservation & energy trackers phase * docs(07-conservation-energy-trackers): create phase plan * feat(07-02): add renewable energy data service - Fetch World Bank EG.ELC.RNEW.ZS indicator (IEA-sourced) for global + 7 regions - Return global percentage, historical time-series, and regional breakdown - Graceful degradation: individual region failures skipped, complete failure returns zeroed data - Follow proven progress-data.ts pattern for getIndicatorData() RPC usage Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(07-01): add conservation wins dataset and data service - Create conservation-wins.json with 10 species recovery stories and population timelines - Create conservation-data.ts with SpeciesRecovery interface and fetchConservationWins() loader - Species data sourced from USFWS, IUCN, NOAA, WWF, and other published reports * feat(07-02): add RenewableEnergyPanel with D3 arc gauge and regional breakdown - Animated D3 arc gauge showing global renewable electricity % with 1.5s easeCubicOut - Historical trend sparkline using d3.area() + curveMonotoneX below gauge - Regional breakdown with horizontal bars sorted by percentage descending - All colors use getCSSColor() for theme-aware rendering - Empty state handling when no data available Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(07-01): add SpeciesComebackPanel with D3 sparklines and species cards - Create SpeciesComebackPanel extending Panel base class - Render species cards with photo (lazy loading + error fallback), info badges, D3 sparkline, and summary - D3 sparklines use area + line with curveMonotoneX and viewBox for responsive sizing - Recovery status badges (recovered/recovering/stabilized) and IUCN category badges - Population values formatted with Intl.NumberFormat for readability * docs(07-02): complete renewable energy panel plan - SUMMARY.md with task commits, decisions, self-check - STATE.md updated to phase 7 plan 2, 83% progress - ROADMAP.md phase 07 progress updated - REQUIREMENTS.md: ENERGY-01, ENERGY-02, ENERGY-03 marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(07-01): complete species comeback panel plan Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(07-03): wire species and renewable panels into App.ts lifecycle - Add imports for SpeciesComebackPanel, RenewableEnergyPanel, and data services - Add class properties for speciesPanel and renewablePanel - Instantiate both panels in createPanels() gated by SITE_VARIANT === 'happy' - Add loadSpeciesData() and loadRenewableData() tasks in refreshAll() - Add destroy cleanup for both panels before map cleanup - Add species and renewable entries to happy.ts DEFAULT_PANELS config * feat(07-03): add CSS styles for species cards and renewable energy gauge - Species card grid layout with 2-column responsive grid - Photo, info, badges (recovered/recovering/stabilized/IUCN), sparkline, summary styles - Renewable energy gauge section, historical sparkline, and regional bar chart styles - Dark mode overrides for species card hover shadow and IUCN badge background - All styles scoped with [data-variant='happy'] using existing CSS variables * docs(07-03): complete panel wiring & CSS plan Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(happy): add missing panel entries and RSS proxy for dev mode HAPPY_PANELS in panels.ts was missing digest, species, and renewable entries — panels were constructed but never appended to the grid because the panelOrder loop only iterated the 6 original keys. Also adds RSS proxy middleware for Vite dev server, fixes sebuf route regex to match hyphenated domains (positive-events), and adds happy feed domains to the rss-proxy allowlist. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: progress data lookup, ticker speed, ultrawide layout gap 1. Progress/renewable data: World Bank API returns countryiso3code "WLD" for world aggregate, but services were looking up by request code "1W". Changed lookups to use "WLD". 2. Breakthroughs ticker: slowed animation from 30s to 60s duration. 3. Ultrawide layout (>2000px): replaced float-based layout with CSS grid. Map stays in left column (60%), panels grid in right column (40%). Eliminates dead space under the map where panels used to wrap below. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: UI polish — counter overflow, ticker speed, monitors panel, filter tabs - Counter values: responsive font-size with clamp(), overflow protection, tighter card padding to prevent large numbers from overflowing - Breakthroughs ticker: slowed from 60s to 120s animation duration - My Monitors panel: gate monitors from panel order in happy variant (was unconditionally pushed into panelOrder regardless of variant) - Filter tabs: smaller padding/font, flex-shrink:0, fade mask on right edge to hint at scrollable overflow Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(happy): exclude APT groups layer from happy variant map The APT groups layer (cyber threat actors like Fancy Bear, Cozy Bear) was only excluded for the tech variant. Now also excluded for happy, since cyber threat data has no place on a Good News Map. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(happy-map): labeled markers, remove fake baseline, fix APT leak - Positive events now show category emoji + location name as colored text labels (TextLayer) instead of bare dots. Labels filter by zoom level to avoid clutter at global view. - Removed synthetic kindness baseline (50-80 fake "Volunteers at work" dots in random cities). Only real kindness events from news remain. - Kindness events also get labeled dots with headlines. - Improved tooltips with proper category names and source counts. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(happy-map): disable earthquakes, fix GDELT query syntax - Disable natural events layer (earthquakes) for happy variant — not positive news - Fix GDELT GEO positive queries: OR terms require parentheses per GDELT API syntax, added third query for charity/volunteer news - Updated both desktop and mobile happy map layer configs Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(happy): ultrawide grid overflow, panel text polish Ultrawide: set min-height:0 on map/panels grid children so they respect 1fr row constraint and scroll independently instead of pushing content below the viewport. Panel CSS: softer word-break on counters, line-clamp on digest and species summaries, ticker title max-width, consistent text-dim color instead of opacity hacks. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(08-map-data-overlays): research phase domain Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(08-map-data-overlays): create phase plan * Add Global Giving Activity Index with multi-platform aggregation (#255) * feat(08-01): add static data for happiness scores, renewable installations, and recovery zones - Create world-happiness.json with 152 country scores from WHR 2025 - Create renewable-installations.json with 92 global entries (solar/wind/hydro/geothermal) - Extend conservation-wins.json with recoveryZone lat/lon for all 10 species * feat(08-01): add service loaders, extend MapLayers with happiness/species/energy keys - Create happiness-data.ts with fetchHappinessScores() returning Map<ISO2, score> - Create renewable-installations.ts with fetchRenewableInstallations() returning typed array - Extend SpeciesRecovery interface with optional recoveryZone field - Add happiness, speciesRecovery, renewableInstallations to MapLayers interface - Update all 8 variant MapLayers configs (happiness=true in happy, false elsewhere) - Update e2e harness files with new layer keys * docs(08-01): complete data foundation plan summary and state updates - Create 08-01-SUMMARY.md with execution results - Update STATE.md to phase 8, plan 1/2 - Update ROADMAP.md progress for phase 08 - Mark requirements MAP-03, MAP-04, MAP-05 complete * feat(08-02): add happiness choropleth, species recovery, and renewable installation overlay layers - Add three Deck.gl layer creation methods with color-coded rendering - Add public data setters for happiness scores, species recovery zones, and renewable installations - Wire layers into buildLayers() gated by MapLayers keys - Add tooltip cases for all three new layer types - Extend happy variant layer toggles (World Happiness, Species Recovery, Clean Energy) - Extend happy variant legend with choropleth, species, and renewable entries - Cache country GeoJSON reference in loadCountryBoundaries() for choropleth reuse Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(08-02): wire MapContainer delegation and App.ts data loading for map overlays - Add MapContainer delegation methods for happiness, species recovery, and renewable installations - Add happiness scores and renewable installations map data loading in App.ts refreshAll() - Chain species recovery zone data to map from existing loadSpeciesData() - All three overlay datasets flow from App.ts through MapContainer to DeckGLMap Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(08-02): complete map overlay layers plan - Create 08-02-SUMMARY.md with execution results - Update STATE.md: phase 8 complete (2/2 plans), 22 total plans, decisions logged - Update ROADMAP.md: phase 08 marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-8): complete phase execution * docs(roadmap): add Phase 7.1 gap closure for renewable energy installation & coal data Addresses Phase 7 verification gaps (ENERGY-01, ENERGY-03): renewable panel lacks solar/wind installation growth and coal plant closure visualizations. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(7.1): research renewable energy installation & coal retirement data * docs(71): create phase plans for renewable energy installation & coal retirement data * feat(71-01): add GetEnergyCapacity RPC proto and server handler - Create get_energy_capacity.proto with request/response messages - Add GetEnergyCapacity RPC to EconomicService in service.proto - Implement server handler with EIA capability API integration - Coal code fallback (COL -> BIT/SUB/LIG/RC) for sub-type support - Redis cache with 24h TTL for annual capacity data - Register handler in economic service handler Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(71-01): add client-side fetchEnergyCapacity with circuit breaker - Add GetEnergyCapacityResponse import and capacityBreaker to economic service - Export fetchEnergyCapacityRpc() with energyEia feature gating - Add CapacitySeries/CapacityDataPoint types to renewable-energy-data.ts - Export fetchEnergyCapacity() that transforms proto types to domain types Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(71-01): complete EIA energy capacity data pipeline plan Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(71-02): add setCapacityData() with D3 stacked area chart to RenewableEnergyPanel - setCapacityData() renders D3 stacked area (solar yellow + wind blue) with coal decline (red) - Chart labeled 'US Installed Capacity (EIA)' with compact inline legend - Appends below existing gauge/sparkline/regions without replacing content - CSS styles for capacity section, header, legend in happy-theme.css Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(71-02): wire EIA capacity data loading in App.ts loadRenewableData() - Import fetchEnergyCapacity from renewable-energy-data service - Call fetchEnergyCapacity() after World Bank gauge data, pass to setCapacityData() - Wrapped in try/catch so EIA failure does not break existing gauge Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(71-02): complete EIA capacity visualization plan - SUMMARY.md documenting D3 stacked area chart implementation - STATE.md updated: Phase 7.1 complete (2/2 plans), progress 100% - ROADMAP.md updated with plan progress Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-71): complete phase execution * docs(phase-09): research sharing, TV mode & polish domain Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(09): create phase plan for sharing, TV mode & polish * docs(phase-09): plan Sharing, TV Mode & Polish 3 plans in 2 waves covering share cards (Canvas 2D renderer), TV/ambient mode (fullscreen panel cycling + CSS particles), and celebration animations (canvas-confetti milestones). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(09-01): create Canvas 2D renderer for happy share cards - 1080x1080 branded PNG with warm gradient per category - Category badge, headline word-wrap, source, date, HappyMonitor branding - shareHappyCard() with Web Share API -> clipboard -> download fallback - wrapText() helper for Canvas 2D manual line breaking Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(09-02): create TvModeController and TV mode CSS - TvModeController class manages fullscreen, panel cycling with configurable 30s-2min interval - CSS [data-tv-mode] attribute drives larger typography, hidden interactive elements, smooth panel transitions - Ambient floating particles (CSS-only, opacity 0.04) with reduced motion support - TV exit button appears on hover, hidden by default outside TV mode Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(09-02): wire TV mode into App.ts header and lifecycle - TV mode button with monitor icon in happy variant header - TV exit button at page level, visible on hover in TV mode - Shift+T keyboard shortcut toggles TV mode - TvModeController instantiated lazily on first toggle - Proper cleanup in destroy() method Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(09-01): add share button to positive news cards with handler - Share button (SVG upload icon) appears on card hover, top-right - Delegated click handler prevents link navigation, calls shareHappyCard - Brief .shared visual feedback (green, scale) for 1.5s on click - Dark mode support for share button background - Fix: tv-mode.ts panelKeys index guard (pre-existing build blocker) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(09-02): complete TV Mode plan - SUMMARY.md with task commits, deviations, decisions - STATE.md updated: position, metrics, decisions, session - ROADMAP.md updated: phase 09 progress (2/3 plans) - REQUIREMENTS.md updated: TV-01, TV-02, TV-03 marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(09-01): complete positive news share cards plan - SUMMARY.md with Canvas 2D renderer and share button accomplishments - STATE.md updated with decisions and session continuity - ROADMAP.md progress updated (2/3 plans in phase 09) - REQUIREMENTS.md: SHARE-01, SHARE-02, SHARE-03 marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(09-03): add celebration service with canvas-confetti - Install canvas-confetti + @types/canvas-confetti - Create src/services/celebration.ts with warm nature-inspired palette - Session-level dedup (Set<string>) prevents repeat celebrations - Respects prefers-reduced-motion media query - Milestone detection for species recovery + renewable energy records - Moderate particle counts (40-80) for "warm, not birthday party" feel Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(09-03): wire milestone celebrations into App.ts data pipelines - Import checkMilestones in App.ts - Call checkMilestones after species data loads with recovery statuses - Call checkMilestones after renewable energy data loads with global percentage - All celebration calls gated behind SITE_VARIANT === 'happy' - Placed after panel setData() so data is visible before confetti fires Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(09-03): complete celebration animations plan - 09-03-SUMMARY.md with execution results - STATE.md updated: phase 09 complete, 26 plans total, 100% progress - ROADMAP.md updated with phase 09 completion - REQUIREMENTS.md: THEME-06 marked complete Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-09): complete phase execution * fix(happy): remove natural events layer from happy variant Natural events (earthquakes, volcanoes, storms) were leaking into the happy variant through stale localStorage and the layer toggle UI. Force all non-happy layers off regardless of localStorage state, and remove the natural events toggle from both DeckGL and SVG map layer configs. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(phase-7.1): complete phase execution — mark all phases done Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(v1): complete milestone audit — 49/49 requirements satisfied Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(happy): close audit tech debt — map layer defaults, theme-color meta - Enable speciesRecovery and renewableInstallations layers by default in HAPPY_MAP_LAYERS (panels.ts + happy.ts) so MAP-04/MAP-05 are visible on first load - Use happy-specific theme-color meta values (#FAFAF5 light, #1A2332 dark) in setTheme() and applyStoredTheme() instead of generic colors Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: add checkpoint for giving integration handoff Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(giving): integrate Global Giving Activity Index from PR #254 Cherry-pick the giving feature that was left behind when PR #255 batch-merged without including #254's proto/handler/panel files. Adds: - Proto definitions (GivingService, GivingSummary, PlatformGiving, etc.) - Server handler: GoFundMe/GlobalGiving/JustGiving/crypto/OECD aggregation - Client service with circuit breaker - GivingPanel with tabs (platforms, categories, crypto, institutional) - Full wiring: API routes, vite dev server, data freshness, panel config - Happy variant panel config entry Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(giving): move panel init and data fetch out of full-variant-only blocks The GivingPanel was instantiated inside `if (SITE_VARIANT === 'full')` and the data fetch was inside `loadIntelligenceSignals()` (also full-only). Moved both to variant-agnostic scope so the panel works on happy variant. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(giving): bypass debounced setContent so tab buttons are clickable Panel.setContent() is debounced (150ms), so event listeners attached immediately after it were binding to DOM elements that got replaced by the deferred innerHTML write. Write directly to this.content.innerHTML like other interactive panels do. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: remove .planning/ from repo and gitignore it Planning files served their purpose during happy monitor development. They remain on disk for reference but no longer tracked. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: merge new panels into saved panelSettings so they aren't hidden When panelSettings is loaded from localStorage, any panels added since the user last saved settings would be missing from the config. The applyPanelSettings loop wouldn't touch them, but without a config entry they also wouldn't appear in the settings toggle UI correctly. Now merges DEFAULT_PANELS entries into loaded settings for any keys that don't exist yet, so new panels are visible by default. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: giving data baselines, theme toggle persistence, and client caching - Replace broken GoFundMe (301→404) and GlobalGiving (401) API calls with hardcoded baselines from published annual reports. Activity index rises from 42 to 56 as all 3 platforms now report non-zero volumes. - Fix happy variant theme toggle not persisting across page reloads: applyStoredTheme() couldn't distinguish "no preference" from "user chose dark" — both returned DEFAULT_THEME. Now checks raw localStorage. - Fix inline script in index.html not setting data-theme="dark" for happy variant, causing CSS :root[data-variant="happy"] (light) to win over :root[data-variant="happy"][data-theme="dark"]. - Add client-side caching to giving service: persistCache on circuit breaker, 30min in-memory TTL, and request deduplication. - Add Playwright E2E tests for theme toggle (8 tests, all passing). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * perf: add persistent cache to all 29 circuit breakers across 19 services Enable persistCache and set appropriate cacheTtlMs on every circuit breaker that lacked them. Data survives page reloads via IndexedDB fallback and reduces redundant API calls on navigation. TTLs matched to data freshness: 5min for real-time feeds (weather, earthquakes, wildfires, aviation), 10min for event data (conflict, cyber, unrest, climate, research), 15-30min for slow-moving data (economic indicators, energy capacity, population exposure). Market quotes breaker intentionally left at cacheTtlMs: 0 (real-time). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: expand map labels progressively as user zooms in Labels now show more text at higher zoom levels instead of always truncating at 30 chars. Zoom <3: 20 chars, <5: 35, <7: 60, 7+: full. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: keep 30-char baseline for map labels, expand to full text at zoom 6+ Previous change was too aggressive with low-zoom truncation (20 chars). Now keeps original 30-char limit at global view, progressively expands to 50/80/200 chars as user zooms in. Also scales font size with zoom. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Revert "fix: keep 30-char baseline for map labels, expand to full text at zoom 6+" This reverts commit 33b8a8accc2d48acd45f3dcea97a083b8bcebbf0. * Revert "feat: expand map labels progressively as user zooms in" This reverts commit 285f91fe471925ca445243ae5d8ac37723f2eda7. * perf: stale-while-revalidate for instant page load Circuit breaker now returns stale cached data immediately and refreshes in the background, instead of blocking on API calls when cache exceeds TTL. Also persists happyAllItems to IndexedDB so Hero, Digest, and Breakthroughs panels render instantly from cache on page reload. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: address PR #229 review — 4 issues from koala 1. P1: Fix duplicate event listeners in PositiveNewsFeedPanel.renderCards() — remove listener before re-adding to prevent stacking on re-renders 2. P1: Fix TV mode cycling hidden panels causing blank screen — filter out user-disabled panels from cycle list, rebuild keys on toggle 3. P2: Fix positive classifier false positives for short keywords — "ai" and "art" now use space-delimited matching to avoid substring hits (e.g. "aid", "rain", "said", "start", "part") 4. P3: Fix CSP blocking Google Fonts stylesheet for Nunito — add https://fonts.googleapis.com to style-src directive Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: decompose App.ts into focused modules under src/app/ Break the 4,597-line monolithic App class into 7 focused modules plus a ~460-line thin orchestrator. Each module implements the AppModule lifecycle (init/destroy) and communicates via a shared AppContext state object with narrow callback interfaces — no circular dependencies. Modules extracted: - app-context.ts: shared state types (AppContext, AppModule, etc.) - desktop-updater.ts: desktop version checking + update badge - country-intel.ts: country briefs, timeline, CII signals - search-manager.ts: search modal, result routing, index updates - refresh-scheduler.ts: periodic data refresh with jitter/backoff - panel-layout.ts: panel creation, grid layout, drag-drop - data-loader.ts: all 36 data loading methods - event-handlers.ts: DOM events, shortcuts, idle detection, URL sync Verified: tsc --noEmit (zero errors), all 3 variant builds pass (full, tech, finance), runtime smoke test confirms no regressions. * fix: resolve test failures and missing CSS token from PR review 1. flushStaleRefreshes test now reads from refresh-scheduler.ts (moved during App.ts modularization) 2. e2e runtime tests updated to import DesktopUpdater and DataLoaderManager instead of App.prototype for resolveUpdateDownloadUrl and loadMarkets 3. Add --semantic-positive CSS variable to main.css and happy-theme.css (both light and dark variants) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: hide happy variant button from other variants The button is only visible when already on the happy variant. This allows merging the modularized App.ts without exposing the unfinished happy layout to users — layout work continues in a follow-up PR. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Elie Habib <elie.habib@gmail.com> |
||
|
|
d24d61f333 |
Fix Linux rendering issues and improve monospace font fallbacks (#243)
* fix: resolve AppImage blank white screen and font crash on Linux (#238) Disable WebKitGTK DMA-BUF renderer by default on Linux to prevent blank white screens caused by GPU buffer allocation failures (common with NVIDIA drivers and immutable distros like Bazzite). Add Linux-native monospace font fallbacks (DejaVu Sans Mono, Liberation Mono) to all font stacks so WebKitGTK font resolution doesn't hit out-of-bounds vector access when macOS-only fonts (SF Mono, Monaco) are unavailable. https://claude.ai/code/session_01TF2NPgSSjgenmLT2XuR5b9 * fix: consolidate monospace font stacks into --font-mono variable - Define --font-mono in :root (main.css) and .settings-shell (settings-window.css) - Align font stack: SF Mono, Monaco, Cascadia Code, Fira Code, DejaVu Sans Mono, Liberation Mono - Replace 3 hardcoded JetBrains Mono stacks with var(--font-mono) - Replace 4 hardcoded settings-window stacks with var(--font-mono) - Fix pre-existing bug: var(--font-mono) used in 4 places but never defined - Match index.html skeleton font stack to --font-mono --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
e1b9e9e8a9 | fix(csp): allow PostHog scripts from us-assets.i.posthog.com | ||
|
|
2473c4bfd4 |
feat: pre-render critical CSS skeleton in index.html for instant perceived load
Inline a minimal HTML skeleton (header bar, map placeholder, panels grid) with critical CSS directly in index.html so the page shows a structured layout immediately instead of a blank screen while JavaScript boots. - Dark theme skeleton with hardcoded colors matching CSS variables - Light theme support via [data-theme="light"] selectors - Shimmer animation on placeholder lines for visual feedback - 6 skeleton panels in a responsive grid matching the real layout - Map section with radial gradient matching the map background - Skeleton is automatically replaced when App.renderLayout() sets innerHTML - Marked aria-hidden="true" for screen reader accessibility Expected gain: perceived load time drops to <0.5s. https://claude.ai/code/session_01Fxk8GMRn2cEUq3ThC2a8e5 |
||
|
|
116fc80fc7 |
Merge remote-tracking branch 'origin/main' into feature/finance-variant
# Conflicts: # index.html # src/components/DeckGLMap.ts |
||
|
|
ed9cc922e2 | Fix finance variant runtime resiliency and API pressure | ||
|
|
db5eff4300 |
feat(04-01): add no-transition class lifecycle for FOUC prevention
- index.html and settings.html FOUC scripts add no-transition class to <html> - src/main.ts removes no-transition after first paint via requestAnimationFrame - src/settings-main.ts removes no-transition after first paint via requestAnimationFrame - Prevents transition sweep from dark-to-light on page load while enabling smooth theme toggles Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
14f7d856cd |
feat(02-01): add FOUC prevention scripts and wire entry points
- Add inline FOUC prevention script to index.html and settings.html <head> - Update CSP script-src to allow 'unsafe-inline' for FOUC prevention - Import and call applyStoredTheme() in src/main.ts before App init - Import and call applyStoredTheme() in src/settings-main.ts before loadDesktopSecrets Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
a9224254a5 |
fix: security hardening — CORS, auth bypass, origin validation & bump v2.2.7
- Tighten CORS regex to block worldmonitorEVIL.vercel.app spoofing - Move sidecar /api/local-env-update behind token auth + add key allowlist - Add postMessage origin/source validation in LiveNewsPanel - Replace postMessage wildcard '*' targetOrigin with specific origin - Add isDisallowedOrigin() check to 25 API endpoints missing it - Migrate gdelt-geo & EIA from custom CORS to shared _cors.js - Add CORS to firms-fires, stock-index, youtube/live endpoints - Tighten youtube/embed.js ALLOWED_ORIGINS regex - Remove 'unsafe-inline' from CSP script-src - Add iframe sandbox attribute to YouTube embed - Validate meta-tags URL query params with regex allowlist |
||
|
|
4a7f9bfdf4 |
Allow Cloudflare Insights script in CSP
Add https://static.cloudflareinsights.com to script-src directive to prevent CSP blocking of Cloudflare Web Analytics beacon. |
||
|
|
2c2a6dfbc3 |
Fix YouTube CSP, add devtools menu, improve desktop channel switching
- Add worldmonitor.app to frame-src CSP in index.html (was only in tauri.conf.json, causing iframe block) - Add devtools feature and Help > Toggle Developer Tools menu item - Try native YouTube JS API first, fall back to cloud bridge on Error 153 - Add pause-then-play workaround for WKWebView channel switching |
||
|
|
c353cf2070 |
Reduce egress costs, add PWA support, fix Polymarket and Railway relay
Egress optimization: - Add s-maxage + stale-while-revalidate to all API endpoints for Vercel CDN caching - Add vercel.json with immutable caching for hashed assets - Add gzip compression to sidecar responses >1KB - Add gzip to Railway RSS responses (4 paths previously uncompressed) - Increase polling intervals: markets/crypto 60s→120s, ETF/macro/stablecoins 60s→180s - Remove hardcoded Railway URL from theater-posture.js (now env-var only) PWA / Service Worker: - Add vite-plugin-pwa with autoUpdate strategy - Cache map tiles (CacheFirst), fonts (StaleWhileRevalidate), static assets - NetworkOnly for all /api/* routes (real-time data must be fresh) - Manual SW registration (web only, skip Tauri) - Add offline fallback page - Replace manual manifest with plugin-generated manifest Polymarket fix: - Route dev proxy through production Vercel (bypasses JA3 blocking) - Add 4th fallback tier: production URL as absolute fallback Desktop/Sidecar: - Dual-backend cache (_upstash-cache.js): Redis cloud + in-memory+file desktop - Settings window OK/Cancel redesign - Runtime config and secret injection improvements |